/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		王英杰		 2024-1-24			1.00		    新建商品档案
 *******************************************************************************/
const mixins = require('@/mixins/index.js')
const app = getApp()
const util = require('@/utils/util.js')
const Constants = require('@/utils/Constants')
import Dialog from '@/dist/dialog/dialog.js';
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    gradeCode: app.globalData.company.gradeCode, //判断版本的 （ 标准还是专业）
    buttonList: [{
      name: 'merge',
      title: mixins.$t("save"), //'保存'
    }],
    table: Constants.tables.goodsSku,
    cardList: [], //不在这定义 在 loadinit定义
    contentObj: {
      main: [{ //商品型号
          code: 'skuModel',
          type: 'textarea',
          title: mixins.$t("skuModel"),
          required: true,
        }, { //商品名称
          code: 'skuName',
          type: 'textarea',
          title: mixins.$t("skuName"),
        }, {
          code: 'skuImages',
          name: mixins.$t("commodityPicture"), //商品图片
          type: 'uploader',
        },

      ],
      goods: [{ //商品品牌
          code: 'brandId',
          name: 'brandName',
          title: mixins.$t("goodsBrand"),
          type: 'choose',
          urlKey: 'goodsBrand',
          required: true,
        },
        { //商品种类
          code: 'categoryId',
          name: 'catName',
          title: mixins.$t("goodsCategory"),
          type: 'choose',
          urlKey: 'goodsCategory',
          required: true,

        }, { //商品系列
          code: 'seriesId',
          name: 'seriesName',
          title: mixins.$t("goodsSeries"),
          type: 'choose',
          urlKey: 'goodsSeries',
        }, { //商品规格 
          code: 'skuSpec',
          name: 'skuSpec',
          type: 'textarea',
          required: true,
          title: mixins.$t("sukSpec"),
        }
      ],
      unit: [{ //基本单位
          code: 'unitId',
          name: 'unitName',
          title: mixins.$t("unit"),
          type: 'choose',
          urlKey: 'unit',
          required: true,
          clear: false,
        }, { //辅助单位标识
          type: 'switch',
          title: mixins.$t("subUnitId"),
          code: 'flgSubUnit',
        }, { //包装单位
          code: 'subUnitId',
          name: 'subUnitName',
          title: mixins.$t("packageUnit"),
          type: 'choose',
          urlKey: 'unit',
          required: true,
          readonly: true,
        }, { //包装
          code: 'packBox',
          title: mixins.$t("package"),
          type: 'number',
          sign: "",
          digits: 0,
          required: true,
          readonly: true,
        },
        {
          code: 'calculationFormula',
          type: 'textarea',
          title: mixins.$t("calculationFormula"),
          readonly: true,
        }
      ],
      warehouse: [{ //期初库存标识
        type: 'switch',
        title: mixins.$t("openingInv"),
        code: 'flgOpeningInv',
      }, ],
      price: [{ //期初库存标识
        type: 'switch',
        title: mixins.$t("flgPrice"),
        code: 'flgPrice',
      }, { //采购价
        tip: mixins.$t("purchasePricetip"),
        code: 'pricePurchase',
        type: 'number',
        title: mixins.$t("purchasePrice"),
        required: true,
      }, { //零售价
        tip: mixins.$t("retailPricetip"),
        code: 'priceStandard',
        type: 'number',
        title: mixins.$t("retailPrice"),
        required: true,
      }, { //批发价
        tip: mixins.$t("wholesalePricetip"),
        code: 'priceWholesale',
        type: 'number',
        title: mixins.$t("wholesalePrice"),
        required: true,
      }, { //销售限价
        tip: mixins.$t("SaleSPriceLimittip"),
        code: 'priceLimited',
        type: 'number',
        title: mixins.$t("SaleSPriceLimit"),
        required: true,
      }, { //其他价
        tip: mixins.$t("otherPriceLimittip"),
        code: 'priceOther',
        type: 'number',
        title: mixins.$t("otherPriceLimit"),
        required: true,
      }, ],
      warning: [{ // 预警信息
        type: 'textarea',
        title: mixins.$t("warningLowerLimit"),
        code: 'warningLowerLimit',
      },{
        type: 'textarea',
        title: mixins.$t("warningUpperLimit"),
        code: 'warningUpperLimit',
      }],
      other: [{
        code: 'remarks',
        type: 'textarea',
        title: mixins.$t("remarks"),
      }]
    },
    popContentBox: [],
    // 路由
    routeObjName: 'goodsSku',
    // 包装小数位
    packBoxDigits: 0,
  },
  /**
   * @desc : 数量改变事件
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  changeStep(e) {
    let key = e.detail.key
    let value = e.detail.value
    let dataItem = JSON.parse(this.data.dataItem)
    dataItem[key] = value
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },
  /**
   * @desc : dk-form 里 str的点击回调 的输入回调
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  openStr(e) {
    console.log("openStr", e);
    let code = e.detail.code
    if (code == "packageBox") { //点击包装数量
      let formData = JSON.parse(this.data.formData)
      if (formData.unitId && formData.subUnitId && formData.packBox) {
        let dataItem = this.data.dataItem ? JSON.parse(this.data.dataItem) : {}
        dataItem['box'] = formData.box || 0
        dataItem['piece'] = formData.piece || 0
        dataItem.packageBox = formData.packageBox
        let popContentBox = [{
            code: 'box',
            type: 'step',
            title: formData.subUnitName,
            required: true
          },
          {
            code: 'piece',
            type: 'step',
            title: formData.unitName,
            required: true
          },
        ]
        this.setData({
          showPopBox: true,
          dataItem: JSON.stringify(dataItem),
          popContentBox: popContentBox
        })
      } else {
        util.showToast('请先输入基本单位、包装单位、包装');
      }
    }
  },
  /**
   * @desc : 商品确认事件--箱片的确认
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  editItemsBox(e) {
    let dataItem = JSON.parse(this.data.dataItem)
    let formData = JSON.parse(this.data.formData)
    formData['box'] = dataItem['box']
    formData['piece'] = dataItem['piece']
    formData['intoQty'] = Number(dataItem['box']) * Number(formData['packBox']) + Number(dataItem['piece'])
    formData.packageBox = dataItem['box'] + formData.subUnitName + dataItem['piece'] + formData.unitName
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : dk-form 里 dk-number-input 的输入回调
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  changeNumberField(e) {
    console.log("changeNumberField", e);
    let code = e.detail.code
    let formData = JSON.parse(this.data.formData)
    if (code == "packBox") { //包装 
      if (formData.intoQty || formData.packageBox) {
        //提示
        Dialog.confirm({
          message: '修改包装将清空期初数量、包装数量',
        }).then(() => {
          formData.intoQty = null
          formData.packageBox = null
          formData.box = null
          formData.piece = null
          formData["packBox_"] = formData["packBox"]
          if (formData.packBox && formData.unitName && formData.subUnitName) { //选了辅助计量单位 正好 包装也有值 那么直接给出公式
            formData.calculationFormula = formData.packBox + formData.unitName + '= 1' + formData.subUnitName
          }
          this.setData({
            formData: JSON.stringify(formData)
          })

        }).catch(() => {
          formData["packBox"] = formData["packBox_"]
          this.setData({
            formData: JSON.stringify(formData)
          })
        });

      } else {
        if (formData.packBox && formData.unitName && formData.subUnitName) { //选了辅助计量单位 正好 包装也有值 那么直接给出公式
          formData.calculationFormula = formData.packBox + formData.unitName + '= 1' + formData.subUnitName
        }
        formData["packBox_"] = formData["packBox"]
      }

    }
    if (code == "intoQty" && formData.flgSubUnit) { //期初数量  
      if (formData.unitId && formData.subUnitId && formData.packBox) {
        formData['box'] = parseInt(formData['intoQty'] / formData['packBox'])
        formData['piece'] = parseFloat(Number(formData['intoQty'] % formData['packBox']).toFixed(formData.decimalPlaces));
        formData.packageBox = formData['box'] + formData.subUnitName + formData['piece'] + formData.unitName
      } else {
        formData['intoQty'] = undefined
        util.showToast('请先输入基本单位、包装单位、包装');
      }

    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : dk-form 里 Switch 的切换回调
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  onSwitchChange(e) {
    console.log("Switch", e);

    let code = e.detail.code
    let checkFlag = !e.detail.checkFlag
    let contentObj = this.data.contentObj
    let formData = JSON.stringify(this.data.formData)
    if (code == "flgSubUnit") { //辅助单位
      if (checkFlag) {
        let formData = JSON.parse(this.data.formData)
        // 当未选择基本单位时不能打开辅助单位开关
        if (!formData.unitId) {
          formData.flgSubUnit = false
          util.showToast('请先选择基本单位');
          this.setData({
            formData: JSON.stringify(formData)
          })
          return
        }
        contentObj.unit = [{ //基本单位
            code: 'unitId',
            name: 'unitName',
            title: mixins.$t("unit"),
            type: 'choose',
            urlKey: 'unit',
            required: true,
            clear: false,
          }, { //辅助单位标识
            type: 'switch',
            title: mixins.$t("subUnitId"),
            code: 'flgSubUnit',
          }, { //包装单位
            code: 'subUnitId',
            name: 'subUnitName',
            title: mixins.$t("packageUnit"),
            type: 'choose',
            urlKey: 'unit',
            required: checkFlag,

          }, { //包装
            code: 'packBox',
            title: mixins.$t("package"),
            type: 'number',
            sign: "",
            // todo
            digits: this.packBoxDigits,
            required: checkFlag,
          },
          {
            code: 'calculationFormula',
            type: 'textarea',
            title: mixins.$t("calculationFormula"),
            readonly: true,
          }
        ]
      } else {
        let formDataJson = JSON.parse(this.data.formData)
        if (formDataJson) {  
          ['subUnitName', 'calculationFormula', 'packBox'].forEach(key => {  
            if (formDataJson.hasOwnProperty(key)) {  
              delete formDataJson[key];
            } 
          });  
        }
        this.setData({
          formData: JSON.stringify(formDataJson)
        })
        contentObj.unit = [{ //基本单位
          code: 'unitId',
          name: 'unitName',
          title: mixins.$t("unit"),
          type: 'choose',
          urlKey: 'unit',
          required: true,
          clear: false,
        }, { //辅助单位标识
          type: 'switch',
          title: mixins.$t("subUnitId"),
          code: 'flgSubUnit',
        }, ]
      }

    } else if (code == "flgOpeningInv") { //期初库存标识
      if (checkFlag) {
        let formData = JSON.parse(this.data.formData)
        //打开期初库存的时候 要先判断 需要先选择基本单位
        if (!formData.unitId) {
          formData.flgOpeningInv = false
          util.showToast('请先选择基本单位');
          this.setData({
            formData: JSON.stringify(formData)
          })
          return
        }
        if (formData.flgSubUnit) { //开了辅助单位
          contentObj.warehouse = [{ //期初库存标识
              type: 'switch',
              title: mixins.$t("openingInv"),
              code: 'flgOpeningInv',
            }, { //仓库名称
              code: 'whId',
              name: 'whName',
              title: mixins.$t("whName"),
              type: 'choose',
              urlKey: 'openingInventory',
              required: checkFlag,
            },
            { //库存批号
              code: 'nonStdCode',
              type: 'textarea',
              title: mixins.$t("iinventoryBatchNumber"),
              required: checkFlag,
              tip: mixins.$t('tipPop'),
            },
            { //期初数量
              code: 'intoQty',
              type: 'number',
              sign: "",
              digits: formData.decimalPlaces,
              title: mixins.$t("openingInventoryQty"),
              required: checkFlag,
            },
            {
              code: 'packageBox',
              type: 'str',
              title: mixins.$t("packageBox"),
              required: checkFlag,
              readonly: true,
            },
            { //期初成本价
              code: 'priceInto',
              type: 'number',
              title: mixins.$t("iinitialCostPrice"),
              required: checkFlag,
            },
          ]
        } else { //没开辅助单位
          contentObj.warehouse = [{ //期初库存标识
              type: 'switch',
              title: mixins.$t("openingInv"),
              code: 'flgOpeningInv',
            }, { //仓库名称
              code: 'whId',
              name: 'whName',
              title: mixins.$t("whName"),
              type: 'choose',
              urlKey: 'openingInventory',
              required: checkFlag,
            },
            { //库存批号
              code: 'nonStdCode',
              type: 'textarea',
              title: mixins.$t("iinventoryBatchNumber"),
              required: checkFlag,
              tip: mixins.$t('tipPop'),
            },
            { //期初数量
              code: 'intoQty',
              type: 'number',
              sign: "",
              digits: formData.decimalPlaces,
              title: mixins.$t("openingInventoryQty"),
              required: checkFlag,
            },
            { //期初成本价
              code: 'priceInto',
              type: 'number',
              title: mixins.$t("iinitialCostPrice"),
              required: checkFlag,
            },
          ]
        }

      } else {
        /**
         * 关闭初期按钮后删除对应的初期数据
         * @author 刘尧
         * @data 2024.06.04
         */
        let formData = JSON.parse(this.data.formData)
        if (formData) {  
          ['packageBox', 'priceInto', 'intoQty', 'nonStdCode', 'whName', 'whId'].forEach(key => {  
            if (formData.hasOwnProperty(key)) {  
              delete formData[key];
            } 
          });  
        }
        this.setData({
          formData: JSON.stringify(formData)
        })
        contentObj.warehouse = [{ //期初库存标识
          type: 'switch',
          title: mixins.$t("openingInv"),
          code: 'flgOpeningInv',
        }, ]
      }
    } else if (code == "flgPrice") { //期初库存标识
      if (checkFlag) {
        contentObj.price = [{ //期初库存标识
          type: 'switch',
          title: mixins.$t("flgPrice"),
          code: 'flgPrice',
        }, { //采购价
          tip: mixins.$t("purchasePricetip"),
          code: 'pricePurchase',
          type: 'number',
          title: mixins.$t("purchasePrice"),
          required: checkFlag,
        }, { //零售价
          tip: mixins.$t("retailPricetip"),
          code: 'priceStandard',
          type: 'number',
          title: mixins.$t("retailPrice"),
          required: checkFlag,
        }, { //批发价
          tip: mixins.$t("wholesalePricetip"),
          code: 'priceWholesale',
          type: 'number',
          title: mixins.$t("wholesalePrice"),
          required: checkFlag,
        }, { //销售限价
          tip: mixins.$t("SaleSPriceLimittip"),
          code: 'priceLimited',
          type: 'number',
          title: mixins.$t("SaleSPriceLimit"),
          required: checkFlag,
        }, { //其他价
          tip: mixins.$t("otherPriceLimittip"),
          code: 'priceOther',
          type: 'number',
          title: mixins.$t("otherPriceLimit"),
          required: checkFlag,
        }, ]
      } else {
        contentObj.price = [{ //期初库存标识
          type: 'switch',
          title: mixins.$t("flgPrice"),
          code: 'flgPrice',
        }, ]
      }

    }
    this.setData({
      contentObj: contentObj
    })
  },
  onShow() {
    console.log("onShow");
    this.dialogShowChooseData();
  },
  /**
   * @desc : 因为chooseData 的执行顺序要高于onshow 且 chooseData无法弹 dialog 所以在onshow执行
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  dialogShowChooseData() {
    if (!this.data.handledata) {
      return
    }
    // todo
    this.setData({
      handledata: false
    })
    let formData = JSON.parse(this.data.formData)
    let data = this.data.chooseUnitData 
    let Dialog_message = null
    let code = this.data.chooseDataCode
    if (code == "unitId") { //计量单位
      formData.intoQty = null
      formData.packBox = null
      formData.subUnitId = null
      formData.subUnitName = null
      formData.packageBox = null
      formData.box = null
      formData.piece = null
      // 当重新选择基本单位后清空公式 刘尧 2024.5.30
      formData.calculationFormula = null
      Dialog_message = '更换基础单位将清空包装单位、期初数量、包装、包装数量'
    }
    if (code == "subUnitId") { //包装单位
      formData.intoQty = null
      formData.packageBox = null
      formData.box = null
      formData.piece = null
      Dialog_message = '更换包装单位将清空期初数量、包装数量'
    }
 
    //提示
    Dialog.confirm({
      message: Dialog_message,
    }).then(() => {
      this.handleChooseDataUnit(formData, data, code)
    }).catch(() => {});
  },
  /**
   * @desc : 选择页面跳转回调事件
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  chooseData(e) {

    console.log("chooseData", e, this.data.formData);
    let formData = JSON.parse(this.data.formData)
    let code = e.detail.code
    let data = e.detail.data.data
    if (code == "brandId") { //商品品牌
      formData.brandId = data.id
      formData.brandName = data.name
    }
    if (code == "categoryId") { //商品种类
      formData.categoryId = data.id
      formData.catName = data.name
    }
    if (code == "unitId") { //计量单位
      //当期初数量有值的时候 弹提示是否清除 
      if (formData.intoQty || formData.packBox || formData.subUnitId || formData.packageBox) { //在onshow执行 这里无法弹出dialog  
        this.setData({
          chooseUnitData: data,
          handledata: true,
          chooseDataCode: code
        })
      } else {
        this.handleChooseDataUnit(formData, data, code)
      }

    }
    if (code == "subUnitId") { //辅助计量单位
      if (data.id == formData.unitId) {
        setTimeout(() => {
          util.showToast('包装单位不能等于基本单位');
        }, 1000)
        return
      }
      if (formData.intoQty || formData.packageBox) { //在onshow执行 这里无法弹出dialog 
        this.setData({
          chooseUnitData: data,
          handledata: true,
          chooseDataCode: code
        })
      } else {
        this.handleChooseDataUnit(formData, data, code)
      }
      if (formData.packBox && formData.unitName && formData.subUnitName) { //选了辅助计量单位 正好 包装也有值 那么直接给出公式
        formData.calculationFormula = formData.packBox + formData.unitName + '= 1' + formData.subUnitName
      }
    }
    if (code == "seriesId") { //商品系列
      formData.seriesId = data.id
      formData.seriesName = data.name
    }
    if (code == "whId") { //仓库名称
      formData.whId = data.id
      formData.whName = data.name
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 处理 选择页面回来的 基本单位
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  handleChooseDataUnit(formData, data, code) {

    if (code == "unitId") {
      formData.unitId = data.id
      formData.unitName = data.name
      formData.decimalPlaces = data.decimalPlaces
      let dataItem = this.data.dataItem ? JSON.parse(this.data.dataItem) : {}
      dataItem.decimalPlaces = data.decimalPlaces
      if (formData.packBox && formData.unitName && formData.subUnitName) { //选了辅助计量单位 正好 包装也有值 那么直接给出公式
        formData.calculationFormula = formData.packBox + formData.unitName + '= 1' + formData.subUnitName
      }
      let contentObj = this.data.contentObj
      let packBoxDigits = formData.decimalPlaces
      if (contentObj.warehouse.length > 0) {
        // 遍历 contentObj.warehouse 数组  
        for (let i = 0; i < contentObj.warehouse.length; i++) {
          // 检查当前对象的 code 是否为 'intoQty'  
          if (contentObj.warehouse[i].code === 'intoQty') { //期初数量
            // 如果是，则修改其 digits 属性  
            contentObj.warehouse[i].digits = formData.decimalPlaces;
            contentObj.warehouse[i].readonly = false;
            // 找到后，可以跳出循环（如果确定只有一个匹配项）  
            break;
          }
        }
      }
      if (contentObj.unit.length > 0) {
        // 遍历 contentObj.unit 数组  
        for (let i = 0; i < contentObj.unit.length; i++) {
          // 检查当前对象的 code 是否为 'packBox'  
          if (contentObj.unit[i].code === 'packBox') { //包装
            // 如果是，则修改其 digits 属性  
            contentObj.unit[i].digits = formData.decimalPlaces;
            contentObj.unit[i].readonly = false;
            continue
          }
          if (contentObj.unit[i].code === 'subUnitId') { //包装单位 
            contentObj.unit[i].readonly = false;
            continue
          }
        }
      }
      this.setData({
        packBoxDigits: packBoxDigits,
        contentObj: contentObj,
        formData: JSON.stringify(formData),
        dataItem: JSON.stringify(dataItem)
      })

    }
    if (code == "subUnitId") {
      formData.subUnitId = data.id
      formData.subUnitName = data.name
      this.setData({
        formData: JSON.stringify(formData),
      })
    }
    return
  },
  /**
   * @desc : 保存数据服务--校验
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  validData() {
    let formData = JSON.parse(this.data.formData)
    if (!formData.flgSubUnit) { //辅助单位标识未勾选 不存包装单位 包装
      delete formData.subUnitId
      delete formData.subUnitName
      delete formData.packBox
    }
    //编辑的时候 就不用删除了  因为不允许修改
    if ((!formData.flgOpeningInv) && this.data.formMode !== Constants.formMode.edit) { //期初库存标识未勾选 不存仓库名称 色号 起初数量 期初成本价
      delete formData.whId
      delete formData.whName
      delete formData.nonStdCode
      delete formData.priceInto
    }
    if (!formData.flgPrice) { //价格体系标识未勾选 不存采购价 零售价 批发价 销售限价 其他价
      delete formData.pricePurchase
      delete formData.priceStandard
      delete formData.priceWholesale
      delete formData.priceLimited
      delete formData.priceOther
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
    return true
  },
  // 设置保存参数
  setParams(params) {
    let saveData = JSON.parse(this.data.formData)
    // 修改之后的 值 
    params = Object.assign({}, params, saveData);
    params.serviceCategories = (params.serviceCategories && params.serviceCategories.length > 0) ? params.serviceCategories.split(',') : []
    params.skuImages = params.annexPaths
    params.orgId = app.globalData.user.orgId
    return params
  },


  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  saveData() {
    console.log("参数", this.data.params);
    let that = this
    if (this.data.formMode == Constants.formMode.edit) { //编辑接口
      return this.excute(this.data.service, this.data.service.update, this.data.params)
    } else { //新建接口
      let excute = this.excute(this.data.service, this.data.service.insert, this.data.params)
      excute.then(res => {
        // 增加包装；数字类型正整数，默认1
        let formData = {}
        let contentObj = this.data.contentObj
        formData.flgPrice = true
        formData.flgOpeningInv = false
        formData.flgSubUnit = true

        that.setData({
          formData: JSON.stringify(formData),
          loading: false,
          contentObj: {
            main: [{ //商品型号
                code: 'skuModel',
                type: 'textarea',
                title: mixins.$t("skuModel"),
                required: true,
              }, { //商品名称
                code: 'skuName',
                type: 'textarea',
                title: mixins.$t("skuName"),
              }, {
                code: 'skuImages',
                name: mixins.$t("commodityPicture"), //商品图片
                type: 'uploader',
              },

            ],
            goods: [{ //商品品牌
                code: 'brandId',
                name: 'brandName',
                title: mixins.$t("goodsBrand"),
                type: 'choose',
                urlKey: 'goodsBrand',
                required: true,
              },
              { //商品种类
                code: 'categoryId',
                name: 'catName',
                title: mixins.$t("goodsCategory"),
                type: 'choose',
                urlKey: 'goodsCategory',
                required: true,

              }, { //商品系列
                code: 'seriesId',
                name: 'seriesName',
                title: mixins.$t("goodsSeries"),
                type: 'choose',
                urlKey: 'goodsSeries',


              }, { //商品规格 
                code: 'skuSpec',
                name: 'skuSpec',
                type: 'textarea',
                required: true,
                title: mixins.$t("sukSpec"),
              }
            ],
            unit: [{ //基本单位
                code: 'unitId',
                name: 'unitName',
                title: mixins.$t("unit"),
                type: 'choose',
                urlKey: 'unit',
                required: true,
                clear: false,
              }, { //辅助单位标识
                type: 'switch',
                title: mixins.$t("subUnitId"),
                code: 'flgSubUnit',
              }, { //包装单位
                code: 'subUnitId',
                name: 'subUnitName',
                title: mixins.$t("packageUnit"),
                type: 'choose',
                urlKey: 'unit',
                required: true,
                readonly: true,
              }, { //包装
                code: 'packBox',
                title: mixins.$t("package"),
                type: 'number',
                sign: "",
                digits: 0,
                required: true,
                readonly: true,
              },
              {
                code: 'calculationFormula',
                type: 'textarea',
                title: mixins.$t("calculationFormula"),
                readonly: true,
              }
            ],
            warehouse: [{ //期初库存标识
              type: 'switch',
              title: mixins.$t("openingInv"),
              code: 'flgOpeningInv',
            }, ],
            price: [{ //期初库存标识
              type: 'switch',
              title: mixins.$t("flgPrice"),
              code: 'flgPrice',
            }, { //采购价
              tip: mixins.$t("purchasePricetip"),
              code: 'pricePurchase',
              type: 'number',
              title: mixins.$t("purchasePrice"),
              required: true,
            }, { //零售价
              tip: mixins.$t("retailPricetip"),
              code: 'priceStandard',
              type: 'number',
              title: mixins.$t("retailPrice"),
              required: true,
            }, { //批发价
              tip: mixins.$t("wholesalePricetip"),
              code: 'priceWholesale',
              type: 'number',
              title: mixins.$t("wholesalePrice"),
              required: true,
            }, { //销售限价
              tip: mixins.$t("SaleSPriceLimittip"),
              code: 'priceLimited',
              type: 'number',
              title: mixins.$t("SaleSPriceLimit"),
              required: true,
            }, { //其他价
              tip: mixins.$t("otherPriceLimittip"),
              code: 'priceOther',
              type: 'number',
              title: mixins.$t("otherPriceLimit"),
              required: true,
            }, ],

            other: [{
              code: 'remarks',
              type: 'textarea',
              title: mixins.$t("remarks"),
            }]
          }
        })
      })
      return excute;
    }
  },
  /**
   * @desc : 处理保存后续事件
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  handleSaveData() {
    console.log('eee', this.data.formType, this.data.formType == Constants.formType.shopping);
    //购物车跳转来的,新建完毕直接回到选择界面
    if (this.data.formType == Constants.formType.shopping) {
      // var pages = getCurrentPages();
      // var prevPage = pages[pages.length - 2]; //上一个页面
      // prevPage.setData({
      //   refreshByAdd: true
      // })
      // 给父页面传递数据
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.emit('refresh', {
        id: 1
      })

      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 200)
    }
    //新手引导过来,需要返回
    if (this.data.formReturnMode == Constants.formReturnMode.beginnerGuide) {
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.emit('refresh', {
        id: 1
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 200)
    }
  },
  /**
   * @desc : 页面加载数据方法
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  loadInit() {

    //标准版商品档案新建、编辑、详情不展示价格体系  
    if (this.data.gradeCode == Constants.gradeCode.STD) { //标准版
      this.setData({
        cardList: ['main', 'goods', "unit", "warehouse", 'warning', 'other'],
      })
    } else {
      this.setData({
        cardList: ['main', 'goods', "unit", "warehouse", 'price', 'warning', 'other'],
      })
    }
    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: mixins.$t('editGoodsSuk'),
      })
    } else {
      // 增加包装；数字类型正整数，默认1
      let formData = JSON.parse(this.data.formData) || {}
      console.log('eeee', formData, this.data.formData, this.data.formType);
      formData.flgPrice = true
      formData.flgOpeningInv = false
      formData.flgSubUnit = false

      // 获取表单总信息
      let contentObj = this.data.contentObj
      // 当页面初始化的时候 将其他内容隐藏
      contentObj.unit = [{ //基本单位
        code: 'unitId',
        name: 'unitName',
        title: mixins.$t("unit"),
        type: 'choose',
        urlKey: 'unit',
        required: true,
        clear: false,
      }, { //辅助单位标识
        type: 'switch',
        title: mixins.$t("subUnitId"),
        code: 'flgSubUnit',
      }, ]

      this.setData({
        formData: JSON.stringify(formData),
        contentObj: contentObj
      })
      wx.setNavigationBarTitle({
        title: mixins.$t('addGoodsSuk'),
      })
    }
    console.log('dddddd', this.data.formType);
  },
  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setValuesByEdit(data) {

    // data.serviceCategories = (data.serviceCategories && data.serviceCategories.length > 0) ? data.serviceCategories.join(',') : undefined
    data.annexPaths = data.skuImages
    data.onlyCode = data.skuCode
    
    let contentObj = this.data.contentObj
    // 我们要添加的新对象是  编码  新建的时候没有 编辑的时候添加 
    contentObj.main = [{ //唯一编码
        code: 'onlyCode',
        type: 'textarea',
        title: mixins.$t("onlyCode"),
        readonly: true
      }, { //商品型号
        code: 'skuModel',
        type: 'textarea',
        title: mixins.$t("skuModel"),
        required: true,
      }, { //商品名称
        code: 'skuName',
        type: 'textarea',
        title: mixins.$t("skuName"),
      }, {
        code: 'skuImages',
        name: mixins.$t("commodityPicture"), //商品图片
        type: 'uploader',
      },

    ]
    if (data.flgSubUnit) {
      if (data.inventoryCount !== 0) {
        contentObj.unit = [{
            text: '本商品有库存，不可更改单位模块；需全部出库后才可更改',
            type: 'text',
          }, { //基本单位
            code: 'unitId',
            name: 'unitName',
            title: mixins.$t("unit"),
            type: 'choose',
            urlKey: 'unit',
            required: true,
            readonly: data.inventoryCount !== 0 //要校验库存；  库存量不为0不让更改 
          }, { //辅助单位标识
            type: 'switch',
            title: mixins.$t("subUnitId"),
            code: 'flgSubUnit',
            disabled: (data.inventoryCount !== 0),

          }, { //包装单位
            code: 'subUnitId',
            name: 'subUnitName',
            title: mixins.$t("packageUnit"),
            type: 'choose',
            urlKey: 'unit',
            required: true,
            readonly: data.inventoryCount !== 0 //要校验库存；  库存量不为0不让更改 
          }, { //包装
            code: 'packBox',
            title: mixins.$t("package"),
            type: 'number',
            sign: "",
            digits: 0,
            required: true,
            readonly: data.inventoryCount !== 0
          },
          {
            code: 'calculationFormula',
            type: 'textarea',
            title: mixins.$t("calculationFormula"),
            readonly: true,
          }
        ]
      } else { //没库存
        contentObj.unit = [{ //基本单位
            code: 'unitId',
            name: 'unitName',
            title: mixins.$t("unit"),
            type: 'choose',
            urlKey: 'unit',
            required: true,
            readonly: data.inventoryCount !== 0 //要校验库存；  库存量不为0不让更改 
          }, { //辅助单位标识
            type: 'switch',
            title: mixins.$t("subUnitId"),
            code: 'flgSubUnit',
            disabled: (data.inventoryCount !== 0),

          }, { //包装单位
            code: 'subUnitId',
            name: 'subUnitName',
            title: mixins.$t("packageUnit"),
            type: 'choose',
            urlKey: 'unit',
            required: true,
            readonly: data.inventoryCount !== 0 //要校验库存；  库存量不为0不让更改 
          }, { //包装
            code: 'packBox',
            title: mixins.$t("package"),
            type: 'number',
            sign: "",
            digits: 0,
            required: true,
            readonly: data.inventoryCount !== 0
          },
          {
            code: 'calculationFormula',
            type: 'textarea',
            title: mixins.$t("calculationFormula"),
            readonly: true,
          }
        ]
      }

    } else {
      contentObj.unit = [{ //基本单位
        code: 'unitId',
        name: 'unitName',
        title: mixins.$t("unit"),
        type: 'choose',
        urlKey: 'unit',
        required: true,

      }, { //辅助单位标识
        type: 'switch',
        title: mixins.$t("subUnitId"),
        code: 'flgSubUnit',
      }, ]
    }
    if (data.flgOpeningInv) {
      if (data.flgSubUnit) { //开了辅助单位
        data.packageBox  = data['box'] + data.subUnitName + data['piece'] + data.unitName
        contentObj.warehouse = [{ //期初库存标识
            type: 'switch',
            title: mixins.$t("openingInv"),
            code: 'flgOpeningInv',
            disabled: true,

          }, { //仓库名称
            code: 'whId',
            name: 'whName',
            title: mixins.$t("whName"),
            type: 'choose',
            urlKey: 'openingInventory',
            required: true,
            readonly: true,
          },
          { //库存批号
            code: 'nonStdCode',
            type: 'textarea',
            title: mixins.$t("iinventoryBatchNumber"),
            required: true,
            readonly: true,
            tip: mixins.$t('tipPop'),
          },
          { //期初数量
            code: 'intoQty',
            type: 'number',
            sign: "",
            digits: 0,
            title: mixins.$t("openingInventoryQty"),
            required: true,
            readonly: true,
          },
          {
            code: 'packageBox',
            type: 'str',
            title: mixins.$t("packageBox"),
            required: true,
            readonly: true,
          },
          { //期初成本价
            code: 'priceInto',
            type: 'number',
            title: mixins.$t("iinitialCostPrice"),
            required: true,
            readonly: true,
          },
        ]
      } else {
        contentObj.warehouse = [{ //期初库存标识
            type: 'switch',
            title: mixins.$t("openingInv"),
            code: 'flgOpeningInv',
            disabled: true,

          }, { //仓库名称
            code: 'whId',
            name: 'whName',
            title: mixins.$t("whName"),
            type: 'choose',
            urlKey: 'openingInventory',
            required: true,
            readonly: true,
          },
          { //库存批号
            code: 'nonStdCode',
            type: 'textarea',
            title: mixins.$t("iinventoryBatchNumber"),
            required: true,
            readonly: true,
            tip: mixins.$t('tipPop'),
          },
          { //期初数量
            code: 'intoQty',
            type: 'number',
            sign: "",
            digits: 0,
            title: mixins.$t("openingInventoryQty"),
            required: true,
            readonly: true,
          },
          { //期初成本价
            code: 'priceInto',
            type: 'number',
            title: mixins.$t("iinitialCostPrice"),
            required: true,
            readonly: true,
          },
        ]
      }

    } else {
      contentObj.warehouse = [{ //期初库存标识
        type: 'switch',
        title: mixins.$t("openingInv"),
        code: 'flgOpeningInv',
        disabled: true,
      }, ]
    }
    if (data.flgPrice) {
      contentObj.price = [{ //期初库存标识
        type: 'switch',
        title: mixins.$t("flgPrice"),
        code: 'flgPrice',
      }, { //采购价
        tip: mixins.$t("purchasePricetip"),
        code: 'pricePurchase',
        type: 'number',
        title: mixins.$t("purchasePrice"),
        required: true,
      }, { //零售价
        tip: mixins.$t("retailPricetip"),
        code: 'priceStandard',
        type: 'number',
        title: mixins.$t("retailPrice"),
        required: true,
      }, { //批发价
        tip: mixins.$t("wholesalePricetip"),
        code: 'priceWholesale',
        type: 'number',
        title: mixins.$t("wholesalePrice"),
        required: true,
      }, { //销售限价
        tip: mixins.$t("SaleSPriceLimittip"),
        code: 'priceLimited',
        type: 'number',
        title: mixins.$t("SaleSPriceLimit"),
        required: true,
      }, { //其他价
        tip: mixins.$t("otherPriceLimittip"),
        code: 'priceOther',
        type: 'number',
        title: mixins.$t("otherPriceLimit"),
        required: true,
      }, ]
    } else {
      contentObj.price = [{ //期初库存标识
        type: 'switch',
        title: mixins.$t("flgPrice"),
        code: 'flgPrice',
      }, ]
    }
    if (data.packBox && data.unitName && data.subUnitName) { //选了辅助计量单位 正好 包装也有值 那么直接给出公式
      data.calculationFormula = data.packBox + data.unitName + '= 1' + data.subUnitName
    }

    this.setData({
      contentObj: contentObj,
      formData: JSON.stringify(data),
      buttonList: [{
        name: 'merge',
        title: mixins.$t("save"), //'保存'
      }],
    })

  },
})