/*******************************************************************************
 * Copyright(c) 2021 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：新建其他入库 采购入库 销售回库入库
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		姜永辉	        2024年3月22日		     1.00		   	    一览
 *******************************************************************************/
const mixins = require('@/mixins/index.js')
const util = require('@/utils/util.js')
const Constants = require('@/utils/Constants.js');
const app = getApp()
Page({
    mixins: [mixins],
    /**
     * 页面的初始数据
     */
    data: {
        formMode: Constants.formMode.index,
        // 弹出按钮
        buttonList: [{
            name: 'merge',
            title: mixins.$t('totalAmount')
        }],
        contentList: [{
            code: 'need',
            title: mixins.$t('totalAmount'),
            type: 'str'
        }, {
            code: 'amount',
            content: 0,
            type: 'number'
        }],
        // 动态的
        cardList: [],
        contentObj: {},
        popContent: [{
            code: 'intoingQty',
            type: 'step',
            title: mixins.$t('count'),
        },
        {
            code: 'whId',
            name: 'whName',
            title: mixins.$t('warehouseId'),
            type: 'choose',
            urlKey: 'openingInventory'
        },
        {
            code: 'skuSpec',
            title: mixins.$t('goodSpec'),
            type: 'str',
            readonly: true
        },
        {
            code: 'nonStdCode',
            title: mixins.$t('goodsBatch'),
            type: 'str',
        },
        ],

        // 路由
        routeObjName: 'inboundProcessing',
        inboundOtherService: app.globalData['inboundOtherService'],
        inboundReturnService: app.globalData['inboundReturnService'],
        // 主键Id
        primaryKey: 'intoId',
        table: Constants.tables.inbound,
    },
    /**
     * @desc : dk-from choose 回调事件
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
    chooseData(e) {
        let formData = JSON.parse(this.data.formData)
        let code = e.detail.code
        let data = e.detail.data.data
        if (code == "whId") { //商品仓库
            formData.whId = data.id
            formData.whName = 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 == "intoReason") { //入库原因
            formData.intoReason = data.id
            formData.intoReasonName = data.name
        }
        if (code == "intoObject") { //入库对象
            formData.intoObject = data.id
            formData.intoObjectName = data.name
            formData.objType = data.objType
        }
        this.setData({
            formData: JSON.stringify(formData)
        })
    },
    /**
     * @desc : 给表单赋值
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
    setValuesByEdit(data) {
        let cardList_ = this.data.cardList
        let contentList_ = this.data.contentList
        let sumitemAmt = 0 
        // 入库对象
        if (data.intoType == Constants.intoType.other) {
            data.intoObject = (data.supId!=null)?data.supId:data.cusId
            data.intoObjectName = (data.supplierName!=null)?data.supplierName:data.cusName
        }       
        //  入库状态-已入库
        if (data.intoStatus == Constants.intoStatus.inBounded) {
            //查询采购订单表 未入库的 详细 
            this.setData({
                buttonList: [{
                    name: 'merge',
                    title: mixins.$t("close")
                }],
            })
        } else {
            this.setData({
                buttonList: [{
                    name: 'merge',
                    title: mixins.$t("inProcessing")
                }],
            })
        }
        console.log("sumitemAmt",data);
        sumitemAmt =   Number(data.intoingAmt)
        cardList_.forEach(card => {
            if (card.name === 'items') {
                if (data.intoStatus == Constants.intoStatus.inBounding) {
                    card.info = "（" + mixins.$t("warehousingProcessing") + "）"
                    card.color = "#E4002B"
                } else {
                    card.info = "（" + mixins.$t("checkined") + "）"
                    card.color = "#1B365D"
                }
                card.itemAmt = sumitemAmt
            }
        })
        contentList_[1].content = sumitemAmt

        // 明细的最大入库办理的量
        data.goodsList.forEach(element => {
            if (this.data.item.intoType == Constants.intoType.saleReturn) {
                element['intoingQty'] = -1 * Math.abs(element.intoingQty)
                element.intoingAmt = -1 * Math.abs(element.intoingAmt)   //金额
                element['intoingQty_max'] = -1
                element['intoingQty_min'] = -1 * Math.abs(element.intoingQty)
            } else {
                element['intoingQty_max'] = element.intoingQty
                element['intoingQty_min'] = 1
            }
        })

        // 刷新商品明细 显示 查看更多
        let card = this.data.cardList.filter(it => it.name == 'items');
        this.selectComponent('#' + this.data.formName).handleContentObj(card[0])

        this.setData({
            itemData: data,
            cardList: cardList_,
            contentList: contentList_,
            formData: JSON.stringify(data),
            sumitemAmt
        })

    },

    /**
     * @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.priceInto * element.intoingQty
            totalAmout += Number(element.priceInto * element.intoingQty)
        })
        // 左下角的合计金额
        contentList_.forEach(card => {
            if (card.code === 'amount') {
                card.content = totalAmout
            }
        })
        // 明细的合计金额
        cardList.forEach(card => {  //循环出商品总共价格
            if (card.name === 'items') {
                //合计金额
                card.itemAmt = totalAmout
            }
        })
        this.setData({
            contentList: contentList_,
            cardList,
            formData: JSON.stringify(formData)
        })
    },

    /**
    * @desc : 保存数据服务--校验
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
    validData() {
        // 已入库
        if (this.data.itemData.intoStatus == Constants.intoStatus.inBounded) {
            return true
        }
        // 入库中
        let formData = JSON.parse(this.data.formData)
        if (formData.goodsList == null || formData.goodsList.length == 0) {
            util.showToast(mixins.$t("chooseGoodsInfo"));
            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 (element.intoingQty == null || element.intoingQty == '' || element.intoingQty == 0) {
                util.showToast(mixins.$t("inputWords") + "[" + element.skuCode + "]" + mixins.$t("count"));
                return false
            }
            if (element.intoingQty > element.intoingQty_max) {
                util.showToast("[" + element.skuCode + "]" + mixins.$t("maxCount") + element.intoingQty_max);
                return false
            }
        }
        return true
    },

    /**
     * @desc : 保存的參數設置
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
    setParams(params) {
        let formData = JSON.parse(this.data.formData)
        params.allEdit = true //大编辑
        // 由于办理后直接生成出库单，将画面的删除的数据放入deleteItemList数组中
        params.deleteItemList = formData.deleteList || []

        params.fromId = formData.fromId  //来源id
        params.fromNo = formData.fromNo  //来源单号
        params.orgId = formData.orgId  //组织部门
        params.staffId = formData.staffId  // 员工 
        params.supId = formData.supId // 供应商
        //  // 供应商1 客户2 所有 传空
        if (formData.objType == 1) {
            params.supId = formData.intoObject  // 供应商
        }
        if (formData.objType == 2) {
            params.cusId = formData.intoObject  // 客户
        }
        params.whId = formData.whId  // 仓库
        params.remarks = formData.remarks  // 备注
        params.makeStaff = app.globalData.user.staffId  // 制单人
        // 退货的时候的数量和金额传负值
        if (this.data.item.intoType == Constants.intoType.saleReturn) {
            params.intoingAmt = -1 * Math.abs(formData.goodsList.sum("intoingAmt"))   //金额
            params.intoingQty = -1 * Math.abs(formData.goodsList.sum("intoingQty"))     //一共的商品数量
            params.returnQty = params.intoingQty     //退货的量
            params.returnAmt = params.intoingAmt     //退货的量
            params.intoAmt = 0     //  已入库金额
            params.outQty = 0     //  已入库数量   
            formData.goodsList.forEach(item => {
                item.intoingAmt = -1 * Math.abs(item.intoingAmt)
                item.intoingQty = -1 * Math.abs(item.intoingQty)
            })
        } else {
            // 总单的 入库中数量和金额合计
            params.intoingAmt = formData.goodsList.sum("intoingAmt")   //金额
            params.intoingQty = formData.goodsList.sum("intoingQty")     //一共的商品数量
            params.intoAmt = 0     //  已入库金额
            params.intoQty = 0     //  已入库数量          
        }
        params.itemList = formData.goodsList //商品明细
        params.annexPaths = formData.annexPaths || [] //附件 
        return params
    },
    /**
     * @desc : 保存数据服务
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
    saveData() {
        if (this.data.itemData.intoStatus == Constants.intoStatus.inBounding) {
            if (this.data.item.intoType == Constants.intoType.pur) {
                return this.excute(this.data.service, this.data.service.inBoundHandle, this.data.params)
            } else if (this.data.item.intoType == Constants.intoType.other) {
                return this.excute(this.data.inboundOtherService, this.data.inboundOtherService.inBoundHandle, this.data.params)
            } else {
                return this.excute(this.data.inboundReturnService, this.data.inboundReturnService.returnHandle, this.data.params)
            }
        } else {
            wx.navigateBack({
                delta: 1
            })
        }
    },

    /**
   * @desc : 加载数据
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
    loadInit() {
        let contentObj = {}
        let cardList = []
        // 采购入库
        if (this.data.item.intoType == Constants.intoType.pur) {
            wx.setNavigationBarTitle({
                title: mixins.$t('purInBound'),
            })
            cardList = [{
                name: 'warehouse'
            }, {
                name: 'relation'
            }, {
                name: 'items',
                title: mixins.$t('goodsDetail'),
                chooseGoodsFlag: '',
                itemAmt: '',
                displayNum: 2
            }, {
                name: 'other',
                title: mixins.$t('otherInfo')
            }]
            contentObj = {
                warehouse: [{
                    //入库仓库
                    code: 'whId',
                    name: 'whName',
                    title: mixins.$t("whName"),
                    type: 'choose',
                    urlKey: 'chooseWh',
                }],
                relation: [{
                    code: 'sourceNo',
                    name: 'fromNo',
                    type: 'choose',
                    readonlyItem: true,
                    controlChooseFlag: true,
                    title: mixins.$t('sourceOrder'),
                    urlKey: 'choosePurchaseOrder'
                }],
                items: [{
                    code: 'sumQuantity',
                    name: 'collectName',
                    type: 'drop',
                    dropType: 'collect',

                }, {
                    code: 'sumAmount',
                    type: 'number',
                    title: mixins.$t('totalAmount'),
                }],

                other: [{
                    code: 'remarks',
                    type: 'textarea',
                    title: mixins.$t('remarks'),
                }, {
                    code: 'file',
                    type: 'uploader',
                    title: mixins.$t('uploader')
                }]
            }
            this.setData({
                contentObj,
                cardList,
            })

        } else if (this.data.item.intoType == Constants.intoType.other) {
            // 其他入库
            wx.setNavigationBarTitle({
                title: mixins.$t('otherInWh'),
            })
            cardList = [{
                name: 'main',
                title: mixins.$t('inBoundInfo'),
            },
            {
                name: 'items',
                title: mixins.$t('goodsDetail'),
                info: '(' + mixins.$t('warehousingProcessing') + ')',
                chooseGoodsFlag: false,
                color: '#E4002B',
                displayNum: 2
            }, {
                name: 'other',
                title: mixins.$t('otherInfo')
            }
            ]
            contentObj = {
                main: [
                    {
                        code: 'intoReason',
                        name: 'intoReasonName',
                        type: 'choose',
                        required: true,
                        urlKey: 'chooseStorageInReason'
                    },
                    {
                        code: 'staffId',
                        name: 'staffName',
                        title: mixins.$t('responsiblePerson'),
                        type: 'choose',
                        required: true,
                        urlKey: 'chooseStaff'
                    }, {
                        code: 'orgId',
                        name: 'orgName',
                        title: mixins.$t('orgId'),
                        type: 'choose',
                        required: true,
                        urlKey: 'chooseOrg'
                    },
                    {
                        code: 'intoDate',
                        name: 'intoDate',
                        type: 'date',
                        required: true,
                    },
                    {
                        code: 'intoObject',
                        name: 'intoObjectName',
                        title: mixins.$t('inObject'),
                        type: 'choose',
                        urlKey: 'chooseStorageObject'
                    },
                ],

                items: [{
                    code: 'collectType',
                    name: 'collectName',
                    type: 'drop',
                    dropType: 'collect'
                }, {
                    code: 'collectAmount',
                    type: 'number',
                    title: mixins.$t('totalAmount'),
                }],

                other: [{
                    code: 'remarks',
                    type: 'textarea',
                    title: mixins.$t('remarks'),
                    readonly: false
                }, {
                    code: 'file',
                    type: 'uploader',
                    title: mixins.$t('uploader')
                }]
            }
            this.setData({
                contentObj,
                cardList,
            })
        } else {
            // 销售退货
            cardList = [{
                name: 'warehouse'
            }, {
                name: 'items',
                title: mixins.$t('goodsDetail'),
                chooseGoodsFlag: '',
                itemAmt: '0',
                displayNum: 2
            }, {
                name: 'other',
                title: mixins.$t('otherInfo')
            }]
            contentObj = {
                warehouse: [{
                    code: 'whId',
                    name: 'whName',
                    title: mixins.$t("whName"),
                    type: 'choose',
                    urlKey: 'chooseWh',
                }],
                items: [{
                    code: 'sumQuantity',
                    name: 'collectName',
                    type: 'drop',
                    dropType: 'collect',

                }, {
                    code: 'sumAmount',
                    type: 'number',
                    title: mixins.$t('totalAmount'),
                }],

                other: [{
                    code: 'remarks',
                    type: 'textarea',
                    title: mixins.$t('remarks')
                }, {
                    code: 'file',
                    type: 'uploader',
                    title: mixins.$t('uploader')
                }]
            }
            this.setData({
                contentObj,
                cardList,
            })
            wx.setNavigationBarTitle({
                title: mixins.$t('purReturnOutBound'),
            })
        }
    },

    /**
     * @desc : （编辑）
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
    toEdit(e) {
        let id = e.currentTarget.dataset.item.intoId
        // 采购入库
        if (this.data.item.intoType == Constants.intoType.pur) {
            wx.navigateTo({
                url: this.data.route.add.url,
                events: {
                    // 回调后，在这里给页面赋值
                    bandData: function (e) { }
                },
                success: function (res) {
                    res.eventChannel.emit('params', {
                        id: id,
                        formMode: Constants.formMode.edit
                    })
                }
            })
        }
        // 其他入库
        else if (this.data.item.intoType == Constants.intoType.other) {
            wx.navigateTo({
                url: this.data.route.addOther.url,
                events: {
                    // 回调后，在这里给页面赋值
                    bandData: function (e) { }
                },
                success: function (res) {
                    res.eventChannel.emit('params', {
                        id: id,
                        formMode: Constants.formMode.edit
                    })
                }
            })
            // 销售退货
        } else {
            wx.navigateTo({
                url: this.data.route.addReturn.url,
                events: {
                    // 回调后，在这里给页面赋值
                    bandData: function (e) { }
                },
                success: function (res) {
                    res.eventChannel.emit('params', {
                        id: id,
                        formMode: Constants.formMode.other,
                        formType: Constants.formType.edit,
                    })
                }
            })
        }

    },

})