<template>
    <!-- 自定义导航栏 -->
    <navigation :title="pathParams.billNo" :back-url="backUrl">
        <template #right>
            <view class="right-btn flex align-center justify-center ">
                <uv-image @tap="onPrinter" src="../../../../static/printer.png" width="20px" height="20px"
                    style="margin-top:10rpx" />
                <uv-image @tap="toEditOrAway('2')" src="../../../../static/edit.png" class="ml-24" width="20px"
                    height="20px" style="margin-top:10rpx" />
            </view>
        </template>
    </navigation>
    <view class="contentBox">
        <!-- 详情信息 -->
        <detail-info :type="pathParams.value?.type" :detailInfo="detailInfo" />

        <!-- 底部按钮 -->
        <view v-if="detailInfo?.billType == '0' && !flag"
            :class="getBillType(detailInfo?.billType, detailInfo?.status) != '物料部分入库' ? 'bottom' : 'bottom1'">
            <uv-button type="error" v-if="getBillType(detailInfo?.billType, detailInfo?.status, flag) != '物料部分入库'"
                text="作废" @tap="toObsolete"></uv-button>
            <uv-button type="primary" text="入库单入库" @tap="toEditOrAway('1')"></uv-button>
        </view>
        <view v-if="detailInfo?.billType == '0' && flag" class="bottom1">
            <uv-button type="primary" text="出库单出库" @tap="toEditOrAway('1')"></uv-button>
        </view>
    </view>
</template>
<script setup>
import _ from 'lodash';
import { ref, computed } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import { objectToQuery, getBillType } from '../../../until';

import { stockOutDetail } from '@/api/stockOut';
import { stockInDetail, inboundBillVoid } from '@/api/stockIn';
import { BASE_URL } from '@/api/request';

import DetailInfo from '../../../components/DetailInfo.vue';
import Navigation from '../../../components/Navigation.vue';
// ref:返回路径
const backUrl = ref('')
// 数据：路径参数
const pathParams = ref('')
// 数据：详情
const detailInfo = ref('')
// type
const OPERATE_CONFIG = {
    // url:入库/出库 地址  back：导航栏返回地址  editUrl：编辑地址
    stockIn: {// 入库单开单
        type: 'stockIn',
        url: '/pages/warehousing/stockOut/components/outAway',
        back: '/pages/warehousing/stockIn/my',
        editUrl: '/pages/warehousing/stockIn/create',
    },
    stockIn_inbound: { // 入库单入库
        type: 'stockIn_inbound',
        url: '/pages/warehousing/stockIn/components/inbound',
        back: '/pages/warehousing/stockIn/putAway',
        editUrl: '/pages/warehousing/stockIn/create',
    },
    stockOut: {    // 出库单开单
        type: 'stockOut',
        url: '/pages/warehousing/stockOut/components/outAway',
        back: '/pages/warehousing/stockOut/my',
        editUrl: '/pages/warehousing/stockOut/create',
    },
    stockOut_outAway: {   // 出库单入库
        type: 'stockOut_outAway',
        url: '/pages/warehousing/stockOut/components/outAway',
        back: '/pages/warehousing/stockOut/outbound',
        editUrl: '/pages/warehousing/stockOut/create',
    },
}
const flag = computed(() => _.includes(pathParams.value.type, 'stockIn') ? 0 : 1)
// 打印
const onPrinter = () => {
    uni.downloadFile({
        url: BASE_URL + (flag.value == 1 ? '/worn/outboundBill/print/' : '/worn/inboundBill/print/') + detailInfo.value?.billId,
        header:{
            authorization: uni.getStorageSync("app_token"),
        },
        success: (res) => {
            let filePath = res.tempFilePath
            uni.openDocument({
                filePath: filePath,
            });
        }
    })
}

// 获取详情 - 将isDelete写入
const getDetailInfo = () => {
    if (flag.value == 1) {
        stockOutDetail({ billNo: pathParams.value.billNo }).then((res) => {
            detailInfo.value = res.data
        })
    } else {
        stockInDetail({ billNo: pathParams.value.billNo }).then((res) => {
            detailInfo.value = res.data
        })
    }

}

const toObsolete = () => {
    inboundBillVoid({
        billNo: pathParams.value?.billNo,
        billType: '5'
    }).then((res) => {
        uni.navigateTo({
            url: `/pages/warehousing/stockIn/my`
        });

    })
}
/**
 * 详情信息存入本地缓存
 * @param {any} type - 类型标识，控制物料存储逻辑
 */
const setDetailInfoToStorage = (type) => {
    const data = detailInfo.value || {}
    //  仓库信息
    uni.setStorageSync('app_warehousing', [{
        deptName: data.warehouseName || '',
        deptCode: data.warehouseCode || ''
    }])
    //  库区信息
    uni.setStorageSync('app_storageArea', [{
        deptName: data.areaName || '',
        deptCode: data.areaCode || ''
    }])
    //  单据备注
    uni.setStorageSync('app_billRemark', data.billRemark || '')
    // 物料列表
    const itemList = data.itemList || []
    if (!type) {
        // 无 type：筛选出状态=0 的数据，分两组
        const material = _.filter(itemList, i => i?.uniqueCode && i.status === '0')
        const materialSelectList = _.filter(itemList, i => !i?.uniqueCode && i.status === '0')

        uni.setStorageSync('app_material', material)
        uni.setStorageSync('app_material_select_list', materialSelectList)
    } else {
        // 有 type：直接存储全部 itemList
        uni.setStorageSync('app_material', itemList)
    }

    // 技术鉴定表
    const technicalEvaluationList = {
        fileList: data?.appraisalFileList,
        remark: data?.appraisalRemark,
        createTime: data?.appraisalTime,
        id: data?.appraisalId,
        appraisalNo: data?.appraisalNo,
    }
    uni.setStorageSync('app_technical', technicalEvaluationList)
}

/**
 * 路径跳转操作 入库、出库、编辑
 * @param {any} type - 类型标识，1 出入库操作   2 编辑
 */
const toEditOrAway = (key) => {
    const config = flag.value ? OPERATE_CONFIG.stockOut_outAway : OPERATE_CONFIG.stockIn_inbound;   // 获取配置（flag 区分入库/出库）
    console.log(config, 'config===>');

    const queryParams = { ...pathParams.value, type: config.type } // 拼接路径参数
    const queryStr = objectToQuery(queryParams)
    const targetUrl = key === '1' ? config.url : config.editUrl // 区分跳转：操作 / 编辑
    setDetailInfoToStorage(key === '1' ? flag.value : undefined)// 存储数据
    uni.navigateTo({
        url: targetUrl + queryStr
    }).catch(err => {
        console.error('页面跳转失败：', err)
    })
}
// 接收路径参数
onLoad((options) => {
    if (!options.billNo) {
        uni.showToast({ title: '参数错误,无唯一码ID', icon: 'none' })
        return
    }
    pathParams.value = options
    const query = objectToQuery(pathParams.value)
    backUrl.value = OPERATE_CONFIG?.[pathParams.value.type]?.back + `${query}`
    getDetailInfo()
})

</script>
<style scoped lang="scss">
// 底部按钮
.bottom {
    position: fixed;
    bottom: 0;
    height: 60rpx;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;

    .uv-button-wrapper {
        width: 50%;
        border-radius: 0;
    }
}

.bottom1 {
    position: fixed;
    bottom: 0;
    height: 60rpx;
    font-size: 14px;
    display: flex;
    align-items: center;
    // justify-content: center;
    width: 100%;

    .uv-button-wrapper {
        width: 100%;
        border-radius: 0;
    }
}
</style>