// package-basic-data/pages/test/add/add.js
const mixins = require('@/mixins/index.js')
const utils = require('@/utils/util');
const app = getApp()
const Constants = require('@/utils/Constants');
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    controlFlags:{choosewhFlag:true,chooseWhByUserDefault:true,choosewhReadonly:true,paramsByWhId:true,sourcePage:'inventory-adjustment'},
    draftFlag: false,
    purIdArray: '', //来源单id 
    // 弹出按钮
    buttonList: [],
    goodsListDownContent: [{
      code: 'whId',
      name: 'whName',
      title: '备注',
      type: 'str',
    }],
    btnFormData: null,
    popupTopObj: [{
      leftTitle: mixins.$t('storageNum'), //库存量',
      leftCode: 'usableQty',
      rightTitle: mixins.$t('sellableQuantity'), //'可售量',
      rightCode: 'invQty'
    }],
    popContent: [{
        code: 'itemQty',
        type: 'step',
        title: mixins.$t('countedQuantity'), //'数量', 
        required: true
      },

      {
        code: 'oWhId',
        name: 'oWhName',
        title: '源库区', //'盘亏原因',
        type: 'choose',
        urlKey: 'chooseWh'
      },
      {
        code: 'whId',
        name: 'whName',
        title: '目标库区', //'盘亏原因',
        type: 'choose',
        urlKey: 'chooseWh'
      },
      {
        code: 'nonStdCode',
        title: mixins.$t("goodsBatch"), //'商品批次',
        type: 'str',
        readonly: true,
      },
      {
        code: 'oNonStdCode',
        name: 'oNonStdName',
        title: '源批号', // '仓库',
        type: 'str',
      },
      {
        code: 'nonStdCode',
        name: 'nonStdName',
        title: '目标批号', //'盘亏原因',
        type: 'str',
        urlKey: 'openingReason'
      },

    ],

    cardList: [{
        name: 'main',
        title: mixins.$t("inventoryInformation"), //'盘点信息 
      },
      {
        name: 'items',
        title: mixins.$t("goodsDetail"), //'商品明细',
        info: '(' + mixins.$t("warehousingProcessing") + ')',
        color: '#E4002B',
        displayNum: 2
      }, {
        name: 'other',
        title: mixins.$t("otherInfo"), // '其他信息'
      }
    ],
    contentObj: {
      main: [{
          code: 'transferType',
          name: 'transferTypeName',
          title: "调整类型", //mixins.$t("inventoryEmployees"),  
          type: 'choose',
          required: true,
          urlKey: 'chooseAdjustmentType',
        }, {
          code: 'staffId',
          name: 'staffName',
          title: '责任人', //'盘点员工', 
          type: 'choose',
          required: true,
          urlKey: 'chooseStaff'
        }, {
          code: 'orgId',
          name: 'orgName',
          title: '部门', //'盘点部门',  
          type: 'choose',
          required: true,
          urlKey: 'chooseOrg'
        },
        {
          code: 'whId',
          name: 'whName',
          type: 'choose',
          title: "目标仓库", //'盘点仓库' 
          urlKey: 'chooseWh'
        },
        {
          code: 'nonStdCode',
          name: 'nonStdName',
          type: 'str',
          title: "目标批号", //'盘点仓库'  
        }
      ],
      items: [],
      other: [{
        code: 'remarks',
        type: 'textarea',
        title: mixins.$t("remarks"), //'备注',
        readonly: false
      }, {
        code: 'file',
        type: 'uploader',
        title: mixins.$t("uploader"), //'附件'
      }]
    },
    // 路由
    routeObjName: 'inventoryAdjustment',

    // inboundProcessingService: app.globalData['inboundProcessingService'],
  },
  /*
   * @desc   : 监听dk-from-bill str类型的数据变化
   * @author : 王英杰
   * @date   : 2024年3月12日
   */
  changeField(e) {
    let code = e.detail.code
    let formData = JSON.parse(this.data.formData)
    if (code == "nonStdCode") { //当输入总单的目标批号的时候  把已选商品的目标批号刷成一样的
      if (formData.goodsList) {
        formData.goodsList.forEach(element => {
          element.nonStdCode = formData.nonStdCode
        });
        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 == "transferType") { //调整类型
      formData.transferType = data.id
      formData.transferTypeName = data.name

      this.switchTransferType(formData.transferType)
    }
    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.name
        });
      }
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 切换调整类型 对应处理 
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  switchTransferType(transferType) {

    if (transferType == Constants.inventoryAdjustment.warehouse) { //调整类型-仓库调整
      this.setData({
        contentObj: {
          main: [{
              code: 'transferType',
              name: 'transferTypeName',
              title: "调整类型", //mixins.$t("inventoryEmployees"),  
              type: 'choose',
              required: true,
              urlKey: 'chooseAdjustmentType',
            }, {
              code: 'staffId',
              name: 'staffName',
              title: '责任人', //'盘点员工', 
              type: 'choose',
              required: true,
              urlKey: 'chooseStaff'
            }, {
              code: 'orgId',
              name: 'orgName',
              title: '部门', //'盘点部门',  
              type: 'choose',
              required: true,
              urlKey: 'chooseOrg'
            },
            {
              code: 'whId',
              name: 'whName',
              type: 'choose',
              title: "目标仓库", //'盘点仓库' 
              urlKey: 'chooseWh'
            },
          ],
          items: [],
          other: [{
            code: 'remarks',
            type: 'textarea',
            title: mixins.$t("remarks"), //'备注',
            readonly: false
          }, {
            code: 'file',
            type: 'uploader',
            title: mixins.$t("uploader"), //'附件'
          }]
        },
        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t('countedQuantity'), //'数量', 
            required: true
          },

          {
            code: 'oWhId',
            name: 'oWhName',
            title: '源库区', //'盘亏原因',
            type: 'choose',
            urlKey: 'chooseWh'
          },
          {
            code: 'whId',
            name: 'whName',
            title: '目标库区', //'盘亏原因',
            type: 'choose',
            urlKey: 'chooseWh'
          },
          {
            code: 'nonStdCode',
            title: mixins.$t("goodsBatch"), //'商品批次',
            type: 'str',
            readonly: true,
          },


        ],
      })
    } else { //盘点状态-非标号调整
      this.setData({
        contentObj: {
          main: [{
              code: 'transferType',
              name: 'transferTypeName',
              title: "调整类型", //mixins.$t("inventoryEmployees"),  
              type: 'choose',
              required: true,
              urlKey: 'chooseAdjustmentType',
            }, {
              code: 'staffId',
              name: 'staffName',
              title: '责任人', //'盘点员工', 
              type: 'choose',
              required: true,
              urlKey: 'chooseStaff'
            }, {
              code: 'orgId',
              name: 'orgName',
              title: '部门', //'盘点部门',  
              type: 'choose',
              required: true,
              urlKey: 'chooseOrg'
            },
            {
              code: 'nonStdCode',
              name: 'nonStdName',
              type: 'str',
              title: "目标批号", //'盘点仓库'  
            }
          ],
          items: [],
          other: [{
            code: 'remarks',
            type: 'textarea',
            title: mixins.$t("remarks"), //'备注',
            readonly: false
          }, {
            code: 'file',
            type: 'uploader',
            title: mixins.$t("uploader"), //'附件'
          }]
        },
        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t('countedQuantity'), //'数量', 
            required: true
          },

          {
            code: 'oNonStdCode',
            name: 'oNonStdName',
            title: '源批号', // '仓库',
            type: 'str',
          },
          {
            code: 'nonStdCode',
            name: 'nonStdName',
            title: '目标批号', //'盘亏原因',
            type: 'str',
            urlKey: 'openingReason'
          },

        ],
      })
    }
  },
  /**
   * @desc : 外露设置产品方法 
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setGoods(e) {
    let formData = JSON.parse(this.data.formData)
    formData.goodsList.forEach(element => {
      element.balanceQty = element.itemQty - element.invQty
    });
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 保存数据服务--校验
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  validData() {
    if (this.data.draftFlag) {
      return true;
    }
    let formData = JSON.parse(this.data.formData)
    let that = this

    if (formData.goodsList == null || formData.goodsList.length == 0) {
      util.showToast(mixins.$t("chooseGoodsInfo"));
      return false
    }

    for (let i = 0; i < formData.goodsList.length; i++) {
      if (formData.goodsList[i].balanceQty < 0) { //盘亏需要盘亏原因
        if (!formData.goodsList[i].lossReason) {
          util.showToast(mixins.$t("chooseLnventoryLossReasons"));
          return false
        }
      }
    }


    return true
  },
  /**
   * @desc : 保存的參數設置
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setParams(params) {
    let formData = JSON.parse(this.data.formData)
    let draftFlag = this.data.draftFlag
    let itemList = []
    formData.goodsList.forEach((element, index) => {
      let item = {}
      item.itemIndex = index
      item.skuId = element.skuId
      item.invId = element.invId
      item.invQty = element.invQty //库存数量
      item.checkQty = element.itemQty //盘点数量
      item.balanceQty = element.itemQty - element.invQty //差异数量
      item.staffId = formData.staffId //责任人
      item.priceInto = element.pricePurchase //单价 
      item.intoingAmt = element.pricePurchase * element.itemQty //单价
      itemList.push(item)
    });
    params.draftFlag = this.data.draftFlag
    params.staffId = formData.staffId
    params.remarks = formData.remarks
    params.orgId = formData.orgId
    params.flgLock = false //锁库标识 todo 不知道为啥
    if (formData.checkStatus == Constants.checkStaus.COMPLETE) {
      params.checkStatus = formData.checkStatus
    } else {
      params.checkStatus = draftFlag ? Constants.checkStaus.STAGING : Constants.checkStaus.COMPLETE
    }
    params.makeStaff = app.globalData.user.staffId
    params.itemList = itemList
    return params;
  },

  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  saveData() {
    let formData = JSON.parse(this.data.formData)
    if (this.data.formMode == "edit") { //编辑
      return this.excute(this.data.service, this.data.service.update, this.data.params)
    } else { //新建 或者暂存
      return this.excute(this.data.service, this.data.service.insert, this.data.params)
    }

  },
  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setValuesByEdit(data) {
    let formData = JSON.parse(this.data.formData)
    let readonly = this.data.readonly || false
    let buttonList = this.data.buttonList
    formData = data.data
    formData.goodsList = data.dataItem
    formData.goodsList.forEach(element => {
      element.itemQty = element.checkQty
      element.pricePurchase = element.priceInto
    });

    wx.setNavigationBarTitle({
      title: '编辑库存盘点', // mixins.$t('supplierAdd')
    })
    if (formData.checkStatus == Constants.checkStaus.COMPLETE) {
      buttonList = [{
        code: 'edit',
        name: 'merge',
        title: mixins.$t("edit"), //'保存'
      }]
      readonly = true
    } else {
      buttonList = [{
        code: 'draft',
        name: 'merge',
        color: '#636FB4',
        title: mixins.$t("staging"), //'暂存'
      }, {
        code: 'save',
        name: 'merge',
        title: mixins.$t("save"), //'保存'
      }]
    }
    this.setData({
      formData: JSON.stringify(formData),
      buttonList: buttonList,
      readonly: readonly
    })
    // 刷新商品明细 显示 查看更多
    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 that = this
    let buttonList = [{
      code: 'save',
      name: 'merge',
      title: mixins.$t("save"), //'保存'
    }]
    that.setData({
      buttonList: buttonList,
    })
    //设置 调整类型初始值 已经对应的逻辑处理
    let formData = this.data.formData ? JSON.parse(this.data.formData) : {}
    formData.transferType = Constants.inventoryAdjustment.warehouse
    formData.transferTypeName = '仓库调整'
    this.switchTransferType(formData.transferType)
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 按钮点击事件回调
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  open(e) {
    console.log('ee', e);
    let that = this
    let code = e.detail.name

    let draftFlag = false;
    if (code == 'draft') { //暂存
      draftFlag = true;
      this.setData({
        validFlag: false
      })
    }
    this.setData({
      draftFlag: draftFlag
    })
    this.save({});
  },
})