// 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: {
        // 弹出按钮
        buttonList: [{
            name: 'merge',
            title: mixins.$t('save') //'保存'
        }],
        contentList: [{
            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: 'skuSpec',
                title: mixins.$t('goodSpec'), //'规格',
                type: 'str',
                readonly: true,
            },
            {
                code: 'nonStdCode',
                title: mixins.$t('goodsBatch'), //'商品批次',
                type: 'str',
            },
        ],

        cardList: [{
                name: 'wh'
            }, {
                name: 'relation'
            },
            {
                name: 'items',
                title: mixins.$t('goodsDetail'), //'商品明细',
                color: '#E4002B',
                displayNum: 2
            }, {
                name: 'other',
                title: mixins.$t('otherInfo'), //'其他信息'
            }
        ],
        contentObj: {

            wh: [{
                code: 'whId',
                name: 'whName',
                title: mixins.$t('eiWhName'), //'预计入库仓库',
                type: 'choose',
                required: true,
                urlKey: 'chooseWh'
            }, {
                code: 'pickupDate',
                name: 'pickupDatem',
                type: 'date',
                required: true,
                title: mixins.$t('erDate'), //'预计入库日期',
            }, {
                code: 'supId',
                name: 'supName',
                title: mixins.$t('supplier'), //'供应商',
                type: 'choose',
                required: true,
                urlKey: 'chooseSupplier'
            }, ],
            relation: [{
                code: 'sourceNo',
                name: 'fromNo',
                type: 'choose',
                title: mixins.$t('sourceOrder'), //'关联源单',
                urlKey: 'chooseSaleOrder'
            }],
            items: [ ],

            other: [{
                code: 'remarks',
                type: 'textarea',
                title: mixins.$t('remarks'), //'备注',
                readonly: false
            }, {
                code: 'file',
                type: 'uploader',
                title: mixins.$t('uploader'), //'附件'
            }]
        },
        table: Constants.tables.purchase,
        // 路由
        routeObjName: 'purchase',
    },
    /**
     * @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.supName = 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 (code == "sourceNo") { //来源单 
            this.convertGoods(data.choooseItemList)
            return
        }

        this.setData({
            formData: JSON.stringify(formData)
        })
    },
    /**
     * @desc   : 转换销售单 过来的选品数据 对应接口数据 
     * @author : 王英杰
     * @date   : 2024年3月12日
     */
    convertGoods(choooseItemList) {
        let formData = JSON.parse(this.data.formData)
        // 提取purNo字段为数组，并去重
        const orderNoArray = [...new Set(choooseItemList.map(item => item.orderNo))];
        const orderIdArray = [...new Set(choooseItemList.map(item => item.orderId))];
        // 将数组元素转换为逗号分隔的字符串
       formData.fromNos = this.isArrayWithSingleNull(orderNoArray) ? []:orderNoArray.join(',').split(',')  //来源单号
        formData.fromIds = this.isArrayWithSingleNull(orderIdArray)?[]:orderIdArray.join(',').split(',') //来源单id
        formData.fromNo = orderNoArray.join(','); 
        let cardList_ = this.data.cardList
        cardList_.forEach(card => { //循环出商品总共价格
            if (card.name === 'items') {
                card.itemAmt = choooseItemList.sum("itemAmt") //售价金额合计 
            }
        })
        let contentList_ = this.data.contentList
        contentList_.forEach(card => { //循环出商品总共价格
            if (card.code === 'amount') {
                card.content = choooseItemList.sum("itemAmt")
            }
        })

        choooseItemList.forEach(element => {
            element.chooseFlg = "biu" //辨别选品标识
            element.priceStd = element.priceStandard
            element.fromId = element.orderId
            element.fromItemId = element.itemId
            element.pricePur = element.pricePurchase
            element.amtStd = Number(element.priceStd * element.itemQty) //标价金额
            element.priceDiscount = (Number(element.pricePurchase) / Number(element.priceStandard)) * 100;
            element.nonStdCode = element.nonStdCode ? element.nonStdCode : '' // 色号  批次号   
        });
        formData.goodsList = choooseItemList
        this.setData({
            formData: JSON.stringify(formData),
            cardList: cardList_,
            contentList: contentList_
        })
    },
    /**
     * @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,
            })
        }
        this.setData({
            formData: JSON.stringify(formData)
        })

    },
     /**
     * @desc : 判断出 数组 arr 是否是 [null] 的数据
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
     isArrayWithSingleNull(arr) {  
        // 检查是否是一个数组  
        if (!Array.isArray(arr)) {  
            return false;  
        }  
          
        // 检查数组长度是否为1  
        if (arr.length !== 1) {  
            return false;  
        }  
          
        // 检查数组中的元素是否为null  
        return arr[0] === null;  
    },
    openChoosedItemInfo(e){
        let popContent_ = this.data.popContent
          popContent_.forEach(card => { //
            if (card.code === 'itemQty') {
                card.max = 1
            }
        })
        this.setData({ 
            popContent:popContent_, 
        })
    },
    /**
     * @desc : 给表单赋值
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    setValuesByEdit(data) {
        data.goodsList = data.purchaseItemResponseList 
        // 提取purNo字段为数组，并去重
        const orderNoArray = [...new Set( data.goodsList.map(item => item.orderNo))];
        const orderIdArray = [...new Set( data.goodsList.map(item => item.orderId))];
        // 将数组元素转换为逗号分隔的字符串 
       
        data.fromNos = this.isArrayWithSingleNull(orderNoArray) ? []:orderNoArray.join(',').split(',')  //来源单号
        data.fromIds = this.isArrayWithSingleNull(orderIdArray)?[]:orderIdArray.join(',').split(',') //来源单id
        data.fromNo = orderNoArray.join(','); 
        data.goodsList.forEach(element => {
            element.chooseFlg = "biu" //辨别选品标识
            element.priceStd = element.priceStandard
            element.pricePur = element.pricePurchase
            element.amtStd = Number(element.priceStd * element.itemQty) //标价金额
            element.priceDiscount = (Number(element.pricePurchase) / Number(element.priceStandard)) * 100;  
            element['itemQty_min'] = Number(element.intoingQty+element.intoQty) 
            if(element.intoingQty>0||element.intoQty>0){
                element.deleteFlag = false
                element.message = '商品已转入库不能删除'
            }
        });
        data.supName = data.supplierName
        let cardList_ = this.data.cardList
        let contentList_ = this.data.contentList
        let popContent_ = this.data.popContent
        cardList_.forEach(card => {  //商品明细右下角 合计
            if (card.name === 'items') {
                card.itemAmt = data.goodsList.sum("itemAmt")
            }
        })
        contentList_.forEach(card => { // 按钮上 dk-save-botton 上的商品明细合计
            if (card.code === 'amount') {
                card.content = data.goodsList.sum("itemAmt")
            }
        })
        // popContent_.forEach(card => { //
        //     if (card.code === 'itemQty') {
        //         card.max = 1
        //     }
        // })
 
        this.setData({
            item: data,
            contentList: contentList_,
            cardList: cardList_,
            popContent:popContent_,
            formData: JSON.stringify(data)
        })
             // 刷新商品明细 显示 查看更多
     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 : 王英杰
     */
    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.itemAmt = element.pricePurchase * element.itemQty
            element.priceStd = element.priceStandard
            element.pricePur = element.pricePurchase
            element.amtStd = element.priceStd * element.itemQty
            element.priceDiscount = (Number(element.pricePurchase) / Number(element.priceStandard)) * 100;
            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 : 王英杰
     */
    setParams(params) {
        let formData = JSON.parse(this.data.formData)
        let totalAmout = Number(0)
        formData.goodsList.forEach(element => {
            element.itemId = (this.data.formMode == Constants.formMode.add) ? null : element.itemId
            totalAmout += Number(element.priceStd * element.itemQty) //标价金额
        })
        params.fromIds = formData.fromIds
        params.fromNos = formData.fromNos
        params.amtStd = totalAmout //标价金额
        params.sumAmount = formData.goodsList.sum("itemAmt") //合计金额 
        params.sumStandard = totalAmout // 标价合计
        params.sumQuantity = formData.goodsList.sum("itemQty") //商品总数量
        params.purDiscount = (Number(formData.goodsList.sum("pricePurchase")) / Number(formData.goodsList.sum("priceStandard"))) * 100
        formData.goodsList.sum("purDiscount") //折扣
        params.pickupDate = formData.pickupDate
        params.orgId = app.globalData.user.orgId //组织部门
        params.staffId = app.globalData.user.staffId // 员工
        params.supId = formData.supId // 供应商
        params.whId = formData.whId // 仓库
        params.remarks = formData.remarks // 备注
        params.makeStaff = app.globalData.user.staffId // 制单人    
        formData.goodsList.forEach((element, index) => {
            element.itemIndex = index
        });
        const deleteLisr = formData.deleteList ? formData.deleteList.filter(li => li.chooseFlg !== null && li.chooseFlg !== undefined && li.chooseFlg !== '') : [];
        params.deleteItemList = deleteLisr
        if (this.data.formMode == "edit") {
            params.editPurchaseItemList = formData.goodsList //商品明细
            params.deletePurchaseItemList = []
        } else {
            params.purchaseItemVOList = formData.goodsList //商品明细
        }
        console.log("save", this.data.params);
        return params
    },
    /**
     * @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.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 : 王英杰
     */
    saveData() {
        if (this.data.formMode != "edit") { //新建
            return this.excute(this.data.service, this.data.service.insert, this.data.params)
        } else {
            return this.excute(this.data.service, this.data.service.update, this.data.params)
        }

    },
    /**
     * @desc : 页面初始化加载方法
     * @date : 2024/2/1 15:49
     * @author : 王英杰
     */
    loadInit() { //以销定采  isSourceOrderFlag 区分是否来源于新建的选择原单 
        let that = this
        let formdata = JSON.parse(this.data.formData)
        let formMode = this.data.formMode
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('params', function (data) {
            const isSourceOrderFlag = data.isSourceOrderFlag
            if ((!isSourceOrderFlag) && (formMode != "edit")) {
                const choooseItemList = data.choooseItemList
                console.log(choooseItemList)
                that.convertGoods(choooseItemList)

            }
        })
        if (this.data.formMode == Constants.formMode.edit) {
            wx.setNavigationBarTitle({
                title: mixins.$t('editPurOrder') //"编辑采购订单", //mixins.$t('supplierEdit')
            })
        } else {
            wx.setNavigationBarTitle({
                title: mixins.$t('addPurOrder') //"新建采购订单",
            })
        }

    }
})