/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.销售出库-新建
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		 2024-3-25	    1.00		   	    
 *******************************************************************************/
const Constants = require('@/utils/Constants.js');
import Dialog from '@/dist/dialog/dialog.js';
const mixins = require('@/mixins/index.js')
const util = require('@/utils/util.js')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 路由
    isDetailFlag: false,
    routeObjName: 'outbound',
    table: Constants.tables.order,
    orderService: app.globalData['orderService'],
    saleChannelService: app.globalData['saleChannelService'],
    saleOutBoundService: app.globalData['saleOutBoundService'],
    commonService: app.globalData['commonService'],
    cardList: [{
      name: 'relation'
    },
    {
      name: 'main',
      title: mixins.$t("customerInformation")
    },

    {
      name: 'items',
      title: mixins.$t("goodsDetail"),
      chooseGoodsFlag: false,
      // chooseGoodsItemFlag: true,
      // chooseInventoryFlag: true,
      // chooseCoordinationFlag: true,
      itemAmt: '',
      displayNum: 2,
      controls: [{
        card: 'relation',
        code: 'fromNo'
      }],
    },
    {
      name: 'other',
      title: mixins.$t("otherInfo")
    },

    ],
    cardContentList: [{
      code: 'whId',
      name: 'whName',
      title: mixins.$t("warehouseId"),
      type: 'choose',
      urlKey: 'openingInventory'
    }],
    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
        },
      ],
      relation: [{
        code: 'fromNo',
        name: 'fromNo',
        type: 'choose',
        // titpsKey: 'cusId',
        // titpsMessage: '请选择客户',
        chooseVisible: true,
        controlChooseFlag: true,
        title: mixins.$t("sourceOrder"), //'关联源单'
        urlKey: 'selectSourceSaleOrder'
      }],
      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: 'outDate',
          type: 'date',
          required: false,
          title: mixins.$t("delivery_Time"),
          required: true
        },
        {
          code: 'remarks',
          type: 'textarea',
          title: mixins.$t("remarks"),
          readonly: false
        },
        {
          code: 'file',
          type: 'uploader',
          title: mixins.$t("uploader")
        }
      ]
    },
    //按钮
    buttonSaveList: [
      {
        code: 'save',
        title: mixins.$t("save")
      },
    ],
    contentSaveList: [
      // {
      //   code: 'flag',
      //   title: mixins.$t("autoSaleOutBoundFlag"),
      //   type: 'checkbox'
      // },
      // {
      //   code: 'receivable',
      //   content: 0,
      //   type: 'number',
      //   title: mixins.$t("saleCollection")
      // },
      {
        code: 'factAmt',
        content: 0,
        type: 'number',
        title: mixins.$t("factAmt")
      }
    ],
    popContent: [{
      code: 'outingQty',
      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: 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',
      readonly: true
    },
    {
      code: 'discAsmt',
      type: 'number',
      title: mixins.$t("sumWaiveAmt"),
      required: true,
      readonly: true,
      negativeNumber: true
    },
    {
      code: 'whId',
      name: 'whName',
      choosePopupType: 'inventorySku',
      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',
      tip: mixins.$t('tipPop'),
      readonly: true,
    },

    ],
    popupTopObj: [{
      leftTitle: '库存量',
      leftCode: 'usableQty',
      rightTitle: '可售量',
      rightCode: 'invQty'
    }],
    titpsFlag: true,
    btnFormData: JSON.stringify({
      flag: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false
    }),
    // 系统参数
    flgHandleSetting: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false,
    //欠货开单标识
    flgBackStockInvoicingSetting: app.globalData.setting[Constants.settingCode.IVT002] == "true" ? true : false,
    step: {
      name: 'order-out',
      guideList: [{
        el: "#dkForm>>>#cusName",
        tips: mixins.$t('chooseCustomer'),
      },
      {
        el: "#dkForm>>>#items",
        tips: mixins.$t('chooseItems'),
      },
      {
        el: "#saveButton>>>#saveButton",
        tips: mixins.$t('saveAndReceiptButton'),
        fixed: true,
      },
      ]
    },

    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 index = cardList.findIndex(it => it.name == 'items');
    let dataItem = {}
    dataItem.sumAmount = cardList[index].sumAmount //合计金额
    dataItem.discount = cardList[index].discount ? cardList[index].discount : 100 //整单折扣
    dataItem.discAmt = cardList[index].discAmt ? cardList[index].discAmt : 0 //优惠金额
    dataItem.factAmt = cardList[index].factAmt ? cardList[index].factAmt : cardList[index].sumAmount // 实际合计金额
    this.setData({
      dataItem: JSON.stringify(dataItem),
      showReverseCalculationPop: true,
    })
  },

  /**
   * @desc :  开始反算
   * @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)
    //实际合计金额=合计金额*折扣-优惠（改折扣）
    if (key == "discount") //整单折扣 
    {
      value = Number(e.detail.value) / 100
      dataItem.discount = value * 100
      dataItem.factAmt = Number(dataItem.sumAmount) * Number(value) - Number(dataItem.discAmt)
    }
    if (key == "discAmt") //优惠金额
    {
      value = Number(e.detail.value)
      dataItem.discAmt = value
      dataItem.factAmt = Number(dataItem.sumAmount) * (Number(dataItem.discount) / 100) - Number(value)

    }
    if (key == "factAmt") //实际合计金额
    {
      value = Number(e.detail.value)
      dataItem.factAmt = value
      //折扣 = (实际合计金额+优惠)/合计金额
      dataItem.discount = Math.floor(((Number(value) + Number(dataItem.discAmt)) / Number(dataItem.sumAmount)) * 100)
      if (dataItem.sumAmount != 0) { //预防 算出的折扣是无线循环  差的金额 放到优惠上
        dataItem.discAmt = ((dataItem.sumAmount * (dataItem.discount / 100)) - dataItem.factAmt).toFixed(2)
      }
    }
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },

  /**
   * @desc :  反算pop 确定按钮
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  editItemsReverse(e) {
    console.log('editItemsReverse', e);
    this.calculateDiscounts()
  },
  /**
   * @desc :  计算折扣 
   * @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)
    goodsList = this.distributeValue(goodsList, dataItem.discAmt, "discAsmt", "outingQty", "outingAmt") //商品平分优惠金额
    goodsList = this.distributeValue(goodsList, dataItem.factAmt, "factAmt", "outingQty", "outingAmt") //商品平分实际合计金额
    goodsList.forEach(element => {
      if (!element.flgGift) {
        element.discount = dataItem.discount
        element.factPrice = element.factAmt / element.outingQty
      }
    }); //折扣 
    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 // 实际合计金额
    this.setData({
      formData: JSON.stringify(formData),
      cardList: cardList
    })
  },
  /**
   * @desc :  分配总值到元素列表 
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  distributeValue(goodsList, totalValue, key, itemQty, itemAmt) {
    if (goodsList.length === 0) return []; // 如果列表为空，直接返回空数组   
    let result = [];
    let itemAmtList = goodsList.filter(it => it[itemAmt] > 0) //过滤出金额大于0 的数据
    if (itemAmtList.length > 0) { //按商品金额分份
      let partNmb = 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 = avg * goodsList[i][itemAmt]; // 每个元素首先分配 itemQty乘以 平均值    
        goodsList[i][key] = value
        result.push(goodsList[i]); // 将结果添加到数组中  
      }
      goodsList[lastIndexNonZero][key] = 0
      result[lastIndexNonZero][key] = totalValue - goodsList.sum(key) //除了最后一个前面均分 然后最后一个是 总-前面均分的和
      console.log('杰明', lastIndexNonZero, totalValue, totalValue - result.sum(key));
    } else { // 能进入这个方法 goodsLsit 一是有值的  进else 说明 都是金额为0 的数据 按数量分份
      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 = avg * goodsList[i][itemQty]; // 每个元素首先分配 itemQty乘以 平均值    
          goodsList[i][key] = value
        }
        result.push(goodsList[i]); // 将结果添加到数组中  
      }
      goodsList[lastIndexNonZero][key] = 0
      result[lastIndexNonZero][key] = totalValue - goodsList.sum(key) //除了最后一个前面均分 然后最后一个是 总-前面均分的和
    }
    return result;
  },

  /**
   * @desc :   将日期字符串 "2024-06-10" 转换为时间戳 并且默认时分秒为 00:00:00
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  convertDateStringToTimestamp(dateString) {
    // 假设dateString的格式为"YYYY-MM-DD"  
    const parts = dateString.split('-');
    const year = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1; // 注意JavaScript中的月份是从0开始的  
    const day = parseInt(parts[2], 10);
    // 创建一个新的Date对象，时分秒默认为00:00:00  
    const date = new Date(Date.UTC(year, month, day, 0, 0, 0));
    // 返回时间戳（秒）  
    return date.getTime();
  },
  /**
   * @desc :   编辑
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  toEdit() {
    let this_ = this
    wx.navigateTo({
      url: this_.data.route.add.url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) { }
      },
      success: function (res) {
        res.eventChannel.emit('params', {
          formMode: 'detailEdit',
          id: this_.data.id
        });
      }
    })
  },

  /**
   * @desc :   自动办理事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveChange(e) {
    let btnFormData = JSON.parse(this.data.btnFormData)
    let formData = JSON.parse(this.data.formData)
    let that = this

    if (!btnFormData.flag) {
      //提示
      Dialog.confirm({
        message: mixins.$t("saleOutBoundInfo"),
      }).then(() => { }).catch(() => {
        btnFormData.flag = true
        that.setData({
          titpsFlag: true,
          btnFormData: JSON.stringify(btnFormData)
        })
      });
    }

    formData.goodsList.forEach(res => {
      res.usableQtyInsufficientFlag = JSON.parse(this.data.btnFormData).flag
    })

    this.setData({
      formData: JSON.stringify(formData),
      titpsFlag: JSON.parse(this.data.btnFormData).flag,
      popupTopObj: JSON.parse(this.data.btnFormData).flag ? [{
        leftTitle: '库存量',
        leftCode: 'usableQty',
        rightTitle: '可售量',
        rightCode: 'invQty'
      }] : [],
    })

  },





  /**
   * @desc : 设置保存参数
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setParams(params) {
    let cardList = this.data.cardList
    let index = cardList.findIndex(it => it.name == 'items');
    params.discount = params.sumAmount == 0 ? 0 : (cardList[index].discount ? cardList[index].discount : 100)
    params.discAmt = cardList[index].discAmt ? cardList[index].discAmt : 0
    //设置转出库参数
    if (this.data.formMode == 'add') {
      params.deleteList = []
    }
    params.fromId = params.orderId
    // params.outingAmt = params.outAmt
    // params.outingQty = params.outQty
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    // 销售订单-系统参数【自动办理】-改变 240612
    // 系统参数【自动办理】关闭，订单开单页面不显示【库存自动办理】，值是不勾选；
    if (!this.data.flgHandleSetting) {
      params.flgAutoHandle = false
    } else {
      params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出入库标识 
    }
    params.outAmt = null
    params.outQty = null
    params.goodsList.forEach(res => {
      res.canNegativeFlag = false
      res.outAmt = null
      res.outQty = null
      if (params.flgAutoHandle) {
        res.outBox = res.box
        res.outPiece = res.piece
      } else {
        res.outingBox = res.box
        res.outingPiece = res.piece
      }
      res.sOutId = res.outId
      res.sOutItemId = res.itemId
      // delete
    })

    params.itemList = params.goodsList //明细
    params.makeStaff = app.globalData.user.staffId
    // params.deleteItemList = params.deleteList ? params.deleteList : []

    // 系统参数
    params.flgHandleSetting = this.data.flgHandleSetting
    params.addressName = params.address.addressName ? params.address.addressName : params.address.name
    params.salesChannel = params.channelId
    params.canNegativeFlag = false
    params.outDate = util.formatDayTime(new Date())

    params.btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    if (params.goodsList) { //算出 要收的钱
      let nmb = 0
      params.goodsList.forEach(element => {
        nmb = element.outingAmt + nmb
      });
      params.sumAmtRec = nmb
    }
    params.objInfo = {} //退款页面的 客户信息
    params.objInfo['cusPhone'] = params.cusPhone
    params.objInfo['cusName'] = params.cusName
    params.objInfo['objectId'] = params.cusId
    params.objInfo['addressFull'] = params.addressFull
    params.formType = 11
    delete params['goodsList']
    delete params['orderItemResponseList']
    console.log('params', params)
    // return
    return params
  },
  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveData() {
    if (this.data.formMode == Constants.formMode.detailEdit) { //编辑
      //limitEdit 编辑标识 true 大
      this.data.params.limitEdit = true
      return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.outboundUpdate, this.data.params);
    } else if (this.data.formMode == Constants.formMode.add || this.data.formMode == Constants.formMode.other) { //新建
      return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.outboundInsert, this.data.params);
    } else if (this.data.formMode == Constants.formMode.detail) { //办理
      // 根据状态来决定走哪个分支
      let formData = JSON.parse(this.data.formData)
      // 出库中状态，调取办理的接口
      if (formData.outStatus == Constants.outStatus.outBounding) {
        return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.handleOutbound, this.data.params);
      } else {
        // 已出库，调取办理撤销接口
        return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.saleOrderOutboundCancel, this.data.params);
      }
    }
  },

  /**
   * @desc : 自定义保存参数
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  handleSaveData() {
    let formData = {}
    //设置显示
    this.setFlagView(this)
    //处理默认值  业务员业务部门
    formData = this.setStaffOrg(formData)
    // 设置送货日期 当前日期 加一天
    var currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + 7);
    formData.outDate = util.formatDayTime(currentDate)
    let dataTime = this.convertDateStringToTimestamp(formData.outDate)
    let contentSaveList = this.data.contentSaveList
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable');
    if (index_receivable >= 0) {
      contentSaveList[index_receivable]['content'] = Number(0)
    }
    if (index_factAmt >= 0) {
      contentSaveList[index_factAmt]['content'] = Number(0)
    }
    this.setData({
      formData: JSON.stringify(formData),
      contentSaveList: contentSaveList,
      dataTime: dataTime
    })
  },

  /**
   * @desc : 查询商品明细
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getItemDetal(id, Service, API) { //get_outbound_for_update 
    if (!Service) {
      Service = 'orderService'
      API = 'getOrderForOut'
    }
    return this.excute(this.data[Service], this.data[Service][API] + '/' + id, {}).then(res => {
      if (res.data.code == 200) {
        let formData = JSON.parse(this.data.formData)
        // return
        formData = res.data.data.data
        //销售订单列表转出库
        formData.fromNo = formData.fromNo ? formData.fromNo : formData.orderNo
        //处理地址
        formData.address = this.setAddress(formData)
        //处理明细
        let listData = res.data.data.dataItem
        if (listData && listData.length > 0) {

          if (this.data.formMode == 'other') {
            //过滤可出库量为0的
            listData = listData.filter(item => {
              return item.canOutingQty > 0
            })
          }
          let list = []
          listData.forEach(item => {
            console.log('Service', Service)
            if (this.data.formMode == 'detail' && Service !== 'saleOutBoundService') {
              item.outingQty = item.outQty
              item.outingAmt = Number(item.outingQty * item.priceOut)
            } else if (this.data.formMode == 'other') {
              item.outingQty = item.canOutingQty
              item.outingAmt = Number(item.outingQty * item.priceOut)
            }

            if (item.outStatus == Constants.outStatus.outBounded) { // 出库状态-已出库
              item.box = item.outBox
              item.piece = item.outPiece
            } else {
              item.box = item.outingBox
              item.piece = item.outingPiece
            }

            //出库中 办理详情页
            if (this.data.formMode == 'other' && Service == 'saleOutBoundService') {
              item.outingQty = item.outQty
              item.outingAmt = Number(item.outingQty * item.priceOut)
            }
            //处理图片
            if (item.skuImages) {
              item['imagesUrl'] = item.skuImages.length > 0 ? item.skuImages[0].url : null
            }
            if (item.flgSubUnit && item.subUnitName) {
              item.calculationFormula = item.packBox + item.unitName + '= 1' + item.subUnitName
              item.packageBox = item['outingBox'] + item.subUnitName + item['outingPiece'] + item.unitName
            }
            let btnFormData = JSON.parse(this.data.btnFormData)

            item.outingQty_min = 1 //可出库最小值
            item.outingQty_max = item.canOutingQty
            if (item.skuId && item.whId) {
              list.push({
                skuId: item.skuId,
                nonStdCode: item.nonStdCode,
                whId: item.whId
              })
            }
            item.noshowtitps = (item.skuId == null) ? true : false //是否显示 有货 无货  没有skuId  就是外协商品 
          })
          //处理按钮
          if (res.data.data.data && res.data.data.data.outStatus == mixins.$t("outBoundedOutStatus")) {
            let buttonSaveList = this.data.buttonSaveList
            buttonSaveList = [{
              code: 'detail',
              title: mixins.$t("handleWithdrawal"),
            }]
            this.setData({
              buttonSaveList: buttonSaveList
            })
          }
          if (this.data.formMode == 'detailEdit') {
            let flgAutoHandle = formData.flgAutoHandle
            let flgHandleSetting = formData.flgHandleSetting
            let btnFormData = JSON.stringify({
              flag: formData.flgAutoHandle
            })
            let buttonSaveList = this.data.buttonSaveList
            let contentSaveList = this.data.contentSaveList
            // 编辑不显示自动库存办理标识
            contentSaveList = []
            contentSaveList = [
              {
                code: 'factAmt',
                content: 0,
                type: 'number',
                title: mixins.$t("factAmt")
              },
            ]
            buttonSaveList = [{
              code: 'save',
              title: mixins.$t("save")
            }]
            this.setData({
              checkFlag: true,
              btnFormData: btnFormData,
              flgAutoHandle: flgAutoHandle,
              flgHandleSetting: flgHandleSetting,
              buttonSaveList: buttonSaveList,
              contentSaveList: contentSaveList
            })
          }
          console.log('listData', listData)
          let that = this
          if (list.length > 0) {
            //批量查库存
            this.getInventory({
              skuIdNonStdCodeWhIdList: list
            }).then(item => {
              listData.forEach(res => {
                if (item.length > 0) {
                  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
                      res.usableQty = it.usableQty ? it.usableQty : 0
                    }
                  })
                }


              })
              formData.goodsList = listData
              this.setData({
                formData: JSON.stringify(formData)
              })

              //处理库存量
              this.calculationSalesUsableQty()
            })
          }

        }
        formData.goodsList = listData
        //处理默认值  业务员业务部门
        formData = this.setStaffOrg(formData)

        if (this.data.formMode == Constants.formMode.detail) { //详情
          if (!formData.flgValid) { //作废单据
            this.setData({
              unOrderFlgValid: true,
              buttonSaveList: [],
              // contentSaveList: [
              //   {
              //     code: 'factAmt',
              //     content: 0,
              //     type: 'number',
              //     title: mixins.$t("factAmt")
              //   }],
            })
          }
        }


        //设置选商品不可用
        let cardList = this.data.cardList
        cardList.forEach(element => {
          if (element.name == 'items') {
            element.chooseGoodsFlag = false
          }
        });
        this.calculateAmount(formData)
        this.setData({
          cardList: cardList,
        })
        setTimeout(() => {
          // 刷新商品明细 显示 查看更多
          let card = this.data.cardList.filter(it => it.name == 'items');
          this.selectComponent('#' + this.data.formName).handleContentObj(card[0])
        }, 2000)
      }
    });
  },
  /**
   * @desc : 提示
   * @date : 2024/5/21 15:49
   * @author : 周兴
   */
  showQuestion() {
    return new Promise((resolve, reject) => {
      if (this.data.gradeCode == Constants.gradeCode.STD) {
        let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
        if (!btnFormData.flag) {
          // 是否弹出询问框
          Dialog.confirm({
            message: '不勾选自动库存办理，需要在入库办理中进行办理才能进行出库。',
          }).then(() => {
            resolve(true);
          }).catch(() => {
            resolve(true);
          })
        } else {
          resolve(true);
        }
      } else {
        resolve(true);
      }
    })
  },
  /**
   * @desc : 底部按钮事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveButton(e) {

    let name = e.detail.name
    // this.showQuestion().then(res => {
    //   if (!res) {
    //     return;
    //   }
    //  全-免费版-销售出库-编辑-【自动出库办理】就算没勾选也不要这个提示，直接过
    console.log('nn', name);
    if (name == 'save' || name == 'detail') { //保存
      this.save({})
    } else if (name == 'collection') {
      this.save({
        saveFlag: false,
        url: this.data.route.selectCollectionConfirm.url,
      })
    }
    // })
  },

  /**
   * @desc : 撤回
   * @date : 2024/2/1 15:49
   * @author : 于
   */
  handleWarehousing(e) {
    // let item = {}
    // item.outId = this.data.id
    // this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.saleOrderOutboundCancel, item).then(res => {
    //   if (res.data.code == Constants.SUCESS_CODE) {
    //     // 重新查询
    //     this.searchData()
    //   }
    // })
  },
  /**
   * @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 : 于继渤
   */
  setValuesByEdit(data) {
    let cardList = this.data.cardList
    //处理地址
    data.address = {
      address: data.addressFull,
      addressFull: data.addressFull,
      addressArea: data.addressArea,
      addressGcj02: data.addressGcj02,
      addressName: data.addressName,
    }
    cardList.forEach(element => {
      if (element.name == 'items') {
        element.sumAmount = data.sumAmount
        element.sumStandard = data.sumStandard
        element.sumQuantity = data.sumQuantity
        element.saleDiscount = data.saleDiscount
      }
    })


    this.setData({
      cardList: cardList,
      formData: JSON.stringify(data),
    })
    if (this.data.formMode == 'edit') { //编辑  办理页
      //处理商品
      this.calculateAmount(data, true)
    } else {
      //查询商品明细
      this.getItemDetal(data.orderId)
    }
  },
  /**
   * @desc : 设置商品
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setGoods(e) {
    //设置需收款
    let contentSaveList = this.data.contentSaveList
    let formData = JSON.parse(this.data.formData)
    let itemIndex = 0
    let list = []
    formData.goodsList.forEach(res => {
      res.itemIndex = itemIndex++
      if (res.skuId) {
        list.push({
          skuId: res.skuId,
          nonStdCode: res.nonStdCode,
          whId: res.whId
        })
      } else {
        res.noshowtitps = true
      }
      res.sumPrice = res.priceInto * res.outingQty
    })

    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 (btnFormData.flag && this.data.flgBackStockInvoicingSetting) {} else {
                //   res['outingQty_max'] = res.invQty
                // }
                // if (res['outingQty_max'] && res['outingQty_max'] < res['outingQty']) { 
                //   console.log("1111");
                //   res['outingQty'] = res['outingQty_max']
                //   res['box'] = parseInt(res.outingQty / res.packBox)
                //   res['piece'] = Number(res.outingQty % res.packBox)
                //   res.sumPrice = res['outingQty'] * res.priceOut
                //   res.packageBox = res['box'] + res.subUnitName + res['piece'] + res.unitName
                // }


                res['outingQty_min'] = 1

                res.usableQty = it.usableQty ? it.usableQty : 0
              }

            })
          } else {
            res.invQty = 0
            res.usableQty = 0
          }

        })
        let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
        let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable');
        if (index_receivable >= 0) {
          contentSaveList[index_receivable]['content'] = Number(formData.sumAmount)
        }
        if (index_factAmt >= 0) {
          contentSaveList[index_factAmt]['content'] = Number(formData.factAmt)
        }

        this.setData({
          formData: JSON.stringify(formData),
          contentSaveList: contentSaveList
        })
        //处理库存量
        this.calculationSalesUsableQty('itemQty')
      })
    }



    this.calculateAmount(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('getInventory', res.data.data)
          resolve(res.data.data)

        }
      })
    })

  },

  editItems(e) {
    this.setGoods()
    //处理库存量
    this.calculationSalesUsableQty('outingQty')
    // let formData = JSON.parse(this.data.formData)
    // this.calculateAmount(formData)
  },

  //计算可售量相关
  calculationSalesUsableQty(key) {
    let btnFormData = JSON.parse(this.data.btnFormData)
    //销售订单、销售出库、采购退货-自动出库或者办理时要读取系统参数【欠货开单】开启就不判断库存，调取后台自动生成对应入库单 
    if (btnFormData.flag && this.data.flgBackStockInvoicingSetting) {
      return
    }
    let formData = JSON.parse(this.data.formData)
    formData.goodsList.forEach(res => {
      if (res.invId) {
        //选择的数量大于可售量
        if (Math.abs(key ? res[key] : res.outQty) > res.usableQty) {
          res['usableQtyInsufficientFlag'] = true //可售量不足
          res['usableQty'] = res.usableQty //可售量
          res['titpsItemColorFlagKey'] = true
          res['titpsLabel'] = '缺货'
        } else {
          res['usableQtyInsufficientFlag'] = false //可售量不足
          res['usableQty'] = res.usableQty //可售量
          res['titpsItemColorFlagKey'] = false
          res['titpsLabel'] = '有货'
        }
      } else {
        // res['usableQtyInsufficientFlag'] = true  //可售量不足
        // res['usableQty'] = res.usableQty  //可售量
        res['titpsItemColorFlagKey'] = true
        res['titpsLabel'] = '缺货'
      }

    })
    let usableQtyInsufficientFlagList = formData.goodsList.filter(item => {
      return item.usableQtyInsufficientFlag
    })
    this.setData({
      formData: JSON.stringify(formData),
      goodsTagColor: usableQtyInsufficientFlagList.length > 0 ? '#E4002B' : null //设置颜色
    })
  },








  /**
   * @desc   : 选择回调
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  chooseData(e) {
    let item = e.detail.data
    let code = e.detail.code
    console.log(e)
    let formData = this.data.formData && JSON.stringify(this.data.formData) !== '{}' ? JSON.parse(this.data.formData) : {}
    //设置客户信息
    if (code == 'cusName') {
      formData.cusCode = item.cusCode
      formData.cusId = item.cusId
      formData.objectId = item.cusId
      formData.cusName = item.cusName
      formData.cusPhone = item.cusPhone
      formData.cusFromName = item.cusFromName
      formData.cusFrom = item.cusFrom
      //处理地址
      formData.address = this.setAddress(item)
      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.contactName = item.contactName
      formData.contactPhone = item.contactPhone
    }
    ///设置主从业务员
    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['orgList'] = item.orgList
    }
    //选择源单
    //销售渠道
    if (code == 'channelId') {
      formData.channelId = e.detail.data.data.id
      formData.channelCode = e.detail.data.data.code
      formData.channelName = e.detail.data.data.name
    }
    //客户来源
    if (code == 'cusFrom') {
      formData.cusFrom = e.detail.data.data.id
      formData.cusFromCode = e.detail.data.data.code
      formData.cusFromName = e.detail.data.data.name
    }
    if (code == 'fromNo') {
      console.log('item.itemList', item)
      let btnFormData = JSON.parse(this.data.btnFormData)
      if (item.itemList && item.itemList.length > 0) {
        item.itemList.forEach(res => {
          res.fromId = res.orderId
          res.fromItemId = res.itemId
          res.itemId = null
          //设置最大值
          //销售订单、销售出库、采购退货-自动出库或者办理时要读取系统参数【欠货开单】开启就不判断库存，调取后台自动生成对应入库单
          if (btnFormData.flag && this.data.flgBackStockInvoicingSetting) { } else {
            res['outQty_max'] = res.outQty
          }
          res['outQty_min'] = 1

        })
        formData.goodsList = item.itemList
        formData.fromNo = item.fromNo
        formData.fromId = item.fromId
        this.calculateAmount(formData)
      }



      formData.cusCode = item.item.cusCode
      formData.cusId = item.item.cusId
      formData.objectId = item.item.cusId
      formData.cusName = item.item.cusName
      formData.cusPhone = item.item.cusPhone
      formData.cusFromName = item.item.cusFromName
      formData.cusFrom = item.item.cusFrom
      //处理地址
      formData.address = this.setAddress(item.item)
      formData.addressArea = item.item.addressArea
      formData.addressFull = item.item.addressFull
      formData.addressGcj02 = item.item.addressGcj02
      formData.addressName = item.item.addressName
      formData.addressNo = item.item.addressNo
      //订单销售渠道 ,默认取的客户的渠道
      formData.salesChannel = item.item.channelId
      formData.channelId = item.item.channelId
      formData.channelName = item.item.channelName
      formData.contactPhone = item.item.contactPhone
      formData.contactPhone = item.item.contactPhone
    }
    this.setData({
      formData: JSON.stringify(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)
    })
  },

  /**
   * @desc : 处理地址
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setAddress(item) {
    let address = {
      address: item.addressFull,
      addressFull: item.addressFull,
      addressArea: item.addressArea,
      addressGcj02: item.addressGcj02,
      addressName: item.addressName,
    }
    return address
  },
  changeStepForm(e) {

  },
  /**
   * @desc   : 计算金额
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  calculateAmount(formData, flgEdit) {
    ///设置总单信息
    let sumAmount = Number(0)
    let factAmt = Number(0)
    let sumQuantity = Number(0)
    let sumStandard = Number(0)
    formData.goodsList.forEach(item => {
      if (item.flgGift) {//赠品
        item.priceOut = Number(0)
        item.factPrice = Number(0)
        item.discount = Number(0)
        item.discAsmt = Number(0)
      }
      //标价合计 =  商品标价 x  商品数量
      item.outingAmt = item.outingQty * item.priceOut
      sumAmount += item.outingQty * item.priceOut
      factAmt += item.outingQty * item.factPrice

      sumQuantity += Number(item.outingQty) //数量
      item.priceDiscount = Number((item.priceOut / item.priceStandard) * 100).toFixed(2) //售价折扣
      sumStandard += item.priceStandard * item.outingQty

      if (item.flgSubUnit && item.subUnitName) {
        item.box = (item.box != null) ? item.box : item.outingBox
        item.piece = (item.piece != null) ? item.piece : item.outingPiece
        item.calculationFormula = item.packBox + item.unitName + '= 1' + item.subUnitName
        item.packageBox = item['box'] + item.subUnitName + item['piece'] + item.unitName
      }

    })

    formData.sumAmount = sumAmount
    formData.factAmt = factAmt
    formData.outingAmt = sumAmount
    formData.sumStandard = sumStandard
    formData.saleDiscount = Number((sumAmount / sumStandard) * 100).toFixed(2)
    formData.canUseCollect = 0
    formData.useCollect = 0
    formData.sumQuantity = sumQuantity
    formData.outingQty = sumQuantity
    let cardList = this.data.cardList
    let contentSaveList = this.data.contentSaveList
    console.log(' formData.sumAmount', formData.sumAmount)
    cardList.forEach(element => {
      if (element.name == "items") {
        element.sumAmount = formData.sumAmount
        element.sumQuantity = formData.sumQuantity
        element.sumStandard = formData.sumStandard
        element.saleDiscount = formData.saleDiscount
      }
    });

    //详情 办理
    let index_factAmt = contentSaveList.findIndex(it => it.code == 'factAmt');
    // let index_receivable = contentSaveList.findIndex(it => it.code == 'receivable');
    // contentSaveList[index_receivable]['content'] = Number(formData.sumAmount)
    if (index_factAmt >= 0) {
      contentSaveList[index_factAmt]['content'] = Number(formData.factAmt)
    }
    this.setData({
      cardList: cardList,
      contentSaveList: contentSaveList,
      formData: JSON.stringify(formData)
    })

  },

  /**
   * @desc : 设置顶部默认值
   * @date : 2024/3/28 15:49
   * @author : 于继渤
   */
  setStaffOrg(formData) {
    formData['staff'] = {
      text: formData.staffName ? formData.staffName : app.globalData.user.staffName,
      value: [formData.staffId ? formData.staffId : app.globalData.user.staffId]
    }
    formData['org'] = {
      text: formData.orgName ? formData.orgName : app.globalData.user.orgName,
      value: [formData.orgId ? formData.orgId : app.globalData.user.orgId]
    }
    formData.orgId = formData.orgId ? formData.orgId : app.globalData.user.orgId
    formData.staffId = formData.staffId ? formData.staffId : app.globalData.user.staffId

    return formData

  },



  /**
   * @desc : 设置表单 
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setFormMain() {
    let contentObj = this.data.contentObj
    let cardList = this.data.cardList
    let buttonSaveList = this.data.buttonSaveList
    let contentSaveList = this.data.contentSaveList
    let popContent = this.data.popContent

    if (this.data.gradeCode == Constants.gradeCode.STD) {
      contentObj.main = [{
        code: 'cusName',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('customerName')
      },
      {
        code: 'cusPhone',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('cusPhone')
      },
      {
        code: 'addressFull',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('addressFull')
      },
      {
        code: 'addressNo',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('addressNo')
      },
      {
        code: 'channelName',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('saleChannel')
      },
      {
        code: 'contactName',
        type: 'str',
        readonly: true,
        title: mixins.$t('contactName')
      },
      {
        code: 'contactPhone',
        type: 'str',
        readonly: true,
        title: mixins.$t('cpPhone'),
      },
      ]
    } else if (this.data.gradeCode == Constants.gradeCode.PRO) {
      contentObj.main = [{
        code: 'cusName',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('customerName')
      },
      {
        code: 'cusPhone',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('cusPhone')
      },
      {
        code: 'addressFull',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('addressFull')
      },
      {
        code: 'addressNo',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('addressNo')
      },
      {
        code: 'channelName',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('saleChannel')
      },
      {
        code: 'cusFromName',
        type: 'str',
        readonly: true,
        required: false,
        title: mixins.$t('customerSource')
      },
      {
        code: 'contactName',
        type: 'str',
        readonly: true,
        title: mixins.$t('contactName')
      },
      {
        code: 'contactPhone',
        type: 'str',
        readonly: true,
        title: mixins.$t('cpPhone'),
      },
      ]
    }

    this.setData({
      contentObj: contentObj
    })

    contentObj.relation = [{
      code: 'fromNo',
      type: 'str',
      title: mixins.$t("sourceOrder"), //'关联源单'
      readonly: true,
    }]

    contentObj.other = [{
      code: 'outDate',
      type: 'str',
      readonly: true,
      required: false,
      title: mixins.$t('delivery_Time')
    },
    {
      code: 'remarks',
      type: 'str',
      readonly: true,
      required: false,
      title: mixins.$t('remarks')
    },
    {
      code: 'file',
      type: 'uploader',
      title: mixins.$t("uploader")
    }
    ]

    cardList = [
      {
        name: 'relation'
      },
      {
        name: 'main',
        title: mixins.$t("customerInformation")
      },

      {
        name: 'items',
        title: mixins.$t("goodsDetail"),
        chooseGoodsFlag: false,
        itemAmt: '',
        displayNum: 2
      },
      {
        name: 'other',
        title: mixins.$t("otherInfo")
      }
    ]
    //详情(办理)
    if (this.data.formMode == Constants.formMode.detail) {
      //按钮
      buttonSaveList = [{
        code: 'save',
        title: mixins.$t("outProcessing")
      }]
      contentSaveList = [
        // { 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: 'outingQty',
        type: 'step',
        title: mixins.$t("count"),
        required: true,
      },
      {
        code: 'packageBox',
        type: 'packageBox',
        title: mixins.$t("packageBox"),
      },
      // { code: 'outingBox', type: 'step', title: mixins.$t("goodsBox"), required: true, readonly: true },
      // { code: 'outingPiece', type: 'step', title: mixins.$t("goodsPiece"), required: true, readonly: true },
      {
        code: 'priceOut',
        type: 'number',
        title: mixins.$t("priceSale"),
        required: true,
        readonly: true
      },

      {
        code: 'whName',
        title: mixins.$t("warehouseId"),
        type: 'str',
        readonly: true,
        readonly: true
      },
      {
        code: 'nonStdCode',
        title: mixins.$t("goodsBatch"),
        type: 'str',
        readonly: true
      },
      ]
    }
    this.setData({
      contentObj: contentObj,
      cardList: cardList,
      popContent: popContent,
      contentSaveList: contentSaveList,
      buttonSaveList: buttonSaveList,
    })

  },


  /**
   * 生命周期函数--监听页面加载
   */
  loadInit() {
    let title = title = mixins.$t('order_out')
    console.log(app.globalData.setting);
    let formData = JSON.parse(this.data.formData)
    if (this.data.formMode == Constants.formMode.other) { //转出库
      //查询可出库销售订单/商品
      this.setFormMain()
      this.getItemDetal(this.data.item.orderId)
      // 设置送货日期 当前日期 加一天
      var currentDate = new Date();
      currentDate.setDate(currentDate.getDate() + 7);
      formData.outDate = util.formatDayTime(currentDate)
      let dataTime = this.convertDateStringToTimestamp(formData.outDate)
      this.setData({
        formData: JSON.stringify(formData),
        dataTime: dataTime
      })
    } else if (this.data.formMode == Constants.formMode.add) { //新建 
      //购物车 标准版 跳入 销售入库
      let that = this
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('params', function (data) {
        if (data && data.goodsList && data.goodsList.length > 0) {
          formData = JSON.parse(that.data.formData)
          console.log('formData11', formData);
          formData.goodsList = data.goodsList
          formData.goodsList.forEach((element, index) => {
            element.itemIndex = index
            element.outingQty = element.itemQty
            element.priceOut = element.priceSale
          });
          that.setData({
            formData: JSON.stringify(formData)
          })
          that.calculateAmount(formData)
        }
      })
      //详情办理
      wx.setNavigationBarTitle({
        title: mixins.$t('add') + title
      })
      // 标准版，自动出库办理标识默认勾上
      if (this.data.gradeCode == Constants.gradeCode.STD) {
        //处理默认值  业务员业务部门
        let buttonSaveList = this.data.buttonSaveList
        //按钮
        buttonSaveList = [
          // {
          //   code: 'collection',
          //   width: "200rpx",
          //   title: mixins.$t("paySave")
          // },
          {
            code: 'save',
            title: mixins.$t("save")
          }
        ]
        let btnFormData = JSON.parse(this.data.btnFormData) || {}
        btnFormData.flag = true

        this.setData({
          btnFormData: JSON.stringify(btnFormData),
          buttonSaveList: buttonSaveList
        })
      }

      //设置显示 
      this.setFlagView(this)
      //处理默认值  业务员业务部门
      formData = this.setStaffOrg(formData)
      // 设置送货日期 当前日期 加一天
      var currentDate = new Date();
      currentDate.setDate(currentDate.getDate() + 7);
      formData.outDate = util.formatDayTime(currentDate)
      let dataTime = this.convertDateStringToTimestamp(formData.outDate)
      this.setData({
        formData: JSON.stringify(formData),
        dataTime: dataTime
      })
      //从客户详情中调转过来后有客户信息，设置客户信息
      // 240611 注释 从客户信息调转到订单了。不会走销售出库
      // this.setCustomerInit(this);

    } else if (this.data.formMode == Constants.formMode.detail) { //详情
      //详情办理
      wx.setNavigationBarTitle({
        title: title + '详情'
      })

      //设置只读
      this.setFormMain()
      this.setFlagView(this)
      this.getItemDetal(this.data.id, 'saleOutBoundService', 'getOutboundForUpdate')
      this.setData({
        isDetailFlag: true,
      })
      this.setData({
        formData: JSON.stringify(formData),
        // contentSaveList: [
        //   {
        //     code: 'factAmt',
        //     content: 0,
        //     type: 'number',
        //     title: mixins.$t("factAmt")
        //   }
        // ]
      })
    } else if (this.data.formMode == Constants.formMode.detailEdit) {
      //编辑
      wx.setNavigationBarTitle({
        title: mixins.$t('edit') + title
      })
      //设置显示
      this.setFlagView(this)

      if (app.globalData.company.gradeCode == Constants.gradeCode.STD) {
        this.setData({
          checkFlag: true
        })
      }

      this.getItemDetal(this.data.id, 'saleOutBoundService', 'getOutboundForUpdate')
      this.setData({
        formData: JSON.stringify(formData)
      })
    }
  },
  /**
   * @desc : 设置系统版本相关
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setStdAndPro(that) {
    let contentObj = this.data.contentObj
    if (that.data.gradeCode == Constants.gradeCode.STD) {
      contentObj.main = [{
        code: 'cusName',
        type: 'str',
        // urlKey: 'selectCustomers',
        required: true,
        readonly: true,
        title: mixins.$t('customerName')
      },
      {
        code: 'cusPhone',
        type: 'str',
        title: mixins.$t('cusPhone'),
        required: true,
        readonly: true,
      },
      {
        code: 'addressFull',
        type: 'str',
        title: mixins.$t('addressFull'),
        required: true,
        readonly: true,
      },
      {
        code: 'addressNo',
        type: 'str',
        required: true,
        title: mixins.$t('addressNo'),
        readonly: true,
      },
      {
        code: 'channelName',
        required: true,
        readonly: true,
        title: mixins.$t('saleChannel'),
        type: 'str',
        // urlKey: 'chooseChannel'
      },
      // { code: 'cusFrom', name: 'cusFromName', required: true, title: mixins.$t('customerSource'), type: 'choose', urlKey: 'choosecusFrom' },
      {
        code: 'contactName',
        type: 'str',
        required: false,
        readonly: true,
        title: mixins.$t('contactName')
      },
      {
        code: 'contactPhone',
        type: 'str',
        title: mixins.$t('cpPhone'),
        required: false,
        readonly: true,
      },
      ]
    } else if (that.data.gradeCode == Constants.gradeCode.PRO) {
      contentObj.main = [{
        code: 'cusName',
        type: 'str',
        // urlKey: 'selectCustomers',
        required: true,
        readonly: false,
        title: mixins.$t('customerName')
      },
      {
        code: 'cusPhone',
        type: 'str',
        title: mixins.$t('cusPhone'),
        required: true
      },
      {
        code: 'addressFull',
        type: 'str',
        title: mixins.$t('addressFull'),
        required: true
      },
      {
        code: 'addressNo',
        type: 'str',
        required: true,
        title: mixins.$t('addressNo')
      },
      {
        code: 'channelName',
        // name: 'channelName',
        required: true,
        title: mixins.$t('saleChannel'),
        type: 'str',
        // urlKey: 'chooseChannel'
      },
      {
        code: 'cusFrom',
        name: 'cusFromName',
        required: false,
        title: mixins.$t('customerSource'),
        type: 'str',
        // urlKey: 'choosecusFrom'
      },
      {
        code: 'contactName',
        type: 'str',
        required: false,
        title: mixins.$t('contactName')
      },
      {
        code: 'contactPhone',
        type: 'str',
        title: mixins.$t('cpPhone'),
        required: false
      },
      ]
    }
    that.setData({
      contentObj: contentObj
    })

  },
  /**
   * @desc : 设置显示
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setFlagView(that) {
    let contentObj = that.data.contentObj
    let cardList = that.data.cardList
    if (app.globalData.company.gradeCode == Constants.gradeCode.STD) {
      contentObj.main = [{
        code: 'cusName',
        type: 'str',
        // urlKey: 'selectCustomers',
        required: true,
        readonly: true,
        title: mixins.$t('customerName')
      },
      {
        code: 'cusPhone',
        type: 'str',
        title: mixins.$t('cusPhone'),
        required: true,
        readonly: true,
      },
      {
        code: 'addressFull',
        type: 'str',
        readonly: true,
        title: mixins.$t('addressFull'),
        required: true
      },
      {
        code: 'addressNo',
        type: 'str',
        required: true,
        readonly: true,
        title: mixins.$t('addressNo')
      },
      {
        code: 'channelName',
        name: 'channelName',
        required: false,
        readonly: true,
        title: mixins.$t('saleChannel'),
        type: 'str',
        // urlKey: 'chooseChannel'
      },
      {
        code: 'contactName',
        type: 'str',
        required: false,
        readonly: true,
        title: mixins.$t('contactName')
      },
      {
        code: 'contactPhone',
        type: 'str',
        title: mixins.$t('cpPhone'),
        required: false,
        readonly: true,
      },
      ]
      // that.getDefChannel(that)
    } else {
      contentObj.relation = [{
        code: 'fromNo',
        name: 'fromNo',
        type: 'choose',
        // titpsKey: 'cusId',
        // titpsMessage: '请选择客户',
        chooseVisible: true,
        controlChooseFlag: true,
        title: mixins.$t("sourceOrder"), //'关联源单'
        urlKey: 'selectSourceSaleOrder'
      }]
    }
    that.setData({
      contentObj: contentObj,
      cardList: cardList
    })
    let contentSaveList = that.data.contentSaveList
    if (!that.data.flgHandleSetting) {
      contentSaveList = [
        {
          code: 'factAmt',
          content: 0,
          type: 'number',
          title: mixins.$t("factAmt")
        }]
    } else {
      if (that.data.formMode == Constants.formMode.add || that.data.formMode == Constants.formMode.other) {
        contentSaveList = [
          {
            code: 'flag',
            title: mixins.$t("autoSaleOutBoundFlag"),
            type: 'checkbox',
          },
          {
            code: 'factAmt',
            content: 0,
            type: 'number',
            title: mixins.$t("factAmt")
          }
        ]
      } else {
        contentSaveList = [
          {
            code: 'factAmt',
            content: 0,
            type: 'number',
            title: mixins.$t("factAmt")
          }]
      }

    }
    that.setData({
      contentSaveList: contentSaveList
    })
  },

  /**
   * @desc : 设置销售渠道
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getDefChannel(that) {
    that.excute(that.data.saleChannelService, that.data.saleChannelService.selectByCond, {
      flgDefault: true
    }).then(res => {
      if (res.data.code == 200) {
        let formData = JSON.parse(that.data.formData)
        if (res.data.data.list && res.data.data.list.length > 0) {
          formData.channelId = res.data.data.list[0].channelId
          formData.channelName = res.data.data.list[0].channelName
          formData.channelCode = res.data.data.list[0].channelCode
        }
        // formData.staffId = app.globalData.user.staffId
        // formData.staffName = app.globalData.user.staffName
        // formData.orgId = app.globalData.user.orgId
        // formData.orgName = app.globalData.user.orgName
        //设置默认值
        that.setData({
          formData: JSON.stringify(formData)
        })
      }
    })
  },
})