// package-basic-data/pages/test/add/add.js
const mixins = require('@/mixins/index.js')
const utils = require('@/utils/util');
const app = getApp()
const config = require('@/config/config.js')
const Constants = require('@/utils/Constants');
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    controlFlags: { choosewhFlag: true, chooseWhByUserDefault: true, choosewhReadonly: false, paramsByWhId: true, sourcePage: 'inventory-adjustment' },
    draftFlag: false,
    purIdArray: '', //来源单id 
    // 弹出按钮
    buttonList: [],
    goodsListDownContent: [{
      code: 'whId',
      name: 'whName',
      title: mixins.$t('remarks'),//'备注'
      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: 'packageBox', type: 'packageBox', title: mixins.$t("packageBox"), readonly: true },
    {
      code: 'oWhId',
      name: 'oWhName',
      title: mixins.$t('owhid'),//'源仓库' 
      type: 'choose',
      urlKey: 'selectInventorySku'
    },
    {
      code: 'whId',
      name: 'whName',
      title: mixins.$t('whid'),//'目标仓库'
      type: 'choose',
      urlKey: 'chooseWh'
    },
    {
      code: 'brandName',
      title: mixins.$t('brandName'),
      type: 'str',
      readonly: true,
    },
    {
      code: 'oNonStdCode',
      name: 'oNonStdName',
      title: mixins.$t('oNonStdCode'),//'源批号'
      type: 'str',
      tip: mixins.$t('tipPop'),

    },
    {
      code: 'nonStdCode',
      name: 'nonStdName',
      title: mixins.$t('nonStdCode'),//'目标批号'
      type: 'str',
      tip: mixins.$t('tipPop'),
    },

    ],

    cardList: [{
      name: 'main',
      title: mixins.$t("inventoryInformation"), //'盘点信息 
    },
    {
      name: 'items',
      title: mixins.$t("goodsDetail"), //'商品明细', 
      color: '#E4002B',
      displayNum: 2
    }, {
      name: 'other',
      title: mixins.$t("otherInfo"), // '其他信息'
    }
    ],
    contentObj: {
      main: [{
        code: 'transferType',
        name: 'transferTypeName',
        title: mixins.$t("adjustmentType"),  //"调整类型",  
        type: 'choose',
        required: true,
        clearItemFlag: true,
        urlKey: 'chooseAdjustmentType',
      }, {
        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: 'whId',
        name: 'whName',
        type: 'choose',
        title: mixins.$t('whid'),//'目标仓库'
        urlKey: 'chooseWh'
      },
      {
        code: 'nonStdCode',
        name: 'nonStdName',
        type: 'str',
        title: mixins.$t('nonStdCode'),//'目标批号'  
      }
      ],
      items: [],
      other: [{
        code: 'remarks',
        type: 'textarea',
        title: mixins.$t("remarks"), //'备注',
        readonly: true
      }, {
        code: 'file',
        type: 'uploader',
        title: mixins.$t("uploader"), //'附件'
        readonly: true
      }]
    },
    // 路由
    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) {
    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("adjustmentType"),  //"调整类型",  
            type: 'choose',
            required: true,
            clearItemFlag: true,
            urlKey: 'chooseAdjustmentType',
          }, {
            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: 'whId',
            name: 'whName',
            type: 'choose',
            title: mixins.$t('whid'),//'目标仓库'
            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: 'packageBox', type: 'packageBox', title: mixins.$t("packageBox"), readonly: true },
        {
          code: 'oWhId',
          name: 'oWhName',
          title: mixins.$t('owhid'),//'源仓库'
          type: 'choose',
          urlKey: 'selectInventorySku'
        },
        {
          code: 'whId',
          name: 'whName',
          title: mixins.$t('whid'),//'目标仓库'
          type: 'choose',
          urlKey: 'chooseWh'
        },
        {
          code: 'brandName',
          title: mixins.$t('brandName'),
          type: 'str',
          readonly: true,
        },
        {
          code: 'nonStdCode',
          title: mixins.$t("goodsBatch"), //'色号',
          type: 'str',
          readonly: true,
        },


        ],
      })
    } else { //盘点状态-色号调整
      this.setData({
        contentObj: {
          main: [{
            code: 'transferType',
            name: 'transferTypeName',
            title: mixins.$t("adjustmentType"),  //"调整类型", 
            type: 'choose',
            required: true,
            clearItemFlag: true,
            urlKey: 'chooseAdjustmentType',
          }, {
            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: 'nonStdCode',
            name: 'nonStdName',
            type: 'str',
            title: mixins.$t('nonStdCode'),//'目标批号'  
          }
          ],
          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: 'packageBox', type: 'packageBox', title: mixins.$t("packageBox"), readonly: true },
        {
          code: 'brandName',
          title: mixins.$t('brandName'),
          type: 'str',
          readonly: true,
        },
        {
          code: 'oNonStdCode',
          name: 'oNonStdName',
          title: mixins.$t('oNonStdCode'),//'源批号'
          type: 'str',
          tip: mixins.$t('tipPop'),
        },
        {
          code: 'nonStdCode',
          name: 'nonStdName',
          title: mixins.$t('nonStdCode'),//'目标批号'  
          type: 'str',
          tip: mixins.$t('tipPop'),
        },

        ],
      })
    }
  },
  /**
   * @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
      if (element.skuImages && element.skuImages.length > 0) {
        element.skuImages.forEach(item => {
          item.url = config.image_url + item.path
        });
        element.imagesUrl = element.skuImages[0].url
      }
    });
    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) {
    //   utils.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) {
    //       utils.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)
    params.staffId = formData.staffId
    params.orgId = formData.orgId
    params.transferType = formData.transferType
    params.makeStaff = app.globalData.user.staffId
    params.remarks = formData.remarks
    params.oWhId = formData.oWhId || ''
    params.whId = formData.whId
    params.oNonStdCode = formData.oNonStdCode || ''
    params.nonStdCode = formData.nonStdCode

    let itemList = []
    formData.goodsList.forEach((element, index) => {
      let item = {}
      item.itemIndex = index
      item.transferQty = element.itemQty
      item.oWhId = element.oWhId || ''
      item.whId = element.whId || ''
      item.oNonStdCode = element.oNonStdCode || ''
      item.nonStdCode = element.nonStdCode || ''
      item.skuId = element.skuId || ''
      item.oInvId = element.invId || ''
      // item.priceInto = element.priceInto||''   
      // item.intoingAmt = element.intoingAmt||''   
      itemList.push(item)
    });

    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.transferTypeName = formData.transferStatusName

    //明细数据
    formData.goodsList = data.dataItem
    formData.goodsList.forEach(element => {
      element.itemQty = element.transferQty
      element.pricePurchase = element.priceInto
      if (element.flgSubUnit) {
        element.calculationFormula = element.packBox + element.unitName + '= 1' + element.subUnitName
        element.packageBox = element['box'] + element.subUnitName + element['piece'] + element.unitName
      }
    });

    wx.setNavigationBarTitle({
      title: '库存调整明细', // mixins.$t('supplierAdd')
    })
    buttonList = []
    readonly = true
    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 = '仓库调整'
    console.log("app.globalData.user", app.globalData.user);
    formData.orgId = app.globalData.user.orgId
    formData.orgName = app.globalData.user.orgName
    formData.staffId = app.globalData.user.staffId
    formData.staffName = app.globalData.user.staffName
    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({});
  },
})