const Constants = require('@/utils/Constants.js');
import Dialog from '@/dist/dialog/dialog.js';
const mixins = require('@/mixins/index.js')
const utils = require('@/utils/util')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    gradeCode:  app.globalData.company.gradeCode,
    // 路由
    routeObjName: 'saleOutBoundReturn',
    table: Constants.tables.order,
    orderService: app.globalData['orderService'],
    commonService: app.globalData['commonService'],
    saleOutBoundReturnService: app.globalData['saleOutBoundReturnService'],
    btnFormData: JSON.stringify({
      flag: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false
    }),
    // 系统参数
    flgHandleSetting: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false,
    cardList: [{
        name: 'main',
        title: mixins.$t("customerInformation")
      },
      {
        name: 'relation'
      },
      {
        name: 'items',
        title: mixins.$t("goodsDetail"),
        chooseGoodsFlag: true,
        itemAmt: '',
        displayNum: 2
      },
      {
        name: 'other',
        title: mixins.$t("otherInfo")
      }
    ],
    popupTopObj: [{
      leftTitle: '库存量',
      leftCode: 'usableQty',
      rightTitle: '可售量',
      rightCode: 'invQty'
    }],
    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',
          type: 'drop',
          required: true,
          dropType: 'saleChannel',
          title: mixins.$t('saleChannel')
        },
        {
          code: 'cusFrom',
          name: 'cusFromName',
          type: 'drop',
          required: false,
          dropType: 'customerFrom',
          title: mixins.$t('customerSource')
        },
      ],
      relation: [{
        code: 'fromNo',
        name: 'fromNo',
        type: 'choose',
        titpsKey: 'cusId',
        titpsMessage: '请选择客户',
        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: 'remarks',
          type: 'textarea',
          title: mixins.$t("remarks"),
          readonly: false
        },
        {
          code: 'file',
          type: 'uploader',
          title: mixins.$t("uploader")
        }
      ]
    },
    //按钮
    buttonSaveList: [{
        code: 'refund',
        width:"200rpx",
        title:  mixins.$t("refundSave")
      },
      {
        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")
      }
    ],
    popContent: [{
        code: 'outingQty',
        type: 'negativeStep',
        title: mixins.$t("count"),
        required: true
      },
      {
        code: 'packageBox',
        type: 'packageBox',
        title: mixins.$t("packageBox"),
      },
      {
        code: 'priceOut',
        type: 'number',
        title: mixins.$t("priceSale"),
        required: true
      },
      {
        code: 'whId',
        name: 'whName',
        choosePopupType: '',
        title: mixins.$t("warehouseId"),
        type: 'choose',
        urlKey: 'openingInventory',
      },
      {
        code: 'brandName',
        title: mixins.$t('brandName'), 
        type: 'str',
        readonly:true,
    },
      {
        code: 'nonStdCode',
        title: mixins.$t("goodsBatch"),
        type: 'str',
      },
    ],
    // 新手引导
    step: {
      name: 'order-return',
      guideList: [{
          el: "#dkForm>>>#cusName",
          tips: mixins.$t('chooseCustomer'),
        },
        {
          el: "#dkForm>>>#fromNo",
          tips: mixins.$t('chooseItems'),
        },
        {
          el: "#dkForm>>>#items",
          tips: mixins.$t('chooseItems'),
        },
        {
          el: "#saveButton>>>#saveButton",
          tips: mixins.$t('saveButton'),
          fixed: true,
        },
      ]
    },
  },

  /**
   * @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++
      list.push({
        skuId: res.skuId,
        nonStdCode: res.nonStdCode,
        whId: res.whId
      })
      res.sumPrice = res.priceOut * res.itemQty
    })
    console.log('eree',formData);
    //批量查库存
    this.getInventory({
      skuIdNonStdCodeWhIdList: list
    }).then(item => {
      formData.goodsList.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
            } else {
              res.invQty = 0
              res.usableQty = 0
            }
          })
        } else {
          res.invQty = 0
          res.usableQty = 0
        }
      })
      //组件显示 需收款
      contentSaveList[1]['content'] = Number(formData.sumAmount)
      this.setData({
        formData: JSON.stringify(formData),
        contentSaveList: contentSaveList
      })
      //处理库存量
      this.calculationSalesUsableQty()
    })
  },
  //计算可售量相关
  calculationSalesUsableQty() {
    let formData = JSON.parse(this.data.formData)
    formData.goodsList.forEach(res => {
      if (res.invId) {
        //选择的数量大于可售量
        if (Math.abs(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['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 : 查询库存
   * @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) {
          resolve(res.data.data)
        }
      })
    })
  },



  /**
   * @desc :   自动办理事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveChange(e) {
    let btnFormData = JSON.parse(this.data.btnFormData)
    let that = this
    if (!btnFormData.flag) {
      //提示
      Dialog.confirm({
        message: mixins.$t("saleOutBoundInfo"),
      }).then(() => {}).catch(() => {
        btnFormData.flag = true
        that.setData({
          btnFormData: JSON.stringify(btnFormData)
        })
      });
    }
  },

  /**
   * @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 = 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.contactPhone = item.contactPhone
      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 == 'fromNo') {
      console.log('item.itemList', item.itemList)
      if (item.itemList && item.itemList.length > 0) {
        item.itemList.forEach(res => {
          res.sOutItemId = res.itemId
          res.fromId = res.outId
          res.sOutId = res.outId
          res.fromItemId = res.itemId
          res.outingAmt = res.outAmt * -1
          res.outingQty = res.outQty * -1
          res['outingQty_min'] = res.outQty * -1
          res['outingQty_max'] = 0
          console.log('111111111111111');
        })


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


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

  },

  /**
   * @desc : 底部按钮事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveButton(e) {
    console.log(e)
    let name = e.detail.name
    if (name == 'save') { //保存
      this.save({})
    } else if (name == 'merge') { //撤回
      this.handleWarehousing()
    } else if (name == 'refund') { //退款
      let formData = JSON.parse(this.data.formData)
      formData.btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : '' 
      if( formData.goodsList){ //算出 要退款 的钱
        let nmb = 0
        formData.goodsList.forEach(element => {
          nmb = element.outingAmt + nmb
        });
        formData.sumAmtRec = nmb 
      } 
      formData.objInfo = {} //退款页面的 客户信息
      formData.objInfo['cusPhone'] = formData.cusPhone
      formData.objInfo['cusName'] = formData.cusName
      formData.objInfo['objectId'] = formData.cusId
      formData.objInfo['addressFull'] = formData.addressFull 
   
      this.setData({
        formData:JSON.stringify(formData),
        refundFlag:true,
      })
      this.save({})
   
    }
  },
  /**
   * @desc : 退款
   * @date : 2024/2/1 15:49
   * @author : 于
   */
  handRefunding(e) {
    let _this = this
    wx.navigateTo({
      url: '/package-base-select/pages/select-collection_confirm/select-collection_confirm',
      events: {
        // 回调后
        refresh: function (data) {
         // 保存成功后 回调
         wx.navigateBack({
          data: 1
        })
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 
        res.eventChannel.emit('params', {
          item: _this.data.formData,
          formType: 10
        })
      }
    })
  },
  /**
   * @desc : 撤回
   * @date : 2024/2/1 15:49
   * @author : 于
   */
  handleWarehousing(e) {
    let item = {}
    item.outId = this.data.id
    this.excute(this.data.service, this.data.service.saleReturnOutboundCancel, item).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        // 重新查询
        this.searchData()
      }
    })
  },
  /**
   * @desc : 设置保存参数
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setParams(params) {
    let itemIndex = 0
    let formData = JSON.parse(this.data.formData)
    console.log('params1', params)
    params.fromId = params.orderId
    params.goodsList.forEach(res => {
      // res['sOutId'] = res.soutId
      // res['sOutItemId'] = res.soutItemId
      // res['sOrderItemId'] = res.sorderItemId
      // res['sOrderId'] = res.sorderId
      res.itemIndex = itemIndex++
      res.canNegativeFlag = true
      if (this.data.formMode != 'detail') {
        delete res['itemId']
      }

    })
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出库标识 
    params.itemList = params.goodsList //明细
    if (formData.outStatus == Constants.outStatus.outBounded) //""出库状态-已出库"
    {
      params.itemList.forEach(element => {
        element.outBox = element.box
        element.outPiece = element.piece
      });
    } else {
      params.itemList.forEach(element => {
        if (params.flgAutoHandle) {
          element.outBox = element.box
          element.outPiece = element.piece
        } else {
          element.outingBox = element.box
          element.outingPiece = element.piece
        }
      });
    }


    params.makeStaff = app.globalData.user.staffId
    // params.deleteItemList = params.deleteList ? params.deleteList : []


    params.addressName = params.address.addressName
    params.objectId = params.cusId
    params.canNegativeFlag = true
    params.outDate = utils.formatDayTime(new Date())
    delete params['goodsList']
    delete params['orderItemResponseList']
    console.log('params', params)

    return params
  },
  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveData() {
    if(this.data.refundFlag){
      this.setData({
        refundFlag:false
      })
      this.handRefunding()
      return
    }
    if (this.data.formMode == Constants.formMode.other || this.data.formMode == Constants.formMode.add) { //关联源单新建退货
      return this.excute(this.data.service, this.data.service.outboundInsert, this.data.params);
    }
    if (this.data.formMode == Constants.formMode.detail) { //办理
      return this.excute(this.data.service, this.data.service.saleReturnHandleOutbound, this.data.params);
    }
    if (this.data.formMode == Constants.formMode.other && this.data.formType == Constants.formMode.edit) { //编辑
      return this.excute(this.data.service, this.data.service.otherOutboundUpdate, this.data.params);
    }
  },
  /**
   * @desc : 处理保存后的数据
   * @date : 2024/5/31 15:49
   * @author : 周兴
   */
  handleSaveData(){
    let contentSaveList = this.data.contentSaveList
    let filters = contentSaveList.filter(it=>it.code == 'receivable')
    if(filters && filters.length > 0){
      filters[0].content = 0;
    }
    this.setData({
      contentSaveList:contentSaveList
    })
  },
  /**
   * @desc : 查询商品明细
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getItemDetal(id, service, API) {
    if (!API) {
      API = 'getOutReturnForUpdate'
      service = 'service'
    }
    console.log('service',service,API,id)
    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)
        if (res.data.data.data.outStatus == mixins.$t("outBoundedOutStatus") && this.data.formMode != 'other') {
          let buttonSaveList = this.data.buttonSaveList
          buttonSaveList = [{
            code: 'merge',
            title: mixins.$t("handleWithdrawal"),
          }]
          this.setData({
            buttonSaveList: buttonSaveList
          })
        }
        formData = res.data.data.data
        //销售订单列表转出库
        if (!API) {
          formData.fromNo = formData.formNo
        } else {
          formData.fromNo = formData.fromNo ? formData.fromNo : formData.orderNo
        }
        if(this.data.formType =='toSaleOut'){ //销售出库转退货
          formData.fromNo = formData.outNo
          formData.outStatus = "出库状态-出库中"
          formData.outType ="出库类型-销退回库"
          formData.receivableId = null
          formData.channelId = formData.salesChannel
        }
        //处理地址
        formData.address = this.setAddress(formData)

        res.data.data.dataItem.forEach(item => {
          item.outingQty_max = 0
          item.priceStd = item.priceOut
          //处理图片
          if (item.skuImages) {
            item['imagesUrl'] = item.skuImages.length > 0 ? item.skuImages[0].url : null
          }
          if(this.data.formType =='toSaleOut'){//销售出库转退货
            item.outingQty =  item.outingQty * -1
            item.outingAmt =  item.outingAmt * -1
          }
          

          console.log('22222222222');
          item.outingQty_min = item.canOutingQty ? item.canOutingQty : item.invQty * -1 //可出库最大值
        })


        formData.goodsList = res.data.data.dataItem

        formData.goodsList.forEach(element => {
          if (element.outStatus == Constants.outStatus.outBounded) //""出库状态-已出库"
          {
            element.box = element.outBox
            element.piece = element.outPiece
          } else {
            element.box = element.outingBox
            element.piece = element.outingPiece
          }
          if (element.flgSubUnit) {
            element.calculationFormula = element.packBox + element.unitName + '= 1' + element.subUnitName
            element.packageBox = element['box'] + element.subUnitName + element['piece'] + element.unitName
          }
          element.sumPrice = element.priceOut * element.itemQty

        });
        //处理默认值  业务员业务部门
        formData = this.setStaffOrg(formData)
        //设置选商品不可用
        let cardList = this.data.cardList
        cardList[2].chooseGoodsFlag = false
        this.calculateAmount(formData)
        console.log('结果', res)

        this.setData({
          cardList: cardList,
          formData: JSON.stringify(formData)
        })
        setTimeout(() => {
          // 刷新商品明细 显示 查看更多
          let card = this.data.cardList.filter(it => it.name == 'items');
          this.selectComponent('#' + this.data.formName).handleContentObj(card[0])
       }, 2000)
      }
    });
  },

  /**
   * @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[1].sumAmount = data.sumAmount
    cardList[1].sumStandard = data.sumStandard
    cardList[1].sumQuantity = data.sumQuantity
    cardList[1].saleDiscount = data.saleDiscount
    console.log(data, '11')

    this.setData({
      cardList: cardList,
      formData: JSON.stringify(data)
    })
    //查询商品明细
    this.getItemDetal(data.orderId)
  },

  /**
   * @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
    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')
      },
    ]
    contentObj.relation = [{
        code: 'fromNo',
        type: 'str',
        title: mixins.$t("sourceOrder"), //'关联源单'
        readonly: true,
      }],
      contentObj.other = [
        // {
        //   code: 'contractNo',
        //   type: 'str',
        //   readonly: true,
        //   required: false,
        //   title: mixins.$t('contractNumber')
        // },

        {
          code: 'remarks',
          type: 'str',
          readonly: true,
          required: false,
          title: mixins.$t('remarks')
        },
        {
          code: 'file',
          type: 'uploader',
          title: mixins.$t("uploader")
        }
      ]
    cardList = [{
        name: 'main',
        title: mixins.$t("customerInformation")
      },
      {
        name: 'relation'
      },
      {
        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("inProcessing")
      }]
      contentSaveList = [
        {
          code: 'receivable',
          content: 0,
          type: 'number',
          title: mixins.$t("saleCollection"),
        }
      ]
      popContent = [{
          code: 'outingQty',
          type: 'negativeStep',
          title: mixins.$t("count"),
          required: true,
          readonly: true
        },
        {
          code: 'packageBox',
          type: 'packageBox',
          title: mixins.$t("packageBox"),
        },
        {
          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,
    })
  },
  /**
   * @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
  },
  /**
   * @desc   : 计算金额
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  calculateAmount(formData) {
    ///设置总单信息
    let sumStandard = Number(0)
    let sumAmount = Number(0)
    let sumQuantity = Number(0)
    console.log('sumQuantity1',sumQuantity);
    formData.goodsList.forEach(item => {
      //标价合计 =  商品标价 x  商品数量
      sumStandard += item.amtStd
      sumAmount += item.outingQty * item.priceOut //没有售价默认取标价
      sumQuantity += Number(item.outingQty) //数量
    })
    console.log('sumQuantity2',sumQuantity);
    formData.sumStandard = sumStandard
    formData.saleDiscount = Number((sumAmount / sumStandard) * 100).toFixed(2)
    formData.sumAmount = sumAmount
    formData.canUseCollect = 0
    formData.useCollect = 0
    formData.sumQuantity = sumQuantity
    formData.outingQty = sumQuantity * -1
    formData.outingAmt = sumAmount
    let cardList = this.data.cardList
    let contentSaveList = this.data.contentSaveList
    let filters = cardList.filter(it=>it.name=='items');
    if(filters && filters.length > 0){
      filters[0].sumAmount = formData.sumAmount
      filters[0].sumStandard = formData.sumStandard
      filters[0].sumQuantity = formData.sumQuantity
      filters[0].saleDiscount = formData.saleDiscount
    }
    //详情 办理
    if (this.data.formMode == Constants.formMode.detail) {
      contentSaveList[0].content = formData.sumAmount
    } else {
      contentSaveList[1].content = formData.sumAmount
    }
    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 : 于继渤
   */
  toEdit() {
    let this_ = this
    wx.navigateTo({
      url: this_.data.route.add.url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {}
      },
      success: function (res) {
        res.eventChannel.emit('params', {
          formMode: Constants.formMode.other,
          id: this_.data.id,
          formType: Constants.formMode.edit
        });
      }
    })
  },
  /**
   * @desc : 设置客户信息
   * @date : 2024/5/24 15:49
   * @author : 周兴
   */
  setCustomerInit(){
    let item = this.data.item
    if(!item)return;
    let formData = this.data.formData && JSON.stringify(this.data.formData) !== '{}' ? JSON.parse(this.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
    this.setData({
      formData:JSON.stringify(formData)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  loadInit() {
    let formData = JSON.parse(this.data.formData)
    if (this.data.formMode == Constants.formMode.detail) { //详情
      //详情办理
      wx.setNavigationBarTitle({
        title: '销售退货详情'
      })
      //设置只读
      this.setFormMain()
      //查询信息
      this.getItemDetal(this.data.id)
      this.setData({
        formData: JSON.stringify(formData)
      })
    } else if (this.data.formMode == Constants.formMode.add) { //新建
      if (this.data.gradeCode == Constants.gradeCode.STD) { //标准 
          //处理默认值  业务员业务部门
          let buttonSaveList = this.data.buttonSaveList
          //按钮
          buttonSaveList =  [{
            code: 'refund',
            width:"200rpx",
            title:  mixins.$t("refundSave")
          },
          {
            code: 'save',
            title: mixins.$t("save")
          }
        ],
          this.setData({
            buttonSaveList: buttonSaveList
          }) 
      }
  
      formData = this.setStaffOrg(formData)
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('params', function (data) {
        console.log('新建', data)
      })
      this.setData({
        formData: JSON.stringify(formData)
      })
      // 设置客户信息
      this.setCustomerInit();
    } else if (this.data.formMode == Constants.formMode.other && this.data.formType !== Constants.formMode.edit) {
      //转退货
      //查询信息
      if(this.data.formType =='toSaleOut'){ 
        //销售出库转退货
        this.getItemDetal(this.data.item.outId, 'saleOutBoundReturnService', 'getOutReturnForUpdateWx')
      }else{
        this.getItemDetal(this.data.item.orderId, 'orderService', 'getOrderForReturn')
      }
      this.setData({
        formData: JSON.stringify(formData)
      })
    } else if (this.data.formMode == Constants.formMode.other && this.data.formType == Constants.formMode.edit) { //编辑
      wx.setNavigationBarTitle({
        title: '编辑销售退货'
      })

      if (this.data.formMode == Constants.formMode.other) {
        this.setData({
          popContent: [{
              code: 'outingQty',
              type: 'negativeStep',
              title: mixins.$t("count"),
              required: true
            },
            {
              code: 'packageBox',
              type: 'packageBox',
              title: mixins.$t("packageBox"),
            },
            {
              code: 'priceOut',
              type: 'number',
              title: mixins.$t("priceSale"),
              required: 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',
            },
            {
              code: 'flgGift',
              title: mixins.$t("flgGift"),
              type: 'checkbox',
              readonly: true
            },
          ]
        })

      }
      //查询信息
      this.getItemDetal(this.data.id)
      this.setData({
        formData: JSON.stringify(formData)
      })
    }

       // 标准版，自动出库办理标识默认勾上
       if (this.data.gradeCode == Constants.gradeCode.STD) {
        let btnFormData = JSON.parse(this.data.btnFormData) || {}
        btnFormData.flag = true
        this.setData({
          btnFormData: JSON.stringify(btnFormData)
        })
      }
  },

})