<template>
    <navigation :title="title" :back-url="backUrl"></navigation>
    <view class="contentBox">
        <!-- 仓库信息 - 仓库、存储区 -->
        <warehousing-info ref="warehousingInfoRef" :warehouseInfo="warehouseInfo"
            :pathParams="{ ...pathParams, type: pathParams.type === 'my' ? 'my' : 'stockIn' }" />
        <!-- 物料列表 - 添加物料 -->
        <material-list ref="materialRef" :formData="formData" isEdit="1"
            :backStr="pathParams.type === 'my' ? 'my' : 'stockIn'" :pathParams="pathParams" />
        <!-- 底部操作栏 -->
        <view class="bottom">
            <uv-button @tap="scanCode">扫码添加</uv-button>
            <uv-button type="primary" @tap="submitForm">提交</uv-button>
        </view>
    </view>
</template>

<script setup>

import _ from 'lodash';
import { ref } from 'vue';
import { objectToQuery } from '../../until';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { addStockIn, stockInUpdate } from '@/api/stockIn';
import { getMaterialUnique } from '@/api/uniqueCode';
import MaterialList from '../../components/MaterialList.vue';
import WarehousingInfo from '../../components/WarehousingInfo.vue';
import Navigation from '../../components/Navigation.vue';
const OPERATE_CONFIG = {
    // 创建
    list: {
        back: 'pages/warehousing/index',
        title: '入库单开单'
    },
    // 编辑/入库
    stockIn: {
        back: '/pages/warehousing/stockIn/components/detail',
        title: ''
    },
    // 
    declaration: {
        back: '/pages/warehousing/Declaration/components/detail',
        title: ''
    },
    // 
    my: {
        back: '/pages/warehousing/Declaration/components/detail',
        title: ''
    },
}
// 数据：路径参数
const pathParams = ref('')
// 标志：是否为编辑
const isEdit = ref('')

// ref：标题
const title = ref('')
const backUrl = ref('')

// ref：物料绑定
const materialRef = ref([])
// ref：仓库信息绑定
const warehousingInfoRef = ref([])

// 数据：物料列表
const formData = ref([{ remark: '', material: [] }])
// 数据：仓库信息
const warehouseInfo = ref({ warehousing: {}, storageArea: {}, remark: '' })

// 数据：获取缓存信息
const getMaterialList = () => {
    // 仓库信息
    const warehouse = uni.getStorageSync('app_warehousing');
    warehouseInfo.value.warehousing = warehouse

    // 存储区信息
    const storageArea = uni.getStorageSync('app_storageArea');
    warehouseInfo.value.storageArea = storageArea

    // 物料信息
    const material = uni.getStorageSync('app_material');
    formData.value.material = material

    // 入库单备注
    const billRemark = uni.getStorageSync('app_billRemark');
    warehouseInfo.value.remark = billRemark
}
getMaterialList();
const scanResult = ref('')
// 扫码添加
const scanCode = () => {
    // 先校验是否支持扫码
    uni.scanCode({
        scanType: ['qrCode', 'barCode'], // 支持二维码 + 条形码
        success: (res) => {
            scanResult.value = res.result;
            if (res.result) {
                getMaterialUnique({ code: res.result }).then((response) => {
                    console.log('物料内容：', response);
                    if (`${response.code}` === '200') {
                        const material = uni.getStorageSync('app_material');
                        // 处理物料信息 合并
                        const materialInfo = _.filter(material, { isDelete: '0' });
                        console.log('materialInfo', materialInfo);
                        const materialId = response.data?.[0]?.materialId;
                        console.log('materialId', materialId);
                        const idx = _.findIndex(materialInfo, (i) => i.materialId ? i.materialId == materialId : i.id == materialId);
                        console.log('已选中是否有重复数据', idx);

                        if (idx != -1) {
                            uni.showToast({
                                title: '该物料已添加，请勿重复添加！',
                                mask: true,
                                icon: 'none',
                            })
                        } else {
                            let _material = [...materialInfo, { ...response.data[0], uniqueCode: res.result }]
                            console.log('新的物料数组', _material);
                            formData.value.material = _material
                            uni.setStorageSync('app_material', formData.value.material)
                        }
                    } else {
                        console.log(response.code, 'response.code');
                    }


                })
            }
        },
        fail: () => {
            uni.showToast({ title: '扫码失败', icon: 'none' });
        }
    });
};

// 提交表单
const submitForm = () => {
    const info = warehousingInfoRef.value.getWarehousingInfo()
    const materialInfo = materialRef.value.getMaterialList() || []

    let params = {
        warehouseCode: info?.warehousing?.[0]?.deptCode || info?.warehousing?.[0]?.deptId,
        warehouseName: info?.warehousing?.[0]?.deptName,
        areaCode: info?.storageArea?.[0]?.deptCode || info.storageArea?.[0]?.deptId,
        areaName: info?.storageArea?.[0]?.deptName,
        remark: info?.remark,
        billRemark: info?.remark,
        itemList: _.map(materialInfo, (i) => ({ ...i.material }))
    }
    try {
        if (!isEdit.value) {
            // 新增
            addStockIn(params).then((res) => {
                if (res.code == 200) {
                    uni.showToast({ title: '入库单创建成功', icon: 'success', mask: true })
                    if (pathParams.value.type == 'my') {
                        const queryStr = objectToQuery(pathParams.value)
                        uni.navigateTo({ url: OPERATE_CONFIG.my.back + queryStr })
                    } else {
                        uni.navigateTo({ url: OPERATE_CONFIG.list.back })

                    }
                }
            })
        } else {
            // 编辑
            params.billNo = pathParams.value?.billNo;
            params.billId = pathParams.value?.billId;
            const queryStr = objectToQuery(pathParams.value)
            stockInUpdate(params).then((res) => {
                if (res.code == 200) {
                    uni.showToast({ title: '入库单编辑成功', icon: 'success', mask: true })
                    uni.navigateTo({ url: OPERATE_CONFIG.stockIn.back + queryStr })
                }
            })
        }
    } catch (err) {
        console.error('提交失败：', err)
        uni.showToast({ title: '提交失败', icon: 'none' })
    }
}

// 数据：路径参数
onLoad((options) => {
    pathParams.value = options
    console.log('options==>', options);

    //  若有billNo传入 修改标题且为编辑 stockIn:入库编辑  stockIn-putAway：入库单入库编辑 
    if (options?.billNo && options?.type != 'my') {
        const query = objectToQuery(options)
        title.value = options.billNo
        backUrl.value = OPERATE_CONFIG.stockIn.back + query;
        isEdit.value = true
    } else {
        isEdit.value = false
        title.value = OPERATE_CONFIG.list.title;
        backUrl.value = OPERATE_CONFIG.list.back;
    }

})

</script>

<style lang="scss" scoped>
.contentBox {
    background: #f5f5f5;
    min-height: 100vh;
}

/* 底部按钮 */
::v-deep .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;
    }

    .uv-button--info {
        background-color: #07c160;
        color: #fff;

    }
}
</style>