<!-- @desc:销售退货入库新建，用于不引用原单，直接新建的退货单  @auth:付斌  @time:2023-10-23 14:10 -->
<template>
  <div class="main-div">
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData">
          <!--出库单号-->
          <DkFormItem prop="outNo">
            <InputPop ref="outNo" v-model="formData.outNo" :readonly="true"/>
          </DkFormItem>
          <!--客户电话-->
          <DkFormItem prop="cusPhone" :required="true">
            <SelectMagnifier v-model="formData.cusPhone" ref="cusPhone" :telephone="true"
                             primary-key="cusId" :input-read-only="false" :multiple="false"
                             :displayText="formData.cusPhone"
                             :type="this.$config.MagnifierType.customer"
                             :disabled="checkColumnIsEdit('cusPhone')"
                             @on-input-blur="selectCustomer"
                             @ok="selectCustomer"/>
          </DkFormItem>
          <!--客户名称-->
          <DkFormItem prop="cusName" :required="true">
            <InputPop ref="cusName" :readonly="checkColumnIsEdit('cusName')"
                      :disabled="checkColumnIsEdit('cusName')"
                      v-model="formData.cusName"/>
          </DkFormItem>
          <!--客户区域-->
          <DkFormItem prop="addressName" :required="true">
            <RegionsChoose v-model="addressArea" :options="cityData" :default-value="formData.addressName"
                           :readonly="checkColumnIsEdit('addressArea')" ref="customerDistrict"
                           :disabled="checkColumnIsEdit('addressName')"
                           @on-choose="chooseAddress"></RegionsChoose>
          </DkFormItem>
          <!--门牌号-->
          <DkFormItem prop="addressNo" :required="true">
            <InputPop ref="addressNo" :readonly="checkColumnIsEdit('addressNo')"
                      v-model="formData.addressNo"
                      :disabled="checkColumnIsEdit('addressNo')"
                      @input="setAddressFull"/>
          </DkFormItem>
          <!--详细地址-->
          <DkFormItem prop="addressFull" :required="true">
            <InputPop ref="addressFull" v-model="formData.addressFull"
                      :disabled="checkColumnIsEdit('addressFull')"/>
          </DkFormItem>
          <!--联系人-->
          <DkFormItem prop="contactName">
            <InputPop ref="contactName" :readonly="checkColumnIsEdit('contactName')"
                      v-model="formData.contactName" :disabled="checkColumnIsEdit('contactName')"/>
          </DkFormItem>
          <!--联系电话-->
          <DkFormItem prop="contactPhone">
            <InputPop :telephone="true" ref="contactPhone" :readonly="checkColumnIsEdit('contactPhone')"
                      v-model="formData.contactPhone" :disabled="checkColumnIsEdit('contactPhone')"/>
          </DkFormItem>
          <!--业务部门-->
          <DkFormItem prop="orgId" :required="true">
            <MultiSelect v-model="formData.orgList"
                         ref="org"
                         main-field="ownerFlag"
                         rate-field="allocationRatio"
                         :order-id="formData.orderId"
                         :default-value="formData.orgName"
                         @ok="orgOk($event)"
                         :type="this.$config.MagnifierType.org"/>
          </DkFormItem>
          <!--业务员-->
          <DkFormItem prop="staffId" :required="true">
            <MultiSelect v-model="formData.staffList"
                         main-field="ownerFlag"
                         rate-field="allocationRatio"
                         :order-id="formData.orderId"
                         :default-value="formData.staffName"
                         @ok="staffOk($event)"
                         :type="this.$config.MagnifierType.staff"/>
          </DkFormItem>
          <!--客户来源-->
          <DkFormItem prop="cusFrom" :required="true">
            <SelectPop v-model="formData.cusFrom" ref="cusFrom" :multiple="false"
                       :options="cusFromList"
                       :disabled="checkColumnIsEdit('cusFrom')"
                       labelKey="dataValue"
                       valueKey=dataId>
            </SelectPop>
          </DkFormItem>
          <!--销售渠道-->
          <DkFormItem prop="salesChannel" :required="true">
            <SelectPop v-model="formData.salesChannel" ref="salesChannel"
                       :options="channelList"
                       :multiple="false"
                       :disabled="checkColumnIsEdit('salesChannel')"
                       labelKey="channelName"
                       valueKey="channelId">
            </SelectPop>
          </DkFormItem>
          <!--出库日期-->
          <DkFormItem prop="outDate" :data-type="$config.dataType.date">
            <DatePickerPop v-model="formData.outDate"
                           :short-cut-flag="true"/>
          </DkFormItem>
          <!--自动出库标识-->
          <DkFormItem prop="autoOutFlag" v-show="showAutoFlag">
            <template>
              <i-switch v-model="formData.flgAutoHandle" @on-change="changeOutStatus"
                        :disabled="type === $config.formMode.handle">
                <span slot="open"></span>
                <span slot="close"></span>
              </i-switch>
            </template>
          </DkFormItem>
          <!--单据备注-->
          <DkFormItem prop="remarks" :span="12">
            <InputPop ref="remarks" v-model="formData.remarks" :readonly="checkColumnIsEdit('remarks')"
                      maxlength=500 textareaFlag/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--商品信息-->
      <DkPanel prop="goodsInformation">
        <div id="search-cond-div-goods-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable ref="goodsTable" :data="formData.itemList" showFooter major-field="itemId"
                     :columns="addOutReturnItemColumns" controlId="skuId"
                     @changeNonStandard="changeNonStandard"
                     @on-choose="getTotals" @changeValue="getTotals"
          ></EditTable>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData"
                    class="read-only-form">
              <!--合计数量-->
              <DkFormItem prop="sumQuantity">
                <InputNumberPop ref="sumQuantity" v-model="goodsFootFormData.sumQuantity" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--货物金额-->
              <DkFormItem prop="sumAmount" class="amount">
                <InputNumberPop ref="sumAmount" v-model="goodsFootFormData.sumAmount" :readonly="true"
                                :digits="2"/>
              </DkFormItem>
            </DkForm>
          </div>
        </div>
      </DkPanel>
      <!--附件-->
      <DkPanel prop="files">
        <div id="search-cond-div-files-info" ref="search-cond-div-files-info" slot="content">
          <DkPicWall v-model="formData.annexPaths"
                     :table="$config.tables.outbound" :accept="$config.uploadFileConfig.acceptPicType"
                     :format="['jpg','jpeg','png']"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save(true)" @close="close"/>
  </div>
</template>

<script>
import {formMixin} from '@/mixins/form'

export default {
  name: 'sale-return',
  mixins: [formMixin],
  data() {
    let self = this
    return {
      showAutoFlag: true, //是否显示自动办理出库标识
      showOutDate: true, //是否显示自动办理出库标识
      // 画面表单数据
      formData: {
        outId: null,
        outNo: null,
        cusId: null,
        cusName: null,
        cusPhone: null,
        contactName: null,
        contactPhone: null,
        customerDistrict: null,
        addressArea: null,
        addressGcj02: null,
        addressName: null,
        addressNo: null,
        addressFull: null,
        salesChannel: null,
        cusFrom: null,
        remarks: null,
        itemList: [],
        deleteItemList: [],
        outDate: new Date(),
        annexPaths: [],
        //出库状态(默认为出库中)
        outStatus: this.$config.outStatus.chuKuZhong,
        staffList: [],    //存放从业务员id和分配百分比
        orgList: [],      //存放从业务部门id和分配百分比
        staffId: self.$store.state.user.id,
        staffName: self.$store.state.user.staffName,
        orgId: self.$store.state.user.orgId,
        orgName: self.$store.state.user.orgName,
        makeStaff: self.$store.state.user.id,
        flgAutoHandle: true,
        limitEdit: true,
      },
      addressArea: [],
      cityData: [],
      channelList: [],
      cusFromList: [],
      addOutReturnItemColumns: [
        {
          field: 'skuModel',
          controlId: 'skuId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.goodsForOrder,
          fieldUpdate: self.$updateColumns.outReturnChooseGoods,
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          controlId: 'skuId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.goodsForOrder,
          fieldUpdate: self.$updateColumns.outReturnChooseGoods,
          searchDetailFlag: true
        },
        {
          field: 'skuCode',
          type: 'disabled',
        },
        {
          field: 'whName',
          type: 'tableSelect',
          multiple: false,
          sortBoolean: false,
          dataType: self.$config.tableSelectType.warehouse,
          otherSearchParam: () => {
            return {
              skuId: self.currentRow?.skuId,
              nonStdCode: self.currentRow?.nonStdCode,
              orgId: self.formData.orgId,
            }
          },
          fieldUpdate: [
            {updateField: 'whId', valueFiled: 'whId'},
            {updateField: 'whName', valueFiled: 'whName'},
          ],
          searchDetailFlag: true
        },
        //退货数量
        {
          field: 'outingQty',
          title: self.$t('退货数量'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true,
          negative: true,
          formula: {
            outingAmt: ['priceOut*outingQty', 'priceOut', 'outingQty'],
          }
        },
        //基本单位
        {
          field: 'unitName',
          title: self.$t('piece'),
          type: 'disabled',
        },
        //包装规格
        {
          field: 'unitInfo',
          title: self.$t('boxPiece'),
          type: 'nonStandard',
        },
        //退货单价
        {
          field: 'priceOut',
          title: self.$t('priceReturn'),
          type: 'number',
          formula: {
            outingAmt: ['priceOut*outingQty', 'priceOut', 'outingQty'],
          },
        },
        //退货金额
        {
          field: 'outingAmt',
          title: self.$t('退货金额'),
          type: 'disabled',
          digits: 2,
          sum: true,
          formula: {
            priceOut: ['outingAmt/outingQty', 'outingAmt', 'outingQty'],
          },
          negative: true,
        },
        //非标号
        {
          field: 'nonStdCode', type: 'text', equal: true,
        },
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      //商品合计信息
      goodsFootFormData: {
        sumQuantity: 0,
        sumAmount: 0,
      },
      showIntoDate: false,//入库日期是否显示
    }
  },
  methods: {
    /**
     * @desc   : 加载数据
     * @author : 付斌
     * @date   : 2024-02-20 15:53
     */
    initData() {
      //获取渠道
      this.getChannel()
      //获取数据字典
      this.getDictionaryData()

      // 设置默认业务员业务部门
      this.formData.staffList = []
      let staff = {}
      staff.staffId = this.$store.state.user.staffId
      staff.staffCode = this.$store.state.user.staffCode
      staff.staffName = this.$store.state.user.staffName
      staff.allocationRatio = 100;
      staff.ownerFlag = true;
      this.formData.staffList.push(staff);

      this.formData.orgList = []
      let org = {}
      org.orgId = this.$store.state.user.orgId
      org.orgName = this.$store.state.user.orgName
      org.allocationRatio = 100;
      org.ownerFlag = true;
      this.formData.orgList.push(org);
    },
    /**
     * @desc   : 获取渠道
     * @author : 付斌
     * @date   : 2024-03-02 10:15
     */
    getChannel() {
      this.excute(this.$service.commonService, this.$service.commonService.getChannel, {}, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.channelList = res.data
        }
      })
    },
    /**
     * @desc   : 获取数据字典
     * @author : 付斌
     * @date   : 2024-03-02 11:15
     */
    getDictionaryData() {
      let params = {
        dictCode: this.$config.dictCode.cusFrom,
      }
      this.excute(this.$service.commonService, this.$service.commonService.getDictionaryData, params, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.cusFromList = res.data
        }
      })
    },
    /**
     *   @desc   : 获取业务员相关
     *   @date   : 2022/5/28 10:43
     *   @author : 付斌
     */
    orgOk(rows) {
      if (rows && rows.length > 0) {
        this.formData.orgList = []
        for (let i of rows) {
          //找到主业务员
          if (i.ownerFlag) {
            this.formData.orgId = i.orgId
            this.formData.orgCode = i.orgCode
            this.formData.orgName = i.orgName
            this.formData.allocationRatio = i.allocationRatio
          }
          //存放从业务员id和分配比
          this.formData.orgList.push({
            orgId: i.orgId,
            orgCode: i.orgCode,
            orgName: i.orgName,
            allocationRatio: i.allocationRatio,
            ownerFlag: i.ownerFlag
          })
        }
      }
    },
    /**
     *   @desc   : 获取业务员相关
     *   @date   : 2022/5/28 10:43
     *   @author : 付斌
     */
    staffOk(rows) {
      if (rows && rows.length > 0) {
        this.formData.staffList = []
        for (let i of rows) {
          //找到主业务员
          if (i.ownerFlag) {
            this.formData.staffId = i.staffId
            this.formData.staffCode = i.staffCode
            this.formData.staffName = i.staffName
            this.formData.allocationRatio = i.allocationRatio

          }
          //存放从业务员id和分配比
          this.formData.staffList.push({
            staffId: i.staffId,
            staffCode: i.staffCode,
            staffName: i.staffName,
            allocationRatio: i.allocationRatio,
            ownerFlag: i.ownerFlag
          })
        }
      }
    },
    /**
     *   @desc   : 获取客户资料并且监听每一次的客户修改
     *   @date   : 2022/5/24 15:04
     *   @author : 付斌
     */
    selectCustomer(val) {
      if (val && val.length > 0) {
        this.formData.cusId = val[0].cusId
        this.formData.cusPhone = val[0].cusPhone
        this.formData.cusName = val[0].cusName
        this.formData.contactName = val[0].contactName
        this.formData.contactPhone = val[0].contactPhone
        this.formData.salesChannel = val[0].channelId
        this.formData.cusFrom = val[0].cusFrom

        this.formData.addressArea = val[0].addressArea
        this.formData.addressName = val[0].addressName
        this.formData.addressGcj02 = val[0].addressGcj02
        this.formData.addressFull = val[0].addressFull
        this.formData.addressNo = val[0].addressNo

        this.formData.customerDistrict = {
          "addressArea": val[0].addressArea,
          "addressName": val[0].addressName,
          "addressGcj02": val[0].addressGcj02,
          // 门牌号去掉
          "addressFull": val[0].addressFull.replace(val[0].addressNo, ""),
        }
      }
    },
    /**
     *   @desc   : 选择地址
     *   @date   : 2022/6/9 19:15
     *   @author : 付斌
     */
    chooseAddress(value) {
      this.formData.customerDistrict = value;
      // 说明是清空
      if (!value) {
        this.formData.addressName = null;
        this.formData.addressArea = {};
        this.formData.addressFull = null;
        this.formData.addressGcj02 = {};
      } else {
        //按照title进行
        this.formData.addressName = value.addressName;
        this.formData.addressArea = value.addressArea;
        this.formData.addressGcj02 = value.addressGcj02;
        this.formData.addressFull = value.addressFull + (this.formData.addressNo ? this.formData.addressNo : '');
      }
    },
    /**
     *   @desc   : 拼写详细地址
     *   @date   : 2022/6/9 10:08
     *   @author : 付斌
     */
    setAddressFull(e) {
      // 客户区域有值才会拼接详细地址
      if (!this.setCustomerFlag && this.formData.customerDistrict && this.formData.customerDistrict.addressFull) {
        this.formData.addressFull = this.formData.customerDistrict.addressFull + (this.formData.addressNo ? this.formData.addressNo : '')
      }
    },
    /**
     * @desc   : 清空客户信息
     * @author : 付斌
     * @date   : 2024-02-27 10:36
     */
    clearCutomer() {
      this.setCustomerFlag = true;
      this.formData.customerDistrict = null;
      this.formData.cusId = null
      this.formData.cusCode = null
      this.formData.cusName = null
      this.formData.contactName = null
      this.formData.contactPhone = null
      this.formData.addressArea = {}
      //新增选择省市区也顺带清空了
      this.addressArea = []
      this.formData.addressName = null
      this.formData.addressNo = null

      this.formData.latitude = null
      this.formData.longitude = null
      this.formData.cusFrom = null;
      // 清空收款
      if (this.$refs['amtHandle']) {
        this.$refs['amtHandle'].clear();
      }
      // 清空客户区域
      if (this.$refs.customerDistrict) {
        this.$refs.customerDistrict.clear();
      }
      this.formData.addressFull = null;
      this.setCustomerFlag = false;
    },

    /**
     * @desc   : 修改包装数
     * @author : 周兴
     * @date   : 2024/5/24 15:02
     */
    changeNonStandard({row,rowIndex,field}){
      let table = this.$refs['goodsTable'].tableData
      table[rowIndex][field] = (row['nonStandardForm']['box']?row['nonStandardForm']['box']:0)
        + row['subUnitName']
        +(row['nonStandardForm']['piece'] == 0 || row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:'')
        +(row['unitName']?(row['nonStandardForm']['piece']?row['unitName']:''):'')
      table[rowIndex]['outingQty'] = -1 * (row['packBox'] * (row['nonStandardForm']['box']?row['nonStandardForm']['box']:0) + (row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0))
      table[rowIndex]['outingAmt'] = table[rowIndex]['outingQty'] * table[rowIndex]['priceOut']
      table[rowIndex]['box'] = row['nonStandardForm']['box'] ? row['nonStandardForm']['box'] : 0
      table[rowIndex]['piece'] = row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0
      this.getTotale(table)
    },

    /**
     *   @desc   : 获取商品表格中数量、金额后计算总单信息
     *   @date   : 2022/5/30 15:31
     *   @author : 付斌
     */
    getTotals(field, row, rowIndex) {
      let table = this.$refs['goodsTable'].getTableDataFilter();
      this.getTotale(table)
      this.decimalPlaces = row['decimalPlaces']
      if(row['subUnitId']){
        row.nonStandardForm = {
          formula: (row['subUnitName']?'1'+row['subUnitName']+ '=':'' ) + row['packBox'] + row['unitName'],
          box:(Math.abs(row['outingQty'])/row['packBox'] >= 1 ? Math.floor(Math.abs(row['outingQty'])/row['packBox']):0),
          piece:Math.abs(row['outingQty'])%row['packBox'],
        }
        row.nonStandardItems = [
          {code:'formula',label:'计算公式',type:'text',readonly:true},
          {code:'box',label:row['subUnitName'],type:'number' , negative: true,},
          {code:'piece',label:row['unitName'],type:'number',digits:this.decimalPlaces, negative: true,}
        ]
        row['unitInfo'] = (Math.abs(row['outingQty'])/row['packBox'] >= 1 ? Math.floor(Math.abs(row['outingQty'])/row['packBox']):0) + row['subUnitName'] + (Math.abs(row['outingQty'])%row['packBox']).toFixed(this.decimalPlaces) + row['unitName']
      }else{
        row.nonStandardForm = {
          formula: (row['subUnitName']?'1'+row['subUnitName']+ '=':'' ) + row['packBox'] + row['unitName'],
          piece:Math.abs(row['outingQty']),
        }
        row.nonStandardItems = [
          {code:'formula',label:'计算公式',type:'text',readonly:true},
          {code:'piece',label:row['unitName'],type:'number',digits: this.decimalPlaces}
        ]
        row['unitInfo'] = Math.abs(row['outingQty']) + row['unitName']
      }
      row['box'] = row['nonStandardForm']['box']
      row['piece'] = row['nonStandardForm']['piece']
    },

    /**
     * @desc   : 计算合计
     * @author : 常皓宁
     * @date   : 2024/5/29 13:27
     */
    getTotale(table){
      let sumQuantity = 0;  // 合计数量
      let sumAmount = 0;    // 货物金额

      if (table && table.length > 0) {
        table.forEach(row => {
          if (row["outingQty"]) {
            sumQuantity += parseFloat(row["outingQty"]);
          }
          if (row["outingAmt"]) {
            sumAmount += parseFloat(row["outingAmt"]);
          }
        })
        this.goodsFootFormData.sumQuantity = sumQuantity;
        this.goodsFootFormData.sumAmount = sumAmount;
      }
    },

    /**
     * @desc   : 自动出库标识变更
     * @author : 付斌
     * @date   : 2024-04-11 14:47
     */
    changeOutStatus() {
      if (this.type === this.$config.formMode.addTogether) {
        if (this.formData.flgAutoHandle) {
          this.formData.outDate = new Date().format("yyyy-MM-dd")
          this.showOutDate = true
        } else {
          this.formData.outDate = null
          this.showOutDate = false
        }
      } else {
        this.formData.outDate = new Date().format("yyyy-MM-dd")
      }
    },
    /**
     * @desc   : 通过id查询
     * @author : 付斌
     * @date   : 2022/03/04 13:17
     */
    detail(id) {
      // 新建订单退货（订单ID）
      if (this.type === this.$config.formMode.addOrderReturn) {
        return this.excuteNoParam(this.$service.orderService, this.$service.orderService.getOrderForReturn, [id]);
      }
      // 新建出库退货（出库单ID）
      else if (this.type === this.$config.formMode.addOutReturn) {
        return this.excuteNoParam(this.$service.orderOutService, this.$service.orderOutService.getOutForReturn, [id]);
      }
      //编辑
      else if (this.type === this.$config.formMode.edit) {
        return this.excuteNoParam(this.$service.orderOutReturnService, this.$service.orderOutReturnService.getOutReturnForUpdate, [id]);
      }
      //入库办理
      else if (this.type === this.$config.formMode.handle) {
        return this.excuteNoParam(this.$service.saleReturnInboundService, this.$service.saleReturnInboundService.selectByUpdate, [id]);
      }
    },
    /**
     * @desc   : 编辑页面赋值
     * @author : 付斌
     * @date   : 2024-03-03 9:33
     */
    setValuesByEdit(data) {
      if (data) {
        this.formData = data["data"];
        this.formData.itemList = data["dataItem"];

        if (!this.formData.outDate) {
          this.formData.outDate = new Date();
        }
        if (!this.formData.returnStatus) {
          this.formData.returnStatus = this.$config.returnStatus.return
        }
        if (!this.formData.intoStatus) {
          this.formData.intoStatus = this.$config.intoStatus.daiRuKu
        }
        if (!this.formData.makeStaff) {
          this.formData.makeStaff = this.$store.state.user.id;
        }

        this.goodsFootFormData.sumQuantity = this.formData.outingQty;
        this.goodsFootFormData.sumAmount = this.formData.outingAmt;

        if (this.type === this.$config.formMode.addOther) {
          //系统自动办理出库
          if (this.$store.state.user.setting[this.$config.settingCode.IVT001] == 1) {
            this.formData.flgAutoHandle = true;
          } else {
            this.formData.flgAutoHandle = false;
          }
        }
        this.formData.limitEdit = true;
      }
    },
    /**
     * @desc   : 校验数据
     * @author : 付斌
     * @date   : 2024-03-11 14:37
     */
    validData() {
      if (this.formData.orgList && this.formData.staffList.length == 0) {
        this.$message.error(this.$t('W_061', {'param': this.$t('staffId')}))
        return false;
      }
      if (this.formData.orgList && this.formData.orgList.length == 0) {
        this.$message.error(this.$t('W_061', {'param': this.$t('orgId')}))
        return false;
      }
      //业务部门中没有主业务部门
      if (this.formData.orgList && this.formData.orgList.length > 0) {
        var list = this.formData.orgList.filter(it => it.ownerFlag);
        if (list.length == 0) {
          this.$message.error(this.$t('W_099'))
          return false;
        }
      }
      //业务员中没有主业务员
      if (this.formData.staffList && this.formData.staffList.length > 0) {
        var list = this.formData.staffList.filter(it => it.ownerFlag);
        if (list.length == 0) {
          this.$message.error(this.$t('W_100'))
          return false;
        }
      }

      let itemTable = this.$refs['goodsTable'].getTableDataFilter();
      if (!itemTable || itemTable.length == 0) {
        this.$Message.warning(this.$t('W_012'))
        return false;
      }
      for (let it of itemTable) {
        if (!it.outingQty || it.outingQty === '') {
          this.$Message.warning(this.$t('W_042', {'param': '退货数量不能'}))
          return false;
        }
        if (it.outingQty > it.canReturnQty) {
          this.$Message.warning(this.$t('W_007', {'param': '退货数量不能大于可退数量'}))
          return false;
        }
      }
      return true;
    },
    /**
     * @desc   : 给参数赋值
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    setParams(arg) {
      if (this.type === this.$config.formMode.edit) {
        // 删除的表数据
        let deleteItemTable = this.$refs['goodsTable'].getDeleteData();
        this.formData.deleteItemList = deleteItemTable
      }

      let itemTable = this.$refs['goodsTable'].getTableDataFilter();
      if (!itemTable || itemTable.length == 0) {
        this.$Message.warning(this.$t('W_012'))
        return;
      }
      itemTable.map(row => {
        let item = row
        if(this.formData.flgAutoHandle || this.type === this.$config.formMode.handle){
          // 箱（出库中）
          this.$set(item, 'outingBox', 0)
          // 片（出库中）
          this.$set(item, 'outingPiece',0)
          // 箱（已出库）
          this.$set(item, 'outBox', row['box'])
          // 片（已出库）
          this.$set(item, 'outPiece',row['piece'])
        }else{
          // 箱（出库中）
          this.$set(item, 'outingBox', row['box'])
          // 片（出库中）
          this.$set(item, 'outingPiece',row['piece'])
          // 箱（已出库）
          this.$set(item, 'outBox', 0)
          // 片（已出库）
          this.$set(item, 'outPiece',0)
        }
      })
      this.formData.itemList = itemTable;
      Object.assign(this.params, this.formData, this.goodsFootFormData)
      this.params.outDate = new Date(this.formData.outDate).toDateStr();
      // console.log('this.params',this.params)
    },
    /**
     * @desc   : 保存数据
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    saveData() {
      // 新建订单退货、出库退货
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.orderOutReturnService, this.$service.orderOutReturnService.outboundInsert, this.params);
      }
      //编辑
      else if (this.type === this.$config.formMode.edit) {
        return this.excute(this.$service.orderOutReturnService, this.$service.orderOutReturnService.outboundUpdate, this.params);
      }
      //入库办理
      else if (this.type === this.$config.formMode.handle) {
        return this.excute(this.$service.saleReturnInboundService, this.$service.saleReturnInboundService.saleReturnHandleInbound, this.params)
      }
    },
    /**
     * @desc   :新建完毕后清空窗体
     * @author : 付斌
     * @date   : 2024-02-27 10:33
     */
    clear() {
      let self = this
      this.formData = {
        outId: null,
        outNo: null,
        cusId: null,
        cusName: null,
        cusPhone: null,
        contactName: null,
        contactPhone: null,
        customerDistrict: null,
        addressArea: null,
        addressGcj02: null,
        addressName: null,
        addressNo: null,
        addressFull: null,
        salesChannel: null,
        cusFrom: null,
        remarks: null,
        itemList: [],
        deleteItemList: [],
        outDate: new Date(),
        annexPaths: [],
        //出库状态(默认为出库中)
        outStatus: this.$config.outStatus.chuKuZhong,
        staffList: [],    //存放从业务员id和分配百分比
        orgList: [],      //存放从业务部门id和分配百分比
        staffId: self.$store.state.user.id,
        staffName: self.$store.state.user.staffName,
        orgId: self.$store.state.user.orgId,
        orgName: self.$store.state.user.orgName,
        makeStaff: self.$store.state.user.id,
        flgAutoHandle: true,
      }

      // 设置默认业务员业务部门
      this.formData.staffList = []
      let staff = {}
      staff.staffId = this.$store.state.user.staffId
      staff.staffCode = this.$store.state.user.staffCode
      staff.staffName = this.$store.state.user.staffName
      staff.allocationRatio = 100;
      staff.ownerFlag = true;
      this.formData.staffList.push(staff);

      this.formData.orgList = []
      let org = {}
      org.orgId = this.$store.state.user.orgId
      org.orgName = this.$store.state.user.orgName
      org.allocationRatio = 100;
      org.ownerFlag = true;
      this.formData.orgList.push(org);

      // 清空客户区域
      if (this.$refs.customerDistrict) {
        this.$refs.customerDistrict.clear();
      }
    },
    /**
     * @desc   : 判断列是否可以编辑
     * @author : 付斌
     * @date   : 2022/6/21 16:42
     */
    checkColumnIsEdit(field) {

    },
  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 付斌
   * @date   : 2022/3/3 10:32
   */
  created() {
    this.focusItem = 'saleReturnId';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'saleReturnId'  // 设置主键Id
    // 入库办理
    if (this.type === this.$config.formMode.handle) {
      this.showIntoDate = true;
    }
  }
}
</script>
