/*******************************************************************************
 * Copyright(c) 2021 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：新建其他入库
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		姜永辉	        2024年3月22日		     1.00		   	    一览
 *******************************************************************************/
const mixins = require('@/mixins/index.js')
const Constants = require('@/utils/Constants');
const config = require('@/config/config.js')
const util = require('@/utils/util.js')
const app = getApp()
Page({
    mixins: [mixins],
    /**
     * 页面的初始数据
     */
    data: {
        purIdArray: '',//来源单id 
        // 弹出按钮
        buttonList: [{
            name: 'merge',
            title: mixins.$t('save')
        }],
        contentList: [],
        btnFormData: null,
        //弹出pop
        popContent: [
            {
                code: 'itemQty',
                type: 'step',
                title: mixins.$t('count'),
                required: true
            },
            { code: 'packageBox', type: 'packageBox', title: mixins.$t("packageBox"), },
            {
                code: 'priceInto',
                type: 'number',
                title: mixins.$t("inboundPrice"),
                required: true
            },
            {
                code: 'whId',
                name: 'whName',
                title: mixins.$t('warehouseId'),
                type: 'choose',
                urlKey: 'openingInventory'
            },

            {
                code: 'skuSpec',
                title: mixins.$t('goodSpec'),
                type: 'str',
                readonly: true,
            },
            {
                code: 'brandName',
                title: mixins.$t('brandName'),
                type: 'str',
                readonly: true,
            },
            {
                code: 'nonStdCode',
                title: mixins.$t('goodsBatch'),
                tip: mixins.$t('tipPop'),
                type: 'str',
            },
        ],
        cardList: [{
            name: 'main',
            title: mixins.$t('inBoundInfo'),
        },
        {
            name: 'items',
            title: mixins.$t('goodsDetail'),
            info: '(' + mixins.$t('warehousingProcessing') + ')',
            color: '#E4002B',
            itemAmt: 0,
            content: 2,
            displayNum: 2
        }, {
            name: 'other',
            title: mixins.$t('otherInfo')
        }
        ],
        contentObj: {
            main: [
                {
                    code: 'intoReason',
                    name: 'intoReasonName',
                    type: 'choose',
                    required: true,
                    urlKey: 'chooseStorageInReason',
                    urlKeyParam: Constants.kindCode.basicEnter
                },
                {
                    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')
            }]
        },
        // 路由
        routeObjName: 'inboundOther',
        table: Constants.tables.inbound,
        // 系统参数
        flgHandleSetting: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false,
        quantityCol: 'intoingQty',
        sumAmountCol: 'itemAmt',
        sumQuantityCol: 'intoingQty',

    },

    /**
    * @desc : 页面加载数据方法
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
    loadInit() {
        if (this.data.formMode == Constants.formMode.edit) {
            wx.setNavigationBarTitle({
                title: mixins.$t('editOtherInWh'),
            })
        } else {
            wx.setNavigationBarTitle({
                title: mixins.$t('addOtherInWh'),
            })
            // 新增
            if (this.data.formData == '{}') {
                this.setData({
                    formData: JSON.stringify({
                        intoDate: new Date().toDateStr(),
                        staffId: app.globalData.user.staffId,
                        orgId: app.globalData.user.orgId,
                        staffName: app.globalData.user.staffName,
                        orgName: app.globalData.user.orgName,
                    })
                })
            }
            // 系统参数开启自动办理        
            if (!this.data.flgHandleSetting) {
                this.setData({
                    contentList: [
                        {
                            code: 'need',
                            title: mixins.$t('totalAmount'),
                            type: 'str'
                        },
                        {
                            code: 'amount',
                            content: 0,
                            type: 'number'
                        }],
                })
            } else {
                this.setData({
                    contentList: [
                        {
                            code: 'flag',
                            title: mixins.$t('antoHandle'),
                            type: 'checkbox'
                        }, {
                            code: 'need',
                            title: mixins.$t('totalAmount'),
                            type: 'str'
                        },
                        {
                            code: 'amount',
                            content: 0,
                            type: 'number'
                        }],
                })

                let btnFormData = JSON.parse(this.data.btnFormData) || {}
                btnFormData.flag = true

                this.setData({
                    btnFormData: JSON.stringify(btnFormData),
                })
            }
        }

    },

    /**
    * @desc : 给表单赋值
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
    setValuesByEdit(data) {
        let that = this
        let cardList_ = this.data.cardList
        let sumitemAmt = 0
        let sumitemquantity = 0
        let formType = this.data.formType
        // 入库中
        if (data.intoStatus == Constants.intoStatus.inBounding) {
            sumitemquantity = Number(data.intoingQty)
            sumitemAmt = Number(data.intoingAmt)
            this.setData({
                quantityCol: 'intoingQty',
                sumQuantityCol: 'intoingQty',
            })
        } else {
            sumitemquantity = Number(data.intoQty)
            sumitemAmt = Number(data.intoAmt)
            this.setData({
                quantityCol: 'intoQty',
                sumQuantityCol: 'intoQty',
            })
        }

        cardList_.forEach(card => {
            if (card.name === 'items') {
                if (formType == 1) {
                    card.info = "（" + mixins.$t("warehousingProcessing") + "）"
                    card.color = "#E4002B"
                } else {
                    card.info = "（" + mixins.$t("checkined") + "）"
                    card.color = "#1B365D"
                }
                card.itemAmt = sumitemAmt
                //  入库状态-已入库
                if (data.intoStatus == Constants.intoStatus.inBounded) {
                    card.intoQty = sumitemquantity
                } else {
                    card.intoingQty = sumitemquantity
                }
            }
        })

        // 明细的最大入库办理的量
        data.goodsList.forEach(element => {
            if (data.intoStatus == Constants.intoStatus.inBounded)//"入库状态-已入库"
            {
                element.itemAmt = element.priceInto * element.intoQty
                element.itemQty = element.intoQty
                element.box = element.intoBox
                element.piece = element.intoPiece
            } else {
                element.itemAmt = element.priceInto * element.intoingQty
                element.itemQty = element.intoingQty
                element.box = element.intoingBox
                element.piece = element.intoingPiece
            }
            element.sumPrice = element.priceInto * element.itemQty
            if (data.intoType == Constants.intoType.saleReturn) {
                element['intoingQty_max'] = -1
                if (data.intoStatus == Constants.intoStatus.inBounded) {
                    element['intoingQty_min'] = -1 * Math.abs(element.intoQty)
                } else {
                    element['intoingQty_min'] = -1 * Math.abs(element.intoingQty)
                }
            } else {
                if (data.intoStatus == Constants.intoStatus.inBounded)
                //"入库状态-已入库"
                {
                    element['intoingQty_max'] = element.intoQty
                } else {
                    element['intoingQty_max'] = element.intoingQty
                }
                element['intoingQty_min'] = 1
            }
            if (element.skuImages && element.skuImages.length > 0) {
                element.skuImages.forEach(item => {
                    item.url = config.image_url + item.path
                });
                element.imagesUrl = element.skuImages[0].url
            }
            if (element.flgSubUnit) {
                element.calculationFormula = element.packBox + element.unitName + '= 1' + element.subUnitName
                element.packageBox = element['box'] + element.subUnitName + element['piece'] + element.unitName

            }
        })

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

        // 系统参数开启自动办理   --编辑的时候都不显示出来 240513 后台不依赖这个参数         
        this.setData({
            contentList: [
                {
                    code: 'need',
                    title: mixins.$t('totalAmount'),
                    type: 'str'
                },
                {
                    code: 'amount',
                    content: sumitemAmt,
                    type: 'number'
                }],
        })


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

    },

    /**
     * @desc   : 绑定数据-选择页面返回的逻辑处理
     * @author : 姜永辉
     * @date   : 2024年3月12日
     */
    chooseData(e) {
        console.log("chooseData", e);
        let formData = JSON.parse(this.data.formData)
        let code = e.detail.code
        let data = e.detail.data.data

        if (code == "staffId") { //员工
            formData.staffId = data.id
            formData.staffName = data.name
            formData.orgId = data.orgId
            formData.orgName = data.orgName
        }
        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 : 姜永辉
     */
    setGoods(e) {
        let contentList_ = this.data.contentList
        let cardList = this.data.cardList
        let formData = JSON.parse(this.data.formData)
        let totalAmout = Number(0)
        let totalQuantity = Number(0)
        // 各个明细的金额数量
        formData.goodsList.forEach(element => {  //循环出商品总共价格  
            //"入库状态-已入库"   
            if (formData.intoStatus == Constants.intoStatus.inBounded) {
                element.intoQty = element.itemQty
                element.priceInto = element.priceInto ? element.priceInto : element.pricePurchase
                element.intoAmt = element.priceInto * element.intoQty
                element.intoingAmt = 0     //  入库中金额
                element.intoingQty = 0     //  入库中数量
                totalAmout += Number(element.priceInto * element.intoQty)
                totalQuantity += Number(element.intoQty)
            }
            else {
                element.intoingQty = element.itemQty
                element.priceInto = element.priceInto ? element.priceInto : element.pricePurchase
                element.intoingAmt = element.priceInto * element.intoingQty
                element.intoAmt = 0     //  已入库金额
                element.intoQty = 0     //  已入库数量
                totalAmout += Number(element.priceInto * element.intoingQty)
                totalQuantity += Number(element.intoingQty)
            }
            element.packageBox = element['box'] + element.subUnitName + element['piece'] + element.unitName
            console.log("element", element, element.nonStdCode);
            element.nonStdCode = element.nonStdCode != null ? element.nonStdCode : '-'
        })
        // 左下角的合计金额
        contentList_.forEach(card => {
            if (card.code === 'amount') {
                card.content = totalAmout
            }
        })
        // 明细的合计金额
        cardList.forEach(card => {  //循环出商品总共价格
            if (card.name === 'items') {
                //合计金额
                card.itemAmt = totalAmout
                card.content = totalQuantity
                //  入库状态-已入库
                if (formData.intoStatus == Constants.intoStatus.inBounded) {
                    card.intoQty = totalQuantity
                } else {
                    card.intoingQty = totalQuantity
                }
            }
        })
        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)
        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.itemQty == null || element.itemQty == '' || element.itemQty == 0) {
                util.showToast(mixins.$t("inputWords") + "[" + element.skuCode + "]" + mixins.$t("count"));
                return false
            }
            if (element.nonStdCode == null || element.nonStdCode == '' || element.nonStdCode.length == 0) {
                util.showToast(mixins.$t("inputWords") + "[" + element.skuCode + "]" + mixins.$t("goodsBatch"));
                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)
        // 新增编辑的
        params.intoId = formData.intoId
        if (!this.data.flgHandleSetting) {
            params.flgAutoHandle = false
        } else {
            params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出入库标识 
        }
        // 总单的 入库中数量和金额合计  
        if (formData.intoStatus == Constants.intoStatus.inBounded) { //已入库
            params.intoingAmt = 0  //金额
            params.intoingQty = 0 //一共的商品数量
            params.intoAmt = formData.goodsList.sum("intoAmt") //  已入库金额
            params.intoQty = formData.goodsList.sum("intoQty") //  已入库数量   
            formData.goodsList.forEach(item => {
                item.intoBox = item.box
                item.intoPiece = item.piece
            })

        } else { //入库中
            params.intoingAmt = formData.goodsList.sum("intoingAmt") //金额
            params.intoingQty = formData.goodsList.sum("intoingQty") //一共的商品数量
            params.intoAmt = 0 //  已入库金额
            params.intoQty = 0 //  已入库数量     
            formData.goodsList.forEach(item => {
                //  新建 直接生成入库单的情况
                if (params.flgAutoHandle) {
                    item.intoBox = item.box
                    item.intoPiece = item.piece
                } else {
                    item.intoingBox = item.box
                    item.intoingPiece = item.piece
                }
            })
        }

        // 系统参数
        params.flgHandleSetting = this.data.flgHandleSetting
        params.orgId = formData.orgId  //组织部门
        params.staffId = formData.staffId  // 员工
        //  // 供应商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  // 制单人
        // 明细的顺序
        let i = 0
        formData.goodsList.forEach(it => {
            it.itemIndex = (i++)
        })
        params.itemList = formData.goodsList //商品明细
        params.annexPaths = formData.annexPaths || [] //附件 
        params.limitEdit = true
        return params
    },

    /**
    * @desc : 保存数据服务
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
    saveData() {
        if (this.data.formMode == Constants.formMode.edit) {
            return this.excute(this.data.service, this.data.service.otherInboundUpdate, this.data.params)
        } else {
            return this.excute(this.data.service, this.data.service.otherInboundInsert, this.data.params)
        }

    },
    /**
      * @desc : 处理保存后续事件
      * @date : 2024/2/1 15:49
      * @author : 姜永辉
      */
    handleSaveData() {
        //购物车跳转来的
        if (this.data.formType == Constants.formType.shopping) {
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2]; //上一个页面
            prevPage.setData({
                refreshByAdd: true
            })

            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                });
            }, 200)
        }
    }


})