/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：选品
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		 2024-1-23			1.00		    选品
 *******************************************************************************/
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
const config = require('@/config/config.js')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    gradeCode: app.globalData.company.gradeCode,
    firstFlag: true,
    orderBy: [{
        "text": "可售量升序",
        "value": 1
      },
      {
        "text": "可售量降序",
        "value": 2
      }
    ],
    routeObjName: 'goodsSku',
    dataItem: null,
    choosedGoodsList: [],
    commonService: app.globalData['commonService'],
    inventoryService: app.globalData['inventoryService'],
    typeList: [{
      brandName: '全部品牌'
    }],
    brandId: null,
    active: 0,
    popContent: [{
        code: 'itemQty',
        type: 'negativeStep',
        title: '数量',
        required: true
      },
      {
        code: 'whId',
        name: 'whName',
        title: '仓库',
        type: 'choose',
        urlKey: 'chooseWh'
      },
      {
        code: 'skuSpec',
        title: '规格',
        type: 'str',
        readonly: true,
        dropType: ''
      },
      {
        code: 'brandName',
        title: mixins.$t('brandName'),
        type: 'str',
        readonly: true,
      },
      {
        code: 'nonStdCode',
        title: '色号',
        type: 'str',
      },
    ],
    popContentBox: [],
    popupTopObj: [{
      leftTitle: '库存量',
      leftCode: 'usableQty',
      rightTitle: '可售量',
      rightCode: 'invQty'
    }],
    popupTopObjUnit: [{
      leftTitle: '箱',
      leftCode: 'usableQty',
      rightTitle: '片',
      rightCode: 'invQty'
    }],
    // 确定按钮
    buttonList: [{
      name: 'confirm',
      title: '确定'
    }],
    contentList: [],
    saleChannelService: app.globalData['saleChannelService'],
  },
  selectedProduct(e) {
    if (e.currentTarget.dataset.active == 0 && this.data.controlFlags && this.data.controlFlags.choosewhFlag) {
      this.setData({
        // searchContent: [ todo
        //   { code: 'whId', title: mixins.$t('whName'), dropType: 'warehouse', searchType: 'dropSingle' },
        // ],
      })
    } else {
      this.setData({
        searchContent: [],
      })
    }
    this.setData({
      active: e.currentTarget.dataset.active
    })
  },
  onClickLeft() {
    wx.navigateBack({
      data: 1
    })
  },
  /**
   * @desc : 加载数据
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  loadInit() {
    this.setData({
      billType: this.data.item
    })
    //销售选品
    console.log(this.data.item)
    this.getDefChannel() //获取默认渠道
    if (this.data.item == Constants.billType.sale || this.data.item == Constants.billType.saleOut || this.data.item == Constants.billType.saleOutReturn) {
      let buttonList = this.data.buttonList
      buttonList = [{
        name: 'confirm',
        title: '结算',
      }]
      this.setData({
        buttonList: buttonList,
        contentList: [{
            code: 'amount',
            content: 0,
            type: 'number',
            title: mixins.$t("totalAmount")
          },
          {
            type: 'count',
            code: 'count',
            quantity: 0
          }
        ]
      })
    }
    //销售订单
    if (this.data.item == Constants.billType.sale) {
      this.setData({
        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t("count"),
            required: true
          },
          {
            code: 'packageBox',
            type: 'packageBox',
            title: mixins.$t("packageBox"),
          },

          {
            code: 'priceSale',
            type: 'number',
            title: mixins.$t("priceSale"),
            required: true,
            center: 'right'
          },
          // {
          //   code: 'whId',
          //   name: 'whName',
          //   title: mixins.$t("warehouseId"),
          //   type: 'choose',
          //   urlKey: 'openingInventory',
          // },
          {
            code: 'whId',
            name: 'whName',
            title: mixins.$t("warehouseId"),
            type: 'choose',
            urlKey: 'chooseWh'
          },
          {
            code: 'brandName',
            title: mixins.$t('brandName'),
            type: 'str',
            readonly: true,
          },
          {
            code: 'nonStdCode',
            title: mixins.$t("goodsBatch"),
            type: 'str',
          },
          {
            code: 'flgGift',
            title: mixins.$t("flgGift"),
            type: 'checkbox',
          },
          {
            code: 'usePlace',
            title: mixins.$t("usePlace"),
            type: 'str',
          },
        ]
      })
    }
    //库存
    if (this.data.item == Constants.billType.inventory) {
      this.setData({
        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t("count"),
            required: true
          },
          {
            code: 'packageBox',
            type: 'packageBox',
            title: mixins.$t("packageBox"),
          },
          {
            code: 'priceOut',
            type: 'number',
            title: mixins.$t("priceSale"),
            required: true,
            readonly: false
          },

          {
            code: 'whName',
            readonly: true,
            title: mixins.$t("warehouseId"),
            type: 'str'
          },
          {
            code: 'brandName',
            title: mixins.$t('brandName'),
            type: 'str',
            readonly: true,
          },
          {
            code: 'nonStdCode',
            readonly: true,
            title: mixins.$t("goodsBatch"),
            type: 'str',
            tip: mixins.$t('tipPop'),
          },
          {
            code: 'usePlace',
            title: mixins.$t("usePlace"),
            type: 'str',
          },
        ]
      })
    }

    //销售出库
    if (this.data.item == Constants.billType.saleOut) {
      this.setData({

        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t("count"),
            required: true
          },
          {
            code: 'packageBox',
            type: 'packageBox',
            title: mixins.$t("packageBox"),
          },

          {
            code: 'priceOut',
            type: 'number',
            title: mixins.$t("priceSale"),
            required: true,
            readonly: false,
            center: 'right'
          },
          {
            code: 'whId',
            name: 'whName',
            title: mixins.$t("warehouseId"),
            type: 'choose',
            urlKey: 'chooseWh'
          },
          {
            code: 'brandName',
            title: mixins.$t('brandName'),
            type: 'str',
            readonly: true,
          },
          {
            code: 'nonStdCode',
            title: mixins.$t("goodsBatch"),
            type: 'str',
          },
          {
            code: 'usePlace',
            title: mixins.$t("usePlace"),
            type: 'str',
          },
          {
            code: 'flgGift',
            title: mixins.$t("flgGift"),
            type: 'checkbox',
          },
        ]
      })
    }
    //销售退货
    if (this.data.item == Constants.billType.saleOutReturn) {
      this.setData({
        contentList: [{
            code: 'amount',
            content: 0,
            type: 'number',
            title: mixins.$t("totalAmount")
          },
          {
            type: 'count',
            code: 'count',
            quantity: 0
          }
        ],
        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t("count"),
            required: true
          },
          {
            code: 'packageBox',
            type: 'packageBox',
            title: mixins.$t("packageBox"),
          },
          {
            code: 'priceOut',
            type: 'number',
            title: mixins.$t("priceSale"),
            required: true,
            readonly: false,
            center: 'right'
          },
          {
            code: 'whId',
            name: 'whName',
            choosePopupType: '',
            title: mixins.$t("warehouseId"),
            type: 'choose',
            urlKey: 'openingInventory',
          },
          {
            code: 'brandName',
            title: mixins.$t('brandName'),
            type: 'str',
            readonly: true,
          },
          {
            code: 'nonStdCode',
            title: mixins.$t("goodsBatch"),
            type: 'str',
          },
        ]
      })
    }
    //采购退货
    if (this.data.item == Constants.billType.purReturn) {
      this.setData({
        popContent: [{
            code: 'itemQty',
            type: 'step',
            title: mixins.$t("count"),
            required: true
          },
          {
            code: 'packageBox',
            type: 'packageBox',
            title: mixins.$t("packageBox"),
          },
          {
            code: 'priceStandard',
            type: 'number',
            title: mixins.$t("purReturnPrice"),
            required: true,
            readonly: true,
            center: 'right'
          },
          {
            code: 'whId',
            name: 'whName',
            choosePopupType: '',
            title: mixins.$t("warehouseId"),
            type: 'choose',
            urlKey: 'selectInventorySku',
          },
          {
            code: 'brandName',
            title: mixins.$t('brandName'),
            type: 'str',
            readonly: true,
          },
          {
            code: 'nonStdCode',
            title: mixins.$t("goodsBatch"),
            type: 'str',
          },
        ]
      })
    }


    let controlFlags = this.data.controlFlags
    //根据传过来的 控制标识实现对应的逻辑  wyj 不懂问我 
    if (controlFlags) {
      //controlFlags.paramsByWhId 查询商品列表 是否开启顶部选择库区的 库区id 作为参数查询  
      //controlFlags.choosewhReadonly 顶部的选择库区是否可点击选择  直接用布尔值在xml控制了
      //controlFlags.chooseWhByUserDefault 顶部的选择库区是否选择用户默认的库区
      if (controlFlags.choosewhFlag) {
        this.setData({
          // searchContent: [ todo
          //   { code: 'whId', title: mixins.$t('whName'), dropType: 'warehouse', searchType: 'dropSingle' },
          // ],
        })
      }
    }

  },
  /**
   * @desc : 顶部切换
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  changeTag(e) {
    this.setData({
      active: e.detail.index
    })
  },

  /**
   * @desc : 分类切换
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  changeSidebar(e) {
    console.log(e.detail)
    let index = e.detail
    let typeList = this.data.typeList
    this.setData({
      brandId: typeList[index].brandId
    })
    this.searchData()
  },
  /**
   * @desc : 新建档案
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toAddGoods() {
    if (this.data.item == 'inventory') {
      this.toAddOtherWarehousing()
    } else {
      let _this = this
      wx.navigateTo({
        url: '/package-basic-data/pages/product-file/add/add',
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
          res.eventChannel.emit('params', {
            formMode: 'add',
            formType: 'shopping'
          })
        }
      })
    }

  },

  /**
   * @desc : 新建其他入库
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  toAddOtherWarehousing() {
    let this_ = this
    wx.navigateTo({
      url: '/package-inventory/pages/other-warehousing/other-warehousing',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {
          formMode: 'add',
          formType: 'shopping'
        })
      }
    })
  },

  /**
   * @desc : 设置查询参数
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  setSearchParams(params) {
    params.brandId = this.data.brandId //品牌id
    // params.searchText = this.data.searchText
    let controlFlags = this.data.controlFlags
    if (this.data.firstFlag && controlFlags && controlFlags.chooseWhByUserDefault) { //顶部的选择库区是否选择用户默认的库区
      let form = this.data.form || {}
      form.whId = app.globalData.user.defaultWhId
      form.whName = app.globalData.user.defaultWhName
      this.setData({
        form: form
      })
    }
    if (controlFlags && controlFlags.paramsByWhId) {
      params.whId = this.data.form.whId //仓库
    }
    this.setData({
      firstFlag: false
    })
    params.flgValid = true
    return params
  },
  /**
   * @desc : 查询
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  doSearch() {
    this.searchData()
  },
  /**
   * @desc : 查询
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getData(params) {
    console.log('fff', this.data.item);
    if (this.data.item == Constants.billType.sale) {
      return this.excute(this.data.commonService, this.data.commonService.getGoodsForOrderByPage, params);
    } else if (this.data.item == Constants.billType.out || this.data.item == Constants.billType.purReturn || this.data.item == Constants.billType.inventory) {
      params.invQtyFlag = true
      return this.excute(this.data.inventoryService, this.data.inventoryService.selectByCond, params);
    } else if (this.data.item == Constants.billType.saleOut || this.data.item == Constants.billType.saleOutReturn) {
      return this.excute(this.data.commonService, this.data.commonService.getGoodsForOrder, params);
    } else {
      return this.excute(this.data.service, this.data.service.selectByCond, params);
    }
  },

  /**
   * @desc :   处理接口返回数据
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  handleSearchData(tableData) {
    //设置默认仓库
    if (this.data.item !== Constants.billType.out && this.data.item !== Constants.billType.purReturn && this.data.item !== Constants.billType.inventory) {
      tableData.forEach(res => {
        res.whId = app.globalData.user.defaultWhId
        res.whName = app.globalData.user.defaultWhName
      })
      this.setData({
        tableData: tableData
      })
    }
    // 采购订单的时候设置默认非标号
    if (this.data.item == "pur" || this.data.item == "purInto") {
      tableData.forEach(res => {
        res.nonStdCode = "-",
          res.pricePur = res.pricePurchase
      })
      this.setData({
        tableData: tableData
      })
    }
    //处理图片
    if (tableData && tableData.length > 0) {
      tableData.forEach(element => {
        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({
        tableData: tableData
      })
    }
    if (this.data.billType == 'sale' || this.data.billType == 'saleOut' || this.data.billType == 'saleOutReturn') {
      //处理图片
      if (tableData && tableData.length > 0) {
        tableData.forEach(item => {
          if (item.skuImages && item.skuImages.value) {
            item.skuImages.value = JSON.parse(item.skuImages.value)
            console.log('item.skuImages.value', item.skuImages.value[0].url)
            item['imagesUrl'] = item.skuImages.value.length > 0 ? item.skuImages.value[0].url : null
          }
        })
        this.setData({
          tableData: tableData
        })
      }
    }


    if (this.data.controlFlags && this.data.controlFlags.sourcePage == "inventory-adjustment") { //库存调整 设置
      let popContent = this.data.popContent
      let tableData = this.data.tableData
      let index = popContent.findIndex(t => t.code == 'oWhId')
      if (index >= 0) { //进入说明 调整类型是 仓库调整
        popContent[index].urlKey = ''
        let form = this.data.form
        tableData.forEach(res => { //取上面的选择库区组件的值附到源库区 把目标库区 先清掉
          res.oWhId = form.whId
          res.oWhName = form.whName
          res.whId = ''
          res.whName = ''
        })
      }
      let index_ = popContent.findIndex(t => t.code == 'oNonStdCode')
      if (index_ >= 0) { //进入说明 调整类型是 色号调整
        popContent[index_].urlKey = ''
        tableData.forEach(res => { //取上面的选择库区组件的值附到源库区 把目标库区 先清掉
          res.oNonStdCode = res.nonStdCode
          res.nonStdCode = ''
        })
      }

      this.setData({
        popContent: popContent,
        tableData: tableData
      })


    }
    if (this.data.controlFlags && this.data.controlFlags.sourcePage == "purchase-receipt") { //采购入库
      tableData.forEach(res => {
        res.priceInto = res.pricePurchase
      })
      this.setData({
        tableData: tableData
      })
    }
  },
  /**
   * @desc : 删除已选
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  delChoosedGoodsItem(e) {
    console.log('delChoosedGoodsItem', e)
    let index = e.currentTarget.dataset.index
    let choosedGoodsList = this.data.choosedGoodsList
    choosedGoodsList.splice(index, 1)
    this.setData({
      choosedGoodsList: choosedGoodsList
    })
  },




  /**
   * @desc : 获取种类
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getGoodsCategoryNoPage() {
    return this.excute(this.data.commonService, this.data.commonService.getGoodsCategoryNoPage, {}).then(res => {
      this.setData({
        typeList: this.data.typeList.concat(res.data.data)
      })
    })
  },
  /**
   * @desc : 打开商品
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  openAddItemInfo(e) {
    console.log('openAddItemInfo', e)
    let item = e.currentTarget.dataset.item
    item.itemQty = 1 //打开 popur 数量默认为1
    // item.nonStdCode = "-" //不要在这赋值色号 想赋值去查询回来处理的方法去赋值
    if (this.data.item == Constants.billType.saleOut || this.data.item == Constants.billType.saleOutReturn) { //跟进仓库批次号cpid 查询库存
      console.log('globalData', app.globalData)
      item.nonStdCode = item.nonStdCode ? item.nonStdCode : '-'
      item.priceOut = item.priceStandard
      console.log(app.globalData)
      this.getInventory({
        skuId: item.skuId,
        cpId: app.globalData.company.cpId,
        nonStdCode: item.nonStdCode,
      }).then(it => {
        if (it.length > 0) {
          console.log('invId', it[0].invId)
          console.log('invQty', it[0].invQty)
          item.invId = it[0].invId
          item.invQty = it[0].invQty
          item.usableQty = it[0].usableQty

          this.setData({
            dataItem: JSON.stringify(item)
          })
        }

      })
      console.log('item', item)
    } else {
      item.invQty = 0
      item.usableQty = 0
    }
    if (this.data.item == Constants.billType.sale) {
      item.nonStdCode = item.nonStdCode ? item.nonStdCode : '-'
      item.priceSale = item.priceStandard
    }

    if ((this.data.controlFlags && this.data.controlFlags.sourcePage && 'inventory-check' == this.data.controlFlags.sourcePage)) { //库存盘点进 赋值盈亏数量
      item.balanceQty = item.itemQty - item.invQty
    }

    //箱片的取值逻辑： 箱 =(数量/包装）取整，片= （数量%包装）取余数
    if (this.data.item == Constants.billType.sale ||
      this.data.item == Constants.billType.pur ||
      this.data.item == Constants.billType.inventory ||
      this.data.item == Constants.billType.out ||
      this.data.item == Constants.billType.purInto ||
      this.data.item == Constants.billType.saleOutReturn ||
      this.data.item == Constants.billType.purReturn ||
      this.data.item == Constants.billType.saleOut) {
      item['box'] = parseInt(item.itemQty / item.packBox)
      item['piece'] = parseFloat(Number(item.itemQty % item.packBox)).toFixed(item.decimalPlaces);
      item.packageBox = item['box'] + item.subUnitName + item['piece'] + item.unitName
      if (this.data.item == Constants.billType.pur) { //采购订单 采购数量 
        item.pricePur = item.pricePurchase ? item.pricePurchase : 0 //采购价
        item.sumPrice = item['itemQty'] * item.pricePur
      }
      if (this.data.item == Constants.billType.purInto) { //采购入库
        item.priceInto = item.pricePurchase ? item.pricePurchase : 0 //采购价
        item.sumPrice = item['itemQty'] * item.priceInto
      }
      if (this.data.item == Constants.billType.saleOutReturn ||
        this.data.item == Constants.billType.out ||
        this.data.item == Constants.billType.saleOut ||
        this.data.item == Constants.billType.inventory
      ) { //销售退货
        item = this.priceSystem(item, 'priceOut') //根据价格体系取值
        item.priceOut = item.priceStandard ? item.priceStandard : 0 //标价 //销售出库的inventory 
        if (this.data.gradeCode == 'STD') {
          item.priceOut = 0 
        }
        item.sumPrice = item.priceOut * item.itemQty
      }
      if (this.data.item == Constants.billType.purReturn) { //采购退货 
        item.sumPrice = item.priceStandard ? item.priceStandard * item.itemQty : 0
      }
      if(this.data.item == Constants.billType.sale){
        item = this.priceSystem(item, 'priceSale') //根据价格体系取值
      }
    }

    //选了辅助计量单位 正好 包装也有值 那么直接给出公式
    if (item.flgSubUnit && item.subUnitName) {
      item.calculationFormula = item.packBox + item.unitName + '= 1' + item.subUnitName
    }
    this.setData({
      dataItem: JSON.stringify(item),
      showPop: true,
    })
  },
  /**
   * @desc :受默认渠道影响 取价格体系
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  priceSystem(item, priceName) {
    // 价格体系 取值
    if (this.data.channelName) { //受默认渠道影响 取价格体系
      switch (this.data.channelName) {
        case '分销':
          item[priceName] = item.priceWholesale //批发价
          break;
        case '零售':
          item[priceName] = item.priceStandard //销售价
          break;
        default:
          item[priceName] = item.priceOther //其他价
          break;
      }
    } else { //没默认渠道 就取值0
      item[priceName] = 0
    }
    return item
  },
  /**
   * @desc : 设置销售渠道
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getDefChannel() {
    this.excute(this.data.saleChannelService, this.data.saleChannelService.selectByCond, {
      flgDefault: true
    }).then(res => {
      if (res.data.code == 200) {
        if (res.data.data.list && res.data.data.list.length > 0) {
          this.setData({
            channelId: res.data.data.list[0].channelId,
            channelName: res.data.data.list[0].channelName,
            channelCode: res.data.data.list[0].channelCode
          })
        }

      }
    })
  },
  /**
   * @desc   : 再次打开箱片的弹框
   * @author : 周兴
   * @date   : 2024/1/26 11:46
   */
  openPackageBox(e) {
    console.log("openPackageBox-", e);
    let dataItem = JSON.parse(this.data.dataItem)
    //采购入库 销售退货  销售出库
    if (this.data.item == Constants.billType.sale ||
      this.data.item == Constants.billType.purReturn ||
      this.data.item == Constants.billType.pur ||
      this.data.item == Constants.billType.purInto ||
      this.data.item == Constants.billType.saleOutReturn ||
      this.data.item == Constants.billType.out ||
      this.data.item == Constants.billType.saleOut ||
      this.data.item == Constants.billType.inventory) {
      this.setData({
        popContentBox: [{
            code: 'box',
            type: 'step',
            title: dataItem.subUnitName,
            required: true
          },
          {
            code: 'piece',
            type: 'step',
            title: dataItem.unitName,
            required: true
          },
        ],

      })
    }
    this.setData({
      showPopBox: true,
    })
  },
  /**
   * @desc   : 修改str 文本变化
   * @author : 王英杰
   * @date   : 2024/2/2 11:46
   */
  changeField(e) {
    console.log("changeField", e);
    let dataItem = JSON.parse(this.data.dataItem)
    dataItem[e.detail.key] = e.detail.name
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },
  /**
   * @desc   : 修改数值离开框的值
   * @author : 王英杰
   * @date   : 2024/2/2 11:46
   */
  blurNumberField(e) {
    console.log("blurNumberField", e);
    let key = e.detail.key //pop里 修改项的 code
    let dataItem = JSON.parse(this.data.dataItem)
    // 采购订单
    if (this.data.item == Constants.billType.sale ||
      this.data.item == Constants.billType.pur ||
      this.data.item == Constants.billType.purInto ||
      this.data.item == Constants.billType.purReturn) {
      dataItem[key] = e.detail.value
      dataItem.sumPrice = dataItem['itemQty'] * dataItem[key]
    }
    if (this.data.item == Constants.billType.saleOutReturn ||
      this.data.item == Constants.billType.inventory ||
      this.data.item == Constants.billType.saleOut) { //销售退货
      dataItem = this.ifPriceLimited(dataItem, key, e.detail.value) //判断销售限价
      dataItem.sumPrice = dataItem[key] * dataItem.itemQty
    }
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },
  /**
   * @desc : 判断销售限价
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  ifPriceLimited(dataItem, priceName, value) {
    if (dataItem.priceLimited) { //如果有销售限价 那就判断下
      if (dataItem.priceLimited > value) { //低于限价 那就把下限付给销售价格
        dataItem[priceName] = dataItem.priceLimited
      } else {
        dataItem[priceName] = value
      }
    } else {
      dataItem[priceName] = value
    }
    return dataItem
  },

  /**
   * @desc : 数量改变事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  changeStep(e) {
    console.log("changeStep", e);
    let dataItem = JSON.parse(this.data.dataItem)
    let key = e.detail.key
    let value = e.detail.value
    dataItem[key] = value
    if (this.data.billType == Constants.billType.sale ||
      this.data.billType == Constants.billType.pur ||
      this.data.billType == Constants.billType.out ||
      this.data.billType == Constants.billType.purInto ||
      this.data.item == Constants.billType.saleOutReturn ||
      this.data.item == Constants.billType.purReturn ||
      this.data.item == Constants.billType.inventory ||
      this.data.billType == Constants.billType.saleOut) {
      //箱片的取值逻辑： 箱 =(数量/包装）取整，片= （数量%包装）取余数
      if (key == 'itemQty') {
        dataItem['itemQty'] = value
        dataItem['box'] = parseInt(value / dataItem.packBox)
        dataItem['piece'] = parseFloat(Number(value % dataItem.packBox).toFixed(dataItem.decimalPlaces));
        dataItem.packageBox = dataItem['box'] + dataItem.subUnitName + dataItem['piece'] + dataItem.unitName
        if (this.data.billType == Constants.billType.pur) { //采购订单 ，单价*数量，实时变化
          dataItem.sumPrice = dataItem['itemQty'] * dataItem.pricePur
        }
        if (this.data.billType == Constants.billType.purInto) { //采购入库
          dataItem.sumPrice = dataItem['itemQty'] * dataItem.priceInto
        }
        if (this.data.billType == Constants.billType.saleOutReturn ||
          this.data.billType == Constants.billType.saleOut ||
          this.data.billType == Constants.billType.out ||
          this.data.billType == Constants.billType.inventory
        ) {
          //销售退货  
          dataItem.sumPrice = dataItem.priceOut * dataItem.itemQty
        }
        if (this.data.item == Constants.billType.purReturn) {
          dataItem.sumPrice = dataItem.priceStandard * dataItem.itemQty
        }
      }
    }


    //选了辅助计量单位 正好 包装也有值 那么直接给出公式
    if (dataItem.flgSubUnit && dataItem.subUnitName) {
      dataItem.calculationFormula = dataItem.packBox + dataItem.unitName + '= 1' + dataItem.subUnitName
    }
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },

  /**
   * @desc : 查询库存
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getInventory(params) {
    return new Promise((resolve, reject) => {
      this.excute(this.data.commonService, this.data.commonService.getInventory, params).then(res => {
        if (res.data.code == 200) {
          console.log(res.data.data)
          resolve(res.data.data)

        }
      })
    })
  },
  /**
   * @desc : 商品确认事件--箱片的确认
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  editItemsBox(e) {
    let dataItem = JSON.parse(this.data.dataItem)
    if (this.data.billType == Constants.billType.sale ||
      this.data.billType == Constants.billType.pur ||
      this.data.billType == Constants.billType.out ||
      this.data.billType == Constants.billType.purInto ||
      this.data.billType == Constants.billType.saleOutReturn ||
      this.data.billType == Constants.billType.purReturn ||
      this.data.billType == Constants.billType.saleOut ||
      this.data.billType == Constants.billType.inventory
    ) {
      //数量等于 包乘以包装数 加上片数 
      dataItem['itemQty'] = Number(dataItem['box']) * Number(dataItem['packBox']) + Number(dataItem['piece'])
      dataItem.packageBox = dataItem['box'] + dataItem.subUnitName + dataItem['piece'] + dataItem.unitName
      if (this.data.billType == Constants.billType.pur) { //采购订单  ，单价*数量，实时变化
        dataItem.sumPrice = dataItem['itemQty'] * dataItem.pricePur
      }
      if (this.data.billType == Constants.billType.purInto) { //采购入库
        dataItem.sumPrice = dataItem['itemQty'] * dataItem.priceInto
      }
      if (this.data.billType == Constants.billType.saleOutReturn ||
        this.data.billType == Constants.billType.out ||
        this.data.billType == Constants.billType.saleOut ||
        this.data.billType == Constants.billType.inventory) { //销售退货
        dataItem.sumPrice = dataItem.priceOut * dataItem.itemQty
      }
      if (this.data.billType == Constants.billType.purReturn) { //采购退货
        dataItem.sumPrice = dataItem['itemQty'] * dataItem.priceStandard
      }
    }

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

  /**
   * @desc : 商品确认事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  editItems(e) {
    let choosedGoodsList = this.data.choosedGoodsList
    let item = e.detail.form
    if (this.data.billType == Constants.billType.saleOutReturn ||
      this.data.billType == Constants.billType.saleOut ||
      this.data.billType == Constants.billType.inventory) { //校验一下 销售限价
      if (!this.editItemsPriceLimited(item, 'priceOut')) {
        return
      }
    }
    if (this.data.billType == Constants.billType.inventory){ //解决 销售订单的出库 没有价格问题  受销售出库的 选择库存限制
      if (!this.editItemsPriceLimited(item, 'priceOut')) {
        return
      }
      item.priceSale = item.priceOut
    } 
    if (this.data.billType == Constants.billType.sale){ //销售订单 的销售限价
      if (!this.editItemsPriceLimited(item, 'priceSale')) {
        return
      } 
    } 
    choosedGoodsList.push(item)
    this.setData({
      choosedGoodsList: choosedGoodsList
    })
    console.log("choosedGoodsList", choosedGoodsList);
    //销售订单需要计算底部按钮
    if (this.data.item == Constants.billType.sale || this.data.item == Constants.billType.saleOut || this.data.item == Constants.billType.saleOutReturn) {
      this.calculateParameters()
    }
  },

  /**
   * @desc : pop确认的时候 校验销售限价 弹消息
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  editItemsPriceLimited(item, priceName) {
    item[priceName] = Number(item[priceName])
    //校验销售价格输入是否符合规则
    //销售价格不能低于销售限价 
    if (item.flgPrice &&item[priceName] < item.priceLimited) {
      Dialog.alert({
        title: mixins.$t('messages'),
        message:  mixins.$t('priceLimited'),//销售价格不能低于销售限价
      }).then(() => {})
      return false
    }
    return true
  },
  /**
   * @desc : 计算数量金额 销售用
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  calculateParameters() {
    let contentList = this.data.contentList
    let choosedGoodsList = this.data.choosedGoodsList
    let sumPrice = Number(0)
    let sumQty = Number(0)
    choosedGoodsList.forEach(res => {
      if (this.data.billType == 'saleOut') {
        sumPrice += (Number(res.priceOut) * Number(res.itemQty))
      } else if (this.data.billType == 'sale') {
        sumPrice += (Number(res.priceSale) * Number(res.itemQty))
      }

      sumQty += Number(res.itemQty)
    })
    contentList[0].content = sumPrice
    contentList[1].quantity = sumQty
    this.setData({
      contentList: contentList
    })
  },



  /**
   * @desc : 结算按钮
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  submit() {
    const eventChannel = this.getOpenerEventChannel();
    const choosedGoodsList = this.data.choosedGoodsList
    const chooseRoute = this.data.chooseRoute
    let that = this
    if (chooseRoute) { //跳转到上一个页面传过来的url
      wx.navigateTo({
        url: chooseRoute,
        events: {
          // 回调后
          bindData: function (data) {}
        },
        success: function (res) {
          let data = {
            item: choosedGoodsList
          }
          if (that.data.formType == 'customer-reception') { //客户接待跳转过来
            data['formItem'] = that.data.formItem
          }
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('params', data)
        }
      })
    } else {
      eventChannel.emit('bindData', {
        choosedGoodsList
      })
      wx.navigateBack({
        delta: 1
      })
    }

  },

  /**
   * @desc : 下拉多选事件
   * @author : 于继渤
   * @date : 2022/5/26 12:16
   */
  dropdowncommit(e) {
    this.setData({
      whFlag: true
    })
  },
  /**
   * @desc : 下拉多选确定
   * @author : 王英杰
   * @date : 2023年9月8日
   */
  mutiSearch(e) {
    let id = e.target.id
    let form = this.data.form || {}

    if (id === 'warehouse') {
      form.whId = e.detail.item.id
      form.whName = e.detail.item.name
      this.setData({
        whFlag: false,
        form: form
      })
      this.selectComponent("#statusItemWareHouse").toggle(false)
      this.searchData()
    }
  },
  muticlose() {
    this.selectComponent("#statusItemWareHouse").toggle(true)
  },

  onShow() {
    if (this.data.refreshByAdd) {
      // 执行查询方法
      this.searchData()
    }
  },
  /**
   * @desc : 获取品牌
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  getGoodsBrandNoPage() {
    return this.excute(this.data.commonService, this.data.commonService.getGoodsBrandNoPage, {
      flgValid: true
    }).then(res => {
      console.log('getGoodsBrandNoPage', res.data.data)
      this.setData({
        typeList: this.data.typeList.concat(res.data.data)
      })
    })
  },
  /**
   * @desc : 初始化
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  onLoad() {
    this.getGoodsBrandNoPage()
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    })
  },
})