// package-basic-data/pages/test/add/add.js
const mixins = require('@/mixins/index.js')
const util = require('@/utils/util.js')
const app = getApp()
const Constants = require('@/utils/Constants');
Page({
    mixins: [mixins],
    /**
     * 页面的初始数据
     */
    data: {
        purIdArray: '', //来源单id 
        // 弹出按钮
        buttonList: [{
            name: 'merge',
            title: mixins.$t("save"), //'保存'
        }],
        contentList: [{
            code: 'flag',
            title: mixins.$t("antoHandle"), //'自动入库办理',
            type: 'checkbox'
        }, {
            code: 'need',
            title: mixins.$t("totalAmount"), //'合计金额',
            type: 'str'
        }, {
            code: 'amount',
            content: 0,
            type: 'number'
        }],
        btnFormData: null,
        popContent: [{
                code: 'itemQty',
                type: 'step',
                title: mixins.$t("count"), //'数量',
                required: true
            },
            {
                code: 'whId',
                name: 'whName',
                title: mixins.$t("warehouseId"), //'仓库',
                type: 'drop',
                dropType: 'warehouse',
                required: true
            },
            {
                code: 'skuSpec',
                title: mixins.$t("goodSpec"), //'规格',
                type: 'str',
                readonly: true,
            },
            {
                code: 'nonStdCode',
                title: mixins.$t("goodsBatch"), //'商品批次',
                type: 'str',
            },
        ],

        cardList: [{
                name: 'main',
            }, {
                name: 'wh'
            }, {
                name: 'relation'
            },
            {
                name: 'items',
                title: mixins.$t("goodsDetail"), //'商品明细',
                info: '(' + mixins.$t("warehousingProcessing") + ')',
                color: '#E4002B',
                displayNum: 2
            }, {
                name: 'other',
                title: mixins.$t("otherInfo"), // '其他信息'
            }
        ],
        contentObj: {
            main: [{
                    code: 'supId',
                    name: 'supplierName',
                    title: mixins.$t("supplier"), //'供应商',
                    type: 'choose',
                    required: true,
                    urlKey: 'chooseSupplier'
                },
                {
                    code: 'staffId',
                    name: 'staffName',
                    title: mixins.$t("procureStaff"), //'采购人',
                    type: 'choose',
                    required: true,
                    urlKey: 'chooseStaff'
                }, {
                    code: 'orgId',
                    name: 'orgName',
                    title: mixins.$t("procureOrg"), //'采购部门',
                    type: 'choose',
                    required: true,
                    urlKey: 'chooseOrg'
                },
            ],
            wh: [{
                code: 'whId',
                name: 'whName',
                type: 'choose',
                required: true,
                title: mixins.$t("enterWhName"), //'入库仓库',
                urlKey: 'chooseWh'
            }],
            relation: [{
                code: 'sourceNo',
                name: 'fromNo',
                type: 'choose',
                controlChooseFlag: true,
                title: mixins.$t("sourceOrder"), //'关联源单',
                urlKey: 'choosePurchaseOrder'
            }],
            items: [ ], 
            other: [{
                code: 'remarks',
                type: 'textarea',
                title: mixins.$t("remarks"), //'备注',
                readonly: false
            }, {
                code: 'file',
                type: 'uploader',
                title: mixins.$t("uploader"), //'附件'
            }]
        },
        // 路由
        routeObjName: 'inbound',
        //接口
        purchaseService: app.globalData['purchaseService'], //采购订单 路由
        inboundProcessingService: app.globalData['inboundProcessingService'],
    },
    /**
     * @desc : 选择框右边删除 回调
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    clear(e) {
        let code = e.detail.code
        let formData = JSON.parse(this.data.formData)
        if (code == "sourceNo") { //来源单号
            let contentList_ = this.data.contentList
            let cardList = this.data.cardList
            formData.goodsList = []
            contentList_.forEach(card => {
                if (card.code === 'amount') {
                    card.content = 0
                }
            })
            cardList.forEach(card => {
                if (card.name === 'items') {
                    card.itemAmt = 0
                }
            })
            this.setData({
                contentList: contentList_,
                cardList,
                chooseVisible: false,
            })
        }
        this.setData({
            formData: JSON.stringify(formData)
        })
    },
    /**
     * @desc   : 绑定数据
     * @author : 王英杰
     * @date   : 2024年3月12日
     */
    chooseData(e) {
        console.log("t", e, this.data.formData);
        let formData = JSON.parse(this.data.formData)
        let code = e.detail.code
        let data = e.detail.data.data
        if (code == "supId") { //供应商
            formData.supId = data.id
            formData.supplierName = data.name
        }
        if (code == "staffId") { //员工
            formData.staffId = data.id
            formData.staffName = data.name
        }
        if (code == "orgId") { //员工
            formData.orgId = data.id
            formData.orgName = data.name
        }
        if (code == "whId") { //仓库
            formData.whId = data.id
            formData.whName = data.name
            if(formData.goodsList){
                formData.goodsList.forEach(element => { //总单的入库仓库 作为一个总开关 直接改变 所以品的仓库
                    element.whId = data.id
                    element.whName = data.whName
                });
            }
       
        }
        if (code == "sourceNo") { //来源单  
           
            this.calculateTotal(data.chooosepurchaseItemResponseList) 

            return
        }

        this.setData({
            formData: JSON.stringify(formData)
        })
    },
    /**
     * @desc : 给表单赋值
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    setValuesByEdit(data) {
        { //是否可编辑逻辑
            if (data.fromId) { //有来源单据
                this.setData({ //隐藏选商品按钮
                    chooseVisible: true
                })
                if (this.data.isSysSetting) { //系统参数为自动办理
                    if (this.data.nopay) { //未付款
                        data.goodsList.forEach(element => {
                            // （添加商品、修改数量不能超出订单商品范围）添加商品TODO(后期改为跳入来源单据让他选择原单数据回来)
                            element['itemQty_max'] = element.purItemQty - element.purItemIntoingQty - element.purItemIntoQty + element.intoQty
                        });
                   
                    } else { //已付款 (只可以编辑备注和附件)
                        this.setData({
                            readonly: true
                        })
                    }
                } else { //系统参数为手动办理
                    if (data.intoStatus = Constants.intoStatus.inBounding) { //入库中 可以编辑修改商品、数量（修改商品、数量不能超出订单商品范围）和备注附件
                        data.goodsList.forEach(element => {
                            // （添加商品、修改数量不能超出订单商品范围）添加商品TODO(后期改为跳入来源单据让他选择原单数据回来)
                            element['itemQty_max'] = element.purItemQty - element.purItemIntoingQty - element.purItemIntoQty + element.intoQty
                        });
                    } else { //已入库（未付款、已付款），只可以编辑备注、附件
                        this.setData({
                            readonly: true
                        })
                    } 
                }
            } else { //无来源单据
                if (this.data.isSysSetting) { //系统参数为自动办理  
                    if (this.data.nopay) { //已入库（未付款），可以编辑修改数量（修改商品、数量不限制，数量改大时要校验库存量）和备注附件； 
                    data.goodsList.forEach(element => {  //  设置库存量未最大值
                        element['itemQty_max'] = element.invQty
                    });
                    } else { //已付款 (只可以编辑备注和附件)
                        this.setData({
                            readonly: true
                        })
                    }
                } else { //系统参数为手动办理
                    if (data.intoStatus = Constants.intoStatus.inBounded) { //已入库
                        if(this.data.nopay){ //（未付款），可以编辑修改数量（修改商品、数量不限制，数量改大时要校验库存量）和备注附件 
                          data.goodsList.forEach(element => {  //  设置库存量未最大值
                            element['itemQty_max'] = element.invQty
                        });
                        }else{//已付款 (只可以编辑备注和附件)
                            this.setData({
                                readonly: true
                            }) 
                        } 
                    } 
                }
            }
        } 
        let purIdArray_ = this.data.purIdArray //来源单id
        let cardList_ = this.data.cardList
        let contentList_ = this.data.contentList //底部按钮上的合计金额

        // 提取purNo字段为数组，并去重
        const purNoArray = [...new Set(data.goodsList.map(item => item.purNo))];
        const purIdArray = [...new Set(data.goodsList.map(item => item.purId))]
        // 将数组元素转换为逗号分隔的字符串
        data.fromNo = purNoArray.join(','); //来源单号
        purIdArray_ = purIdArray.join(',');

        data.goodsList.forEach(element => {
            element.itemAmt = element.intoingAmt * element.intoingQty
            element.itemQty = element.intoingQty
        });
        cardList_.forEach(card => { //循环出商品总共价格 展示用
            if (card.name === 'items') {
                card.itemAmt = data.goodsList.sum("itemAmt")
            }
        })
        contentList_.forEach(card => { //底部按钮 展示价格 用
            if (card.code === 'amount') {
                card.content = data.goodsList.sum("itemAmt")
            }
        })
           // 刷新商品明细 显示 查看更多
    let card = this.data.cardList.filter(it => it.name == 'items');
    this.selectComponent('#'+this.data.formName).handleContentObj(card[0])

        this.setData({
            contentList: contentList_,
            purIdArray: purIdArray_,
            cardList: cardList_,
            formData: JSON.stringify(data)
        })
    },
    /**
     * @desc :处理商品(选择采购订单处理)
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    calculateTotal(choooseItemList) {
        let formData = JSON.parse(this.data.formData)
        let purIdArray_ = this.data.purIdArray //来源单id
        let cardList_ = this.data.cardList
        let contentList_ = this.data.contentList //底部按钮上的合计金额
        let contentObj_ = this.data.contentObj
        formData.goodsList = choooseItemList
        // 提取purNo字段为数组，并去重
        const purNoArray = [...new Set(formData.goodsList.map(item => item.purNo))];
        const purIdArray = [...new Set(formData.goodsList.map(item => item.purId))]
        // 将数组元素转换为逗号分隔的字符串
        formData.fromNo = purNoArray.join(','); //来源单号
        purIdArray_ = purIdArray.join(',');
    
        formData.goodsList.forEach(element => {
            element.intoingAmt = element.itemAmt
            element.intoingQty = element.itemQty
            element.sumAmt = element.itemQty * element.itemAmt
            element.costPrice = element.pricePur
            element.costAmt = element.itemAmt
            element.fromId = element.purId
            element.fromItemId = element.itemId
            element.priceInto = element.pricePur
            element.nonStdCode = element.nonStdCode ? element.nonStdCode : '' // 色号  批次号 
            element.outQty = 0
            delete element.opAppCode
            delete element.opCreateTime
            delete element.opCreateUserId
            delete element.opDbUser
            delete element.opTimestamp
            delete element.opUpdateTime
            delete element.opUpdateUserId
        });
        cardList_.forEach(card => { //循环出商品总共价格 展示用
            if (card.name === 'items') {
                card.itemAmt = formData.goodsList.sum("sumAmt")
            }
        })
        contentList_.forEach(card => { //底部按钮 展示价格 用
            if (card.code === 'amount') {
                card.content = formData.goodsList.sum("sumAmt")
            }
        }) 
            contentObj_["relation"].forEach(element => {
               if(element.code == "sourceNo"){ //来源单号
                element.purNo = purNoArray.join(',')
                element.chooseList =  formData.goodsList
               }
            }); 
        this.setData({
            contentList: contentList_,
            purIdArray: purIdArray_,
            cardList: cardList_,
            contentObj:contentObj_,
            formData: JSON.stringify(formData)
        })
    },
    /**
     * @desc : 外露设置产品方法 
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    setGoods(e) {
        let contentList_ = this.data.contentList
        let cardList = this.data.cardList
        let formData = JSON.parse(this.data.formData)
        let totalAmout = Number(0)
        // 各个明细的金额数量
        formData.goodsList.forEach(element => { //循环出商品总共价格 
            element.intoingAmt = element.pricePurchase * element.itemQty
            element.intoingQty = element.itemQty
            element.pricePur = element.pricePurchase
            element.priceInto = element.pricePurchase
            element.intoAmt = 0 //  已入库金额
            element.intoQty = 0 //  已入库数量
            totalAmout += Number(element.pricePurchase * element.itemQty)
        })
        // 左下角的合计金额
        contentList_.forEach(card => {
            if (card.code === 'amount') {
                card.content = totalAmout
            }
        })
        // 明细的合计金额
        cardList.forEach(card => { //循环出商品总共价格
            if (card.name === 'items') {
                //合计金额
                card.itemAmt = totalAmout
            }
        })
        console.log(formData.goodsList);
        this.setData({
            contentList: contentList_,
            cardList,
            formData: JSON.stringify(formData)
        })
    },
    /**
     * @desc : 保存数据服务--校验
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    validData() { 
        let formData = JSON.parse(this.data.formData)
        let that = this
        if (formData.goodsList == null || formData.goodsList.length == 0) {
            util.showToast('请选择商品明细');
            return false
        }
        // 明细的数量和仓库不能为空
        for (let index = 0; index < formData.goodsList.length; index++) {
            const element = formData.goodsList[index];
            if (element.whId == null) {
                util.showToast(mixins.$t("chooseWh"));
                return false
            }
            //如果 设置了总单的仓库 然后又进行选品 没设置一样的仓库 那就把总单上的仓库清空
            if (formData.whId) {
                if (element.whId != formData.whId) {
                    formData.whId = null
                    formData.whName = ""
                    that.setData({
                        formData:JSON.stringify(formData)
                    })
                }
            }
            if (element.itemQty == null || element.itemQty == '' || element.itemQty == 0) {
                util.showToast(mixins.$t("inputWords") + "[" + element.skuCode + "]" + mixins.$t("count"));
                return false
            }
        }  
        return true
    },
    /**
     * @desc : 保存的參數設置
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    setParams(params) {
        let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
        let formData = JSON.parse(this.data.formData)
        formData.goodsList.forEach((element,index) => {
            element.itemIndex = index
        }); 
        params.intoingAmt = formData.goodsList.sum("intoingAmt") //金额
        params.intoingQty = formData.goodsList.sum("intoingQty") //一共的商品数量
        params.intoAmt = 0 //  已入库金额
        params.intoQty = 0 //  已入库数量         
        params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出入库标识 
        params.fromId = this.data.purIdArray?this.data.purIdArray:null //来源id
        params.fromNo = formData.fromNo //来源单号
        params.orgId = formData.orgId //组织部门
        params.staffId = formData.staffId // 员工
        params.supId = formData.supId // 供应商
        params.whId = formData.whId // 仓库
        params.remarks = formData.remarks // 备注
        params.makeStaff = app.globalData.user.staffId // 制单人
    
        params.itemList = formData.goodsList //商品明细
        console.log("save", this.data.params);
        return params
    },

    /**
     * @desc : 保存数据服务
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    saveData() {
        if (this.data.formMode == Constants.formMode.edit) { //编辑保存
            return this.excute(this.data.inboundProcessingService, this.data.inboundProcessingService.inboundUpdate, this.data.params)
        } else { //新建保存
            return this.excute(this.data.inboundProcessingService, this.data.inboundProcessingService.inboundInsert, this.data.params)
        }

    },
    /**
     * @desc : 查询数据 (转入库调用)
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    getData(e) {
        if (!e.idKey) {
            return
        }
        let param = {}
        let excute = this.excute(this.data.purchaseService, e.id, {});
        excute.then(res => {
            if (res.data.code === Constants.SUCESS_CODE) {
                let formData = JSON.parse(this.data.formData)
                formData = res.data.data
                this.setData({
                    formData:JSON.stringify(formData),
                    chooseVisible: true
                })
                this.calculateTotal(res.data.data.purchaseItemResponseList)
                   // 刷新商品明细 显示 查看更多
                 let card = this.data.cardList.filter(it => it.name == 'items');
             this.selectComponent('#'+this.data.formName).handleContentObj(card[0])

            }
        })
    },
    /**
     * @desc : 初始化数据
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    loadInit() {
        let isSysSetting = false //true为自动办理  false 为手动办理
        let contentList = this.data.contentList
        if (isSysSetting) { //系统参数中的自动办理参数  
            // 使用 filter 方法删除 code 为 flag 的项  
            contentList = contentList.filter(item => item.code !== 'flag');
            this.setData({
                contentList: contentList,
                isSysSetting
            })
        }
        if (this.data.formMode == Constants.formMode.edit) {
            wx.setNavigationBarTitle({
                title: mixins.$t('editPurInbound') //"编辑采购入库",  
            })
        } else {
            wx.setNavigationBarTitle({
                title: mixins.$t('addPurInbound') //"新建采购入库",
            })
        }
    },
})