const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
import Dialog from '@/dist/dialog/dialog.js';
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 路由
    routeObjName: 'order',
    gradeCode: app.globalData.company.gradeCode,
    commonService: app.globalData['commonService'],
    validFlag: true,
    customerService: app.globalData['customerService'],
    saleChannelService: app.globalData['saleChannelService'],
    cardList: [{
        name: 'main',
        title: mixins.$t("customerInformation")
      },
      {
        name: 'items',
        title: mixins.$t("goodsDetail"),

        chooseGoodsFlag: false,
        chooseGoodsItemFlag: true,
        chooseInventoryFlag: true,
        chooseCoordinationFlag: true,

        itemAmt: '',
        displayNum: 2
      },
      {
        name: 'other',
        title: mixins.$t("otherInfo")
      }
    ],
    contentObj: {
      main: [{
          code: 'cusName',
          type: 'selectIcon',
          urlKey: 'selectCustomers',
          required: true,
          readonly: false,
          title: mixins.$t('customerName')
        },
        {
          code: 'cusPhone',
          type: 'phone',
          title: mixins.$t('cusPhone'),
          required: true
        },
        {
          code: 'addressFull',
          type: 'address',
          title: mixins.$t('addressFull'),
          required: true
        },
        {
          code: 'addressNo',
          type: 'str',
          required: true,
          title: mixins.$t('addressNo')
        },
        {
          code: 'channelId',
          name: 'channelName',
          required: true,
          title: mixins.$t('saleChannel'),
          type: 'choose',
          urlKey: 'chooseChannel'
        },

        {
          code: 'cusFrom',
          name: 'cusFromName',
          required: true,
          title: mixins.$t('customerSource'),
          type: 'choose',
          urlKey: 'choosecusFrom'
        },

        {
          code: 'contactName',
          type: 'str',
          required: false,
          title: mixins.$t('contactName')
        },
        {
          code: 'contactPhone',
          type: 'str',
          title: mixins.$t('cpPhone'),
          required: false
        },

      ],
      items: [{
          code: 'collectType',
          name: 'collectName',
          type: 'drop',
          dropType: 'collect'
        },
        {
          code: 'collectAmount',
          type: 'number',
          title: mixins.$t("amountCollected")
        }
      ],
      other: [
        // { code: 'contractNo', type: 'textarea', title: mixins.$t("contractNumber"), readonly: false },
        {
          code: 'deliveryDate',
          type: 'date',
          required: false,
          title: mixins.$t("delivery_Time"),
          required: false
        },
        {
          code: 'remarks',
          type: 'textarea',
          title: mixins.$t("remarks"),
          readonly: false
        },
        {
          code: 'file',
          type: 'uploader',
          title: mixins.$t("uploader")
        }
      ]
    },
    //按钮
    buttonSaveList: [{
        code: 'collection',
        title: mixins.$t("collection"),
        plain: true
      },
      {
        code: 'save',
        title: mixins.$t("save")
      }
    ],
    contentSaveList: [{
        code: 'flag',
        title: mixins.$t("saleOutBoundFlag"),
        type: 'checkbox'
      },
      // { code: 'need', title: mixins.$t("saleCollection"), type: 'str' },
      {
        code: 'receivable',
        content: 0,
        type: 'number',
        title: mixins.$t("saleCollection")
      },
      {
        code: 'factAmt',
        content: 0,
        type: 'number',
        title: mixins.$t("factAmt")
      },
    ],
    popContent: [{
        code: 'itemQty',
        type: 'step',
        title: mixins.$t("count"),
        required: true
      },
      {
        code: 'packageBox',
        type: 'packageBox',
        title: mixins.$t("packageBox"),
      },
      // { code: 'box', type: 'step', title: mixins.$t("goodsBox"), required: true },
      // { code: 'piece', type: 'step', title: mixins.$t("goodsPiece"), required: true },
      {
        code: 'priceSale',
        type: 'number',
        title: mixins.$t("priceSale"),
        required: true,
        center: 'right',
        readonly: true
      },
      {
        code: 'factPrice',
        type: 'number',
        title: mixins.$t("factPrice"),
        required: true,
        readonly: true
      },
      {
        code: 'discount',
        title: mixins.$t("goodswholeOrderDiscount"),
        type: 'number',
        digits: 0,
        sign: '',
        percentSignFlag: true,
        inputColor: '#95A8CB'
      },
     
      {
        code: 'whId',
        name: 'whName',
        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',
      },
      {
        code: 'flgGift',
        title: mixins.$t("flgGift"),
        type: 'checkbox',
        tipFlag: true
      },
      {
        code: 'usePlace',
        title: mixins.$t("usePlace"),
        type: 'str',
      },
    ],
    // 新手引导
    step: {
      name: 'order',
      guideList: [{
          el: "#dkForm>>>#cusName",
          tips: mixins.$t('chooseCustomer'),
        },
        {
          el: "#dkForm>>>#items",
          tips: mixins.$t('chooseItems'),
        },
        {
          el: "#saveButton>>>#saveButton",
          tips: mixins.$t('saveAndReceiptButton'),
          fixed: true,
        },
      ]
    },
    table: Constants.tables.order,
    // 系统参数
    flgHandleSetting: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false,
    //欠货开单标识
    flgBackStockInvoicingSetting: app.globalData.setting[Constants.settingCode.IVT002] == "true" ? true : false,
    popContentReverse: [{
        code: 'sumAmount',
        type: 'number',
        title: mixins.$t("totalAmount"),
        readonly: true
      },
      {
        code: 'discount',
        type: 'number',
        title: mixins.$t("wholeOrderDiscount"),
        digits: 0,
        sign: '',
        percentSignFlag: true,
        inputColor: '#95A8CB'
      },
      {
        code: 'discAmt',
        type: 'number',
        title: mixins.$t("sumWaiveAmt"),
      },
      {
        code: 'factAmt',
        type: 'number',
        title: mixins.$t("actualTotalAmount"),
        negativeNumber: true
      },
    ],
  
  },

  /**
   * @desc :  打开反算逻辑pop
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  openReverseCalculationPop() {
    let formData = JSON.parse(this.data.formData)
    if (formData.goodsList.length <= 0) { //没有商品不能点开折扣反算
      return
    }
    let cardList = this.data.cardList
    let contentSaveList = this.data.contentSaveList 
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable'); 
    let index = cardList.findIndex(it => it.name == 'items');
    let dataItem = {}
    dataItem.sumAmount = contentSaveList[index_receivable]['content']//合计金额
    dataItem.discount = cardList[index].discount ? cardList[index].discount : 100 //整单折扣
    dataItem.discAmt = cardList[index].discAmt ? cardList[index].discAmt : 0 //优惠金额
    dataItem.factAmt =   contentSaveList[index_factAmt]['content'] ?  contentSaveList[index_factAmt]['content'] :contentSaveList[index_receivable]['content'] // 实际合计金额
    this.setData({
      dataItem: JSON.stringify(dataItem),
      showReverseCalculationPop: true,
    })
  },
  /**
   * @desc :  总单的各个反算
   * 反算逻辑涉及到五个地方（1，总单的各个反算  2.明细的反算（在dk-form-bill里） 3.点击总单pop确定均分 4.点击明细pop确定反写总单 5明细dpop点击价格 还能弹pop 有点逻辑）
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  blurNumberField(e) {
    console.log('blurNumberField', e);
    let key = e.detail.key
    let value = null
    let dataItem = JSON.parse(this.data.dataItem)
   // 总单折扣=实际合计金额/合计金额
   // 实际合计金额=合计金额-优惠
   // Math.round 四舍五入 取整
    if (key == "discount") //修改整单折扣 
    {
      value = Number(e.detail.value) / 100
      dataItem.discount = value * 100   //整单折扣
      dataItem.factAmt = Number(dataItem.sumAmount) * Number(value)  //实际合计金额 = 合计金额*总单折扣
      dataItem.discAmt = Number(dataItem.sumAmount)-Number(dataItem.factAmt)  // 优惠 = 合计金额-实际合计金额
    }
    if (key == "discAmt") //修改优惠金额
    {
      value = Number(e.detail.value)
      dataItem.discAmt = value    //优惠金额
      dataItem.factAmt = Number(dataItem.sumAmount) - Number(dataItem.discAmt)//实际合计金额 = 合计金额-优惠
      dataItem.discount =  dataItem.sumAmount? Math.round(Number(dataItem.factAmt) / Number(dataItem.sumAmount)*100):0 //总单折扣=实际合计金额/合计金额
    }
    if (key == "factAmt") //修改实际合计金额 
    {
      value = Number(e.detail.value)
      dataItem.factAmt = value  //实际合计金额
      dataItem.discAmt = Number(dataItem.sumAmount)-Number(dataItem.factAmt)  // 优惠 = 合计金额-实际合计金额
      dataItem.discount =  dataItem.sumAmount? Math.round(Number(dataItem.factAmt) / Number(dataItem.sumAmount)*100):100 //总单折扣=实际合计金额/合计金额
    }
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },
  /**
   * @desc :  反算pop 确定按钮
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  editItemsReverse(e) {
    console.log('editItemsReverse', e);
    this.calculateDiscounts()
  },
  /**
   * @desc :  点击总单pop确定均分 
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  calculateDiscounts() {
    let formData = JSON.parse(this.data.formData)
    let goodsList = formData.goodsList
    let dataItem = JSON.parse(this.data.dataItem)
    let contentSaveList = this.data.contentSaveList
    goodsList.forEach(element => {
      element.sumPrice = Number(element.priceSale) * Number(element.itemQty) //求出单品合计
    }); //折扣  
    goodsList = this.distributeValue(goodsList, dataItem.factAmt, "factAmt", "itemQty", "sumPrice") //商品平分实际合计金额
    goodsList.forEach(element => {
      if (!element.flgGift) {
        element.discount = dataItem.discount //商品折扣 = 总单折扣
        element.factPrice = Math.round( (Number(element.factAmt) / Number(element.itemQty) * 100) )/100 //求出实际单价
      }
    }); //折扣 
    formData.goodsList = goodsList
    let cardList = this.data.cardList
    let index = cardList.findIndex(it => it.name == 'items');
    cardList[index].sumAmount = dataItem.sumAmount //合计金额
    cardList[index].discount = dataItem.discount //整单折扣
    cardList[index].discAmt = dataItem.discAmt //优惠金额
    cardList[index].factAmt = dataItem.factAmt // 实际合计金额
    formData.sumAmount = dataItem.sumAmount //合计金额
    formData.discount = dataItem.discount //整单折扣
    formData.discAmt = dataItem.discAmt //优惠金额
    formData.factAmt = dataItem.factAmt // 实际合计金额
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    if (index_factAmt != -1) {
      contentSaveList[index_factAmt]['content'] = dataItem.factAmt
    }
    this.setData({
      formData: JSON.stringify(formData),
      cardList: cardList,
      contentSaveList: contentSaveList
    })
  },
   /**
   * @desc :  点击销售单价和实际单价 弹出pop
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  openPopDkNumberInput(e){
    console.log('openPopDkNumberInput',e);
    let dataItem = JSON.parse(e.detail.dataItem)
    let key = e.detail.key
    if(key=="priceSale"||key=="factPrice"){
       this.setData({
         showChangePrice:true
       })
    }
  },
  /**
   * @desc :  总单分配明细 均分方法
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  distributeValue(goodsList, totalValue, key, itemQty, itemAmt) {
    if (goodsList.length === 0) return []; // 如果列表为空，直接返回空数组   
    let result = [];
    let filterFlgGift = goodsList.filter(it => !!!it["flgGift"]) //过滤掉赠品
    let itemAmtList = filterFlgGift.filter(it => it[itemAmt] > 0) //过滤出金额大于0 的数据
    if (itemAmtList.length > 0) { //按商品金额分份
      let partNmb = Number(itemAmtList.sum(itemAmt))
      let avg = (Number(totalValue) / Number(partNmb)).toFixed(2); // 计算平均值（取两位小数）
      let lastIndexNonZero = -1
      // 为每个元素分配值  
      for (let i = 0; i < goodsList.length; i++) {
        if (goodsList[i][itemAmt] !== 0) {
          lastIndexNonZero = i
        }
        let value = Number(avg) * Number(goodsList[i][itemAmt]); // 占比=销售金额（单品金额乘数量）/合计金额 ：goodsList[i][itemAmt]/itemAmtList.sum(itemAmt)
        goodsList[i][key] = value
        result.push(goodsList[i]); // 将结果添加到数组中  
      }
      goodsList[lastIndexNonZero][key] = 0
      result[lastIndexNonZero][key] = totalValue - goodsList.sum(key) //除了最后一个前面均分 然后最后一个是 总-前面均分的和 
    } else { // 能进入这个方法 goodsLsit 都是有值的  进else 说明 都是金额为0 的数据 按数量分份
      return
      let itemAmtList = goodsList.filter(it => !!!it["flgGift"]) //过滤掉赠品
      let partNmb = itemAmtList.sum(itemQty)
      let avg = (Number(totalValue) / Number(partNmb)).toFixed(2); // 计算平均值（取两位小数）
      let lastIndexNonZero = -1
      // 为每个元素分配值  
      for (let i = 0; i < goodsList.length; i++) {
        if (!goodsList[i]["flgGift"]) {
          lastIndexNonZero = i
          let value = Number(avg) * Number(goodsList[i][itemQty]); // 占比=销售单个品的数量/合计数量
          goodsList[i][key] = value
        }
        result.push(goodsList[i]); // 将结果添加到数组中  
      }
      goodsList[lastIndexNonZero][key] = 0
      result[lastIndexNonZero][key] = totalValue - goodsList.sum(key) //除了最后一个前面均分 然后最后一个是 总-前面均分的和
    }
    return result;
  },
 
  /**
   * @desc   : 手机号离焦事件
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  changePhoneblur(e) {
    let formData = JSON.parse(this.data.formData)
    console.log('cusPhone', formData.cusPhone)
    if (formData.cusPhone) {
      this.getCustomerData({
        cusPhone: formData.cusPhone
      })
    }

  },
  /**
   * @desc : 查询客户信息
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  getCustomerData(params) {
    return this.excute(this.data.customerService, this.data.customerService.selectByCondNoPage, params).then(res => {
      if (res.data.code == 200) {
        if (res.data.data.length > 0) {
          console.log('res', res)
          let formData = JSON.parse(this.data.formData)
          let item = res.data.data[0]
          formData.cusCode = item.cusCode
          formData.cusId = item.cusId
          formData.cusName = item.cusName
          // formData.cusPhone = item.cusPhone
          formData.cusFromName = item.cusFromName
          formData.cusFrom = item.cusFrom
          //处理地址
          formData.address = {
            address: item.addressFull,
            addressFull: item.addressFull,
            addressArea: item.addressArea,
            addressGcj02: item.addressGcj02,
            addressName: item.addressName,
          }
          formData.addressArea = item.addressArea
          formData.addressFull = item.addressFull
          formData.addressGcj02 = item.addressGcj02
          formData.addressName = item.addressName
          formData.addressNo = item.addressNo
          //订单销售渠道 ,默认取的部门的渠道
          // formData.salesChannel = item.channelId
          // formData.channelId = item.channelId
          // formData.channelName = item.channelName
          formData.contactPhone = item.contactPhone
          formData.contactPhone = item.contactPhone

          this.setData({
            formData: JSON.stringify(formData)
          })
        }
      }
    });
  },
  /**
   * @desc   : 选择回调
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  chooseData(e) {
    console.log('eee1', e);
    let item = e.detail.data
    let code = e.detail.code
    let formData = JSON.parse(this.data.formData)
    //设置客户信息
    if (code == 'cusName') {
      formData.cusCode = item.cusCode
      formData.cusId = item.cusId
      formData.cusName = item.cusName
      formData.cusPhone = item.cusPhone
      formData.cusFromName = item.cusFromName
      formData.cusFrom = item.cusFrom
      //处理地址
      formData.address = {
        address: item.addressFull,
        addressFull: item.addressFull,
        addressArea: item.addressArea,
        addressGcj02: item.addressGcj02,
        addressName: item.addressName,
      }
      formData.addressArea = item.addressArea
      formData.addressFull = item.addressFull
      formData.addressGcj02 = item.addressGcj02
      formData.addressName = item.addressName
      formData.addressNo = item.addressNo
      //订单销售渠道 ,默认取的部门的渠道
      formData.salesChannel = item.channelId
      formData.channelId = item.channelId
      formData.channelName = item.channelName
      formData.contactPhone = item.contactPhone
      formData.contactName = item.contactName

      formData.collectAmount = item.receiptResidue
      let cardList = this.data.cardList
      cardList[1].canUseCollect = item.receiptResidue //可用
      cardList[1].useCollect = item.receiptResidue //可用

      formData.canUseCollect = item.receiptResidue //可用
      formData.useCollect = item.receiptResidue //使用
      this.setData({
        cardList: cardList
      })
    }
    ///设置主从业务员
    if (code == 'staff') {
      formData.staff = item.staffItem
      formData['staffId'] = item.staffMain.staffId
      formData['staffName'] = item.staffMain.staffName
      formData['staffList'] = item.staffList
      console.log(item.staffList)
    }
    ///设置主从业务部门
    if (code == 'org') {
      console.log('item', item)
      formData.org = item.orgItem
      formData['orgId'] = item.orgMain.orgId
      formData['orgName'] = item.orgMain.orgName
      formData['flgBusiness'] = item.orgMain.flgBusiness
      formData['orgList'] = item.orgList
    }
    //销售渠道
    if (code == 'channelId') {
      formData.channelId = item.data.id
      formData.channelCode = item.data.code
      formData.channelName = item.data.name
    }
    //客户来源
    if (code == 'cusFrom') {
      formData.cusFromId = item.data.id
      formData.cusFromCode = item.data.code
      formData.cusFromName = item.data.name
      formData.cusFrom = item.data.id
    }
    this.setData({
      formData: JSON.stringify(formData)
    })

  },
  saveChange(e) {
    //校验库存
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    if (btnFormData.flag) {
      this.outBound()
    }
  },
  /**
   * @desc : 底部按钮事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveButton(e) {

    let name = e.detail.name
    if (name == 'save') { //保存
      this.save({})
    } else if (name == 'collection') { //收款
      //跳转收款页
      let formData = JSON.parse(this.data.formData)
      console.log('formData', formData)
      //保存接口并没有计算,因此前台计算
      let list = this.setItemList(formData.goodsList)
      formData.itemList = list //明细
      formData.orderStatus = Constants.orderStatus.STATUS_DEAL //订单状态
      formData.outStatus = Constants.outStatus.unOutBound //出库状态
      formData.makeStaff = app.globalData.user.staffId //制单人
      // formData.amtResidue = formData.amtReceivable //剩余应收 = 应收金额 
      formData.deleteItemList = formData.deleteList ? formData.deleteList : []
      formData.salesChannel = formData.channelId
      delete formData['goodsList']
      formData.objInfo = {}
      formData.objInfo['cusPhone'] = formData.cusPhone
      formData.objInfo['cusName'] = formData.cusName
      formData.objInfo['objectId'] = formData.cusId
      formData.objInfo['addressFull'] = formData.addressFull


      let _this = this
      wx.navigateTo({
        url: this.data.route.selectCollectionConfirm.url,
        events: {
          // 回调后
          bindData: function (data) {}
        },
        success: function (res) {
          //设置参数
          //let item = _this.setSaveData()
          res.eventChannel.emit('params', {
            item: JSON.stringify(formData),
            formType: 8
          })
        }
      })
    }
  },
  /**
   * @desc : 删除明细
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  deleteItemList() {
    console.log('deleteItemList')
    let formData = JSON.parse(this.data.formData)
    this.calculateAmount(formData)
  },
  /**
   * @desc : 设置保存参数
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setParams(params) {
    //保存接口并没有计算,因此前台计算
    let list = this.setItemList(params.goodsList)
    params.itemList = list //明细
    params.orderStatus = Constants.orderStatus.STATUS_DEAL //订单状态
    params.outStatus = Constants.outStatus.unOutBound //出库状态
    params.makeStaff = app.globalData.user.staffId //制单人
    params.amtResidue = params.amtReceivable //剩余应收 = 应收金额 
    params.deleteItemList = params.deleteList ? params.deleteList : []
    params.salesChannel = params.channelId
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    // if (btnFormData.flag) {
    //   //出库
    //   params.outboundProcessingFlag = true
    // }
  // 系统参数【自动办理】关闭，订单开单页面不显示【库存自动办理】，值是不勾选；
  if (!this.data.flgHandleSetting) {
    params.flgAutoHandle = false
  } else {
    params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出入库标识 
    params.outboundProcessingFlag = btnFormData ? btnFormData.flag : false //自动出入库标识 
  }
    delete params['goodsList']
    // return
    return params
  },
  /**
   * @desc : 明细,保存接口并没有计算,因此前台计算
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setItemList(list) {
    for (let i = 0; i < list.length; i++) {
      list[i].itemIndex = i + 1 //序号
    }
    return list
  },
  /**
   * @desc : 清空时调用
   * @date : 2024/4/25 15:49
   * @author : 周兴
   */
  clearAmount() {
    let contentSaveList = this.data.contentSaveList
    contentSaveList.forEach(element => {
      element['content'] = 0
    });
    this.setData({
      contentSaveList: contentSaveList
    })
  },
  /**
   * @desc : 设置商品
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setGoods(e) {
    console.log("jm1", this.data.formData);
    //校验库存
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    if (btnFormData.flag) {
      this.outBound()
    }
    //设置需收款
    let contentSaveList = this.data.contentSaveList
    let formData = JSON.parse(this.data.formData)
    //需收款 = 实际金额 - 使用预存
    let amtReceivable = Number(formData.factAmt - formData.useCollect) 
    formData.factAmt = formData.factAmt  //总单实收金额 =  明细实收金额汇总
    formData.discAmt = Number(formData.sumAmount) - Number(formData.factAmt)   //总单优惠金额 = 合计金额 - 总单实收金额 
    formData.discount = formData.sumAmount? Math.round(Number(formData.factAmt) / Number(formData.sumAmount)*100):100 //总单折扣  = 总单实收金额 /总单合计金额
    //组件显示 需收款 
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    if (index_factAmt != -1) {
      contentSaveList[index_factAmt]['content'] = formData.factAmt
    }
    let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable');
    if (index_receivable != -1) {
      contentSaveList[index_receivable]['content'] = amtReceivable
    }

    //设置应收金额
    formData['amtReceivable'] = amtReceivable
    this.setData({
      formData: JSON.stringify(formData),
      contentSaveList: contentSaveList
    })
 
  },
  //校验库存
  outBound() {
    let formData = JSON.parse(this.data.formData)
    let list = []
    if (formData.goodsList && formData.goodsList.length > 0) {
      formData.goodsList.forEach(res => {
        // res.itemIndex = itemIndex++
        if (res.skuId) {
          list.push({
            skuId: res.skuId,
            nonStdCode: res.nonStdCode,
            whId: res.whId
          })
        }
      })
      if (list.length > 0) {
        //批量查库存
        this.getInventory({
          skuIdNonStdCodeWhIdList: list
        }).then(item => {
          formData.goodsList.forEach(res => {
            if (item.length > 0) {
              let btnFormData = JSON.parse(this.data.btnFormData)
              item.forEach(it => {
                if (it.nonStdCode == res.nonStdCode && it.skuId == res.skuId && it.whId == res.whId) {
                  res.invId = it.invId
                  res.invQty = it.invQty ? it.invQty : 0
                  //销售订单、销售出库、采购退货-自动出库或者办理时要读取系统参数【欠货开单】开启就不判断库存，调取后台自动生成对应入库单
                  if (this.data.flgBackStockInvoicingSetting) {} else {
                    res['itemQty_max'] = res.invQty
                  }
                  res['itemQty_min'] = 1

                  res.usableQty = it.usableQty ? it.usableQty : 0
                } else {
                  res.invQty = 0
                  res.usableQty = 0
                }
              })
            } else {
              res.invQty = 0
              res.usableQty = 0
            }

          })


          this.setData({
            formData: JSON.stringify(formData)
          })

        })
      }
    }

  },



  /**
   * @desc : 查询库存
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getInventory(params) {
    return new Promise((resolve, reject) => {
      this.excute(this.data.commonService, this.data.commonService.getInventoryByList, 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 : 于继渤
   */
  saveData() {
    //判断当前主业务部门标识
    let formData = JSON.parse(this.data.formData)
    if (!formData.flgBusiness) {
      Dialog.confirm({
        message: '当前部门不是业务部门,请选择业务部门',
      }).then(() => {}).catch(() => {})

      return
    }
    if (this.data.formMode == Constants.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 cardList = this.data.cardList
    //处理地址
    data.address = {
      address: data.addressFull,
      addressFull: data.addressFull,
      addressArea: data.addressArea,
      addressGcj02: data.addressGcj02,
      addressName: data.addressName,
    }
    let index = cardList.findIndex(it => it.name == 'items');
    cardList[index].sumAmount = data.sumAmount //合计金额
    cardList[index].sumStandard = data.sumStandard
    cardList[index].sumQuantity = data.sumQuantity
    cardList[index].saleDiscount = data.saleDiscount
    cardList[index].discount = data.discount //整单折扣
    cardList[index].discAmt = data.discAmt //优惠金额
    cardList[index].factAmt = data.factAmt // 实际合计金额 
    let contentSaveList = this.data.contentSaveList
    //组件显示 需收款 
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    if (index_factAmt != -1) {
      contentSaveList[index_factAmt]['content'] = data.factAmt
    }
    let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable');
    if (index_receivable != -1) {
      contentSaveList[index_receivable]['content'] = data.sumAmount
    }
    this.setData({
      cardList: cardList,
      formData: JSON.stringify(data),
      contentSaveList: contentSaveList
    })
    //查询商品明细
    this.getItemDetal(data.orderId)


  },
  /**
   * @desc : 查询商品明细
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getItemDetal(orderId) {
    return this.excute(this.data.service, this.data.service.getOrderForUpdate + '/' + orderId, {}).then(res => {
      if (res.data.code == 200) {
        let formData = JSON.parse(this.data.formData)
        if (res.data.data.dataItem && res.data.data.dataItem.length > 0) {
          res.data.data.dataItem.forEach(item => {
            //处理图片
            if (item.skuImages) {
              item['imagesUrl'] = item.skuImages.length > 0 ? item.skuImages[0].url : null
            }
          })
        }

        formData.goodsList = res.data.data.dataItem
        //处理主从业务员业务部门
        if (res.data.data.staffList) {
          let staffIds = []
          let staffList = []
          let staffNames = []
          res.data.data.staffList.forEach(it => {
            if (it.ownerType == '归属类型-主员工') {
              formData.staffId = it.staffId
            }

            staffList.push({
              staffId: it.staffId,
              staffName: it.staffName,
              ownerFlag: it.ownerType == '归属类型-主员工' ? true : false,
              allocationRatio: it.allocationRatio
            })
            staffIds.push(it.staffId)
            staffNames.push(it.staffName)
          })
          formData['staff'] = {
            text: staffNames.join(","),
            value: staffIds
          }
        }
        if (res.data.data.orgList) {

          let orgIds = []
          let orgList = []
          let orgNames = []
          res.data.data.orgList.forEach(it => {
            if (it.ownerType == '归属类型-主部门') {
              formData.orgId = it.orgId
            }
            orgList.push({
              orgId: it.orgId,
              orgName: it.orgName,
              ownerFlag: it.ownerType == '归属类型-主部门' ? true : false,
              allocationRatio: it.allocationRatio
            })
            orgIds.push(it.orgId)
            orgNames.push(it.orgName)
          })
          formData['org'] = {
            text: orgNames.join(","),
            value: orgIds
          }
        }
        this.setData({
          formData: JSON.stringify(formData)
        })
      }
    });
  },

  /**
   * @desc : 查询默认渠道
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getSaleChannelDef() {
    return this.excute(this.data.saleChannelService, this.data.saleChannelService.selectByCoud, {

    }).then(res => {
      if (res.data.code == 200) {
        // let formData = JSON.parse(this.data.formData)
        // formData.goodsList = res.data.data.orderItem
        // this.setData({
        //   formData: JSON.stringify(formData)
        // })
      }
    });
  },
  /**
   * @desc   : 设置顶部默认值
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  setTopStaffAndOrg(formData) {
    formData['staff'] = {
      text: app.globalData.user.staffName,
      value: [app.globalData.user.staffId]
    }

    formData['org'] = {
      text: app.globalData.user.orgName,
      value: [app.globalData.user.orgId]
    }
    formData.orgId = app.globalData.user.orgId
    console.log('app.globalData.user.flgBusiness', app.globalData.user.flgBusiness);
    formData.flgBusiness = app.globalData.user.flgBusiness
    formData.orgList = [{
      orgId: app.globalData.user.orgId,
      orgName: app.globalData.user.orgName,
      ownerFlag: true,
      allocationRatio: 100,
    }]
    formData.staffId = app.globalData.user.staffId
    formData.staffList = [{
      staffId: app.globalData.user.staffId,
      staffName: app.globalData.user.staffName,
      ownerFlag: true,
      allocationRatio: 100
    }]
    this.setData({
      formData: JSON.stringify(formData)
    })
  },


  editItems() {
    let formData = JSON.parse(this.data.formData)
    this.calculateAmount(formData)
    //校验库存
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    if (btnFormData.flag) {
      this.outBound()
    }
  },

  /**
   * @desc   : 计算金额
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  calculateAmount(formData) {
    let cardList = this.data.cardList
    ///设置总单信息
    console.log('formData1', formData)
    let sumStandard = Number(0)
    let sumAmount = Number(0)
    let factAmt = Number(0)
    let sumQuantity = Number(0)
    formData.goodsList.forEach(item => {
      //标价合计 =  商品标价 x  商品数量
      item.priceStd = item.priceStd ? item.priceStd : item.priceStandard //标价
      item.amtStd = Number(item.priceStd) *  Number(item.itemQty) //合计标价金额
      item.itemAmt =  Number(item.priceSale) *  Number(item.itemQty)
      item.factAmt =  Number(item.factPrice) *  Number(item.itemQty)
      item.priceDiscount = item.priceStandard ? Number(( Number(item.priceSale) /  Number(item.priceStandard)) * 100).toFixed(2) : 100 //售价折扣
      sumStandard +=  Number(item.priceStandard) *  Number(item.itemQty)
      sumAmount +=  Number(item.itemAmt)
      factAmt +=  Number(item.factAmt)
      sumQuantity += Number( item.itemQty) //数量

    })
    formData.sumStandard = sumStandard
    formData.saleDiscount = sumStandard ? Number((sumAmount / sumStandard) * 100).toFixed(2) : 100
    formData.sumAmount = sumAmount
    // formData.canUseCollect = 0
    // formData.useCollect = 0
    formData.sumQuantity = sumQuantity
    formData.factAmt = factAmt  //总单实收金额 =  明细实收金额汇总
    formData.discAmt = sumAmount - factAmt   //总单优惠金额 = 合计金额 - 总单实收金额
    formData.discount = sumAmount? Math.round(Number(factAmt) / Number(sumAmount)*100):100 //总单折扣  = 总单实收金额 /总单合计金额
   
    cardList.forEach(element => {
      if (element.name == "items") {
        element.sumAmount = sumAmount
        element.sumQuantity = formData.sumQuantity
        element.sumStandard = formData.sumStandard
        element.saleDiscount = formData.saleDiscount
      }
    });
    let contentSaveList = this.data.contentSaveList
    //需收款 = 实际金额 - 使用预存
    let amtReceivable = Number(formData.factAmt - formData.useCollect) 
    //组件显示 需收款 
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    if (index_factAmt != -1) {
      contentSaveList[index_factAmt]['content'] = factAmt
    }
    let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable');
    if (index_receivable != -1) {
      contentSaveList[index_receivable]['content'] = amtReceivable
    }
 
    this.setData({
      cardList: cardList,
      contentSaveList: contentSaveList,
      formData: JSON.stringify(formData)
    })

  },
 

  /**
   * 生命周期函数--监听页面加载
   */
  loadInit() { 
    let that = this
    let formData = JSON.parse(this.data.formData)
    if (this.data.formMode == Constants.formMode.add) {
      if (!that.data.flgHandleSetting) {
        this.setData({
          contentSaveList: [{
              code: 'receivable',
              content: 0,
              type: 'number',
              title: mixins.$t("saleCollection")
            },
            {
              code: 'factAmt',
              content: 0,
              type: 'number',
              title: mixins.$t("factAmt")
            },
          ]
        })
      } else {
        this.setData({
          contentSaveList: [{
              code: 'flag',
              title: mixins.$t("saleOutBoundFlag"),
              type: 'checkbox'
            },
            // { code: 'need', title: mixins.$t("saleCollection"), type: 'str' },
            {
              code: 'receivable',
              content: 0,
              type: 'number',
              title: mixins.$t("saleCollection")
            },
            {
              code: 'factAmt',
              content: 0,
              type: 'number',
              title: mixins.$t("factAmt")
            },
          ]
        })
      }
    }


    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: '编辑订单'
      })
      this.setStdAndPro()
      this.setData({
        buttonSaveList: [{
          code: 'save',
          title: mixins.$t("save")
        }]
      })
    } else {
      //设置默认业务员业务部门
      this.setTopStaffAndOrg(formData)
      this.setStdAndPro()
      // 设置送货日期 当前日期 加一天
      var currentDate = new Date();
      currentDate.setDate(currentDate.getDate() + 7);
      formData.deliveryDate = util.formatDayTime(currentDate)
      this.setData({
        formData: JSON.stringify(formData)
      })
    }
  
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('params', function (data) {
      console.log('eventChannel', data)
      if (data && data.goodsList && data.goodsList.length > 0) {
        formData.goodsList = data.goodsList
        that.setData({
          formData: JSON.stringify(formData)
        })
        that.calculateAmount(formData)
      }
      //客户接待过来的
      if (data.formItem) {
        that.setData({
          item: data.formItem
        })
      }
      // 设置客户信息
      that.setCustomerInit(that);

      if (data && data.item && data.item.length > 0) {
        formData.goodsList = data.item
        that.setGoodsAmount(formData)
        that.calculateAmount(formData)
      }
    })
  },
  /**
   * @desc : 设置客户信息
   * @date : 2024/5/24 15:49
   * @author : 周兴
   */
  setCustomerInit(that) {
    let item = that.data.item
    if (!item) return;
    let formData = that.data.formData && JSON.stringify(that.data.formData) !== '{}' ? JSON.parse(that.data.formData) : {}
    formData.cusCode = item.cusCode
    formData.cusId = item.cusId
    formData.cusName = item.cusName
    formData.cusPhone = item.cusPhone
    formData.cusFromName = item.cusFromName
    formData.cusFrom = item.cusFrom
    //处理地址
    formData.address = {
      address: item.addressFull,
      addressFull: item.addressFull,
      addressArea: item.addressArea,
      addressGcj02: item.addressGcj02,
      addressName: item.addressName,
    }
    formData.addressArea = item.addressArea
    formData.addressFull = item.addressFull
    formData.addressGcj02 = item.addressGcj02
    formData.addressName = item.addressName
    formData.addressNo = item.addressNo
    //订单销售渠道 ,默认取的客户的渠道
    formData.salesChannel = item.channelId
    formData.channelId = item.channelId
    formData.channelName = item.channelName
    formData.contactPhone = item.contactPhone
    formData.contactPhone = item.contactPhone
    that.setData({
      formData: JSON.stringify(formData)
    })
  },
  setGoodsAmount(formData) {
    let cardList = this.data.cardList

    let index = cardList.findIndex(it => it.name == 'items');
    if (formData.goodsList && formData.goodsList.length > 0) {
      let sumStandard = Number(0)
      let sumAmount = Number(0)
      let sumQuantity = Number(0)
      formData.goodsList.forEach(item => {
        //标价合计 =  商品标价 x  商品数量
        item.priceStd = item.priceStd ? item.priceStd : (item.priceStandard ? item.priceStandard : 0) //标价
        item.amtStd = Number(item.priceStd * item.itemQty) //合计标价金额
        item.priceSale = item.priceSale ? item.priceSale : item.priceStandard
        item.itemAmt = item.priceSale * item.itemQty //商品金额
        item.priceDiscount = item.priceStd ? Number((item.priceSale / item.priceStd) * 100).toFixed(2) : 100 //售价折扣
        sumQuantity += item.itemQty //数量
        sumAmount += item.priceSale * item.itemQty //没有售价默认取标价
        console.log('111', item.priceStandard)
        console.log('111', item.priceStd)
        sumStandard += (item.priceStd ? item.priceStd : item.priceStandard) * item.itemQty
      })
      //标价合计
      cardList[index].sumStandard = sumStandard
      //销售折扣 (合计金额/标价合计)
      cardList[index].saleDiscount = sumStandard ? Number((sumAmount / sumStandard) * 100).toFixed(2) : 100
      //合计金额
      cardList[index].sumAmount = sumAmount
      cardList[index].sumQuantity = sumQuantity
      //TODO   需要获取当前客户可用预存
      // cardList[index].canUseCollect = 0  //可用
      // cardList[index].useCollect = 0  //使用
      formData.sumStandard = sumStandard
      formData.saleDiscount = cardList[index].saleDiscount
      formData.sumAmount = sumAmount
      // formData.canUseCollect = 0
      // formData.useCollect = 0
      formData.sumQuantity = sumQuantity
    } else {
      cardList[index].sumStandard = 0
      cardList[index].saleDiscount = 0
      cardList[index].sumAmount = 0
      cardList[index].canUseCollect = 0
      cardList[index].useCollect = 0

      formData.sumStandard = 0
      formData.saleDiscount = 0
      formData.sumAmount = 0
      formData.canUseCollect = 0
      formData.useCollect = 0
    }

    this.setData({
      cardList: cardList,
      formData: JSON.stringify(formData)
    })
  },


  changeCheckBox(e) {
    console.log('changeCheckBox', e)
    let formData = JSON.parse(this.data.formData)
    //处理价格为0
    // 是否弹出询问框
    Dialog.confirm({
      message: '是否勾选赠品标识',
    }).then(() => {
      this.selectComponent('#dkForm').setFlgGift(e.detail.code, e.detail.flag, 'flgGift')

    }).catch(() => {

    })
  },


  setStdAndPro() {
    let contentObj = this.data.contentObj
    if (this.data.gradeCode == Constants.gradeCode.STD) {
      contentObj.main = [{
          code: 'cusName',
          type: 'selectIcon',
          urlKey: 'selectCustomers',
          required: true,
          readonly: false,
          title: mixins.$t('customerName')
        },
        {
          code: 'cusPhone',
          type: 'phone',
          title: mixins.$t('cusPhone'),
          required: true
        },
        {
          code: 'addressFull',
          type: 'address',
          title: mixins.$t('addressFull'),
          required: true
        },
        {
          code: 'addressNo',
          type: 'str',
          required: true,
          title: mixins.$t('addressNo')
        },
        {
          code: 'channelId',
          name: 'channelName',
          required: true,
          title: mixins.$t('saleChannel'),
          type: 'choose',
          urlKey: 'chooseChannel'
        },
        {
          code: 'contactName',
          type: 'str',
          required: false,
          title: mixins.$t('contactName')
        },
        {
          code: 'contactPhone',
          type: 'str',
          title: mixins.$t('cpPhone'),
          required: false
        },

      ]
    } else if (this.data.gradeCode == Constants.gradeCode.PRO) {
      contentObj.main = [{
          code: 'cusName',
          type: 'selectIcon',
          urlKey: 'selectCustomers',
          required: true,
          readonly: false,
          title: mixins.$t('customerName')
        },
        {
          code: 'cusPhone',
          type: 'phone',
          title: mixins.$t('cusPhone'),
          required: true
        },
        {
          code: 'addressFull',
          type: 'address',
          title: mixins.$t('addressFull'),
          required: true
        },
        {
          code: 'addressNo',
          type: 'str',
          required: true,
          title: mixins.$t('addressNo')
        },
        {
          code: 'channelId',
          name: 'channelName',
          required: true,
          title: mixins.$t('saleChannel'),
          type: 'choose',
          urlKey: 'chooseChannel'
        },
        {
          code: 'cusFrom',
          name: 'cusFromName',
          required: false,
          title: mixins.$t('customerSource'),
          type: 'choose',
          urlKey: 'choosecusFrom'
        },
        {
          code: 'contactName',
          type: 'str',
          required: false,
          title: mixins.$t('contactName')
        },
        {
          code: 'contactPhone',
          type: 'str',
          title: mixins.$t('cpPhone'),
          required: false
        },
      ]
    }
    this.setData({
      contentObj: contentObj
    })

  },
})