<!-- @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" style="width:100%;margin-top: 30px">
          <!--出库单号-->
          <DkFormItem prop="outNo">
            <InputPop ref="outNo" v-model="formData.outNo" :readonly="true"/>
          </DkFormItem>
          <!--客户电话-->
          <DkFormItem prop="cusPhone">
            <InputPop ref="cusPhone" :disabled="true" v-model="formData.cusPhone"/>
          </DkFormItem>
          <!--客户名称-->
          <DkFormItem prop="cusName">
            <InputPop ref="cusName" :disabled="true" v-model="formData.cusName"/>
          </DkFormItem>
          <!--客户区域-->
          <DkFormItem prop="addressName" :required="true">
            <RegionsChoose v-model="addressArea" :options="cityData" :default-value="formData.addressName"
                           ref="customerDistrict" :disabled="true"></RegionsChoose>
          </DkFormItem>
          <!--门牌号-->
          <DkFormItem prop="addressNo">
            <InputPop ref="addressNo" v-model="formData.addressNo" :disabled="true"/>
          </DkFormItem>
          <!--联系人-->
          <DkFormItem prop="contactName">
            <InputPop ref="contactName" :disabled="true"
                      v-model="formData.contactName"/>
          </DkFormItem>
          <!--详细地址-->
          <DkFormItem prop="addressFull">
            <InputPop ref="addressFull" v-model="formData.addressFull" :disabled="true"/>
          </DkFormItem>
          <!--业务部门-->
          <DkFormItem prop="orgId" :label="$t('orgId')">
            <SelectMagnifier v-model="formData.orgId" :display-text="formData.orgName"
                             :type="this.$config.MagnifierType.org"
                             :multiple="false" :disabled="true"/>
          </DkFormItem>
          <!--业务员-->
          <DkFormItem prop="staffId" :label="$t('staffId')">
            <SelectMagnifier v-model="formData.staffId" :display-text="formData.staffName"
                             :type="this.$config.MagnifierType.staff"
                             :multiple="false" :disabled="true"/>
          </DkFormItem>
          <!--客户来源-->
          <DkFormItem prop="cusFrom">
            <InputPop ref="cusFromName" :disabled="true" v-model="formData.cusFromName"/>
          </DkFormItem>
          <!--销售渠道-->
          <DkFormItem prop="channelId">
            <InputPop ref="channelName" :disabled="true" v-model="formData.channelName"/>
          </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">
            <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"
                     :new-row-flag="false" :add-flag="false" :delete-flag="false"
                     :columns="addOutReturnItemColumns" controlId="skuId"
                     @changeNonStandard="changeNonStandard"
                     @on-choose="getTotals" @changeValue="getTotals"
          ></EditTable>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData"
                    class="form-content-class">
              <!--合计数量-->
              <DkFormItem prop="sumQuantity">
                <InputNumberPop ref="sumQuantity" v-model="goodsFootFormData.sumQuantity" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--货物金额-->
              <DkFormItem prop="sumAmount">
                <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,//客户Id
        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: null,
        staffName: null,
        orgId: null,
        orgName: null,
        makeStaff: self.$store.state.user.id,
        flgAutoHandle: true,
      },
      addressArea: [],
      cityData: [],
      channelList: [],
      cusFromList: [],
      addOutReturnItemColumns: [
        {
          field: 'skuModel',
          type: 'disabled',
        },
        {
          field: 'skuName',
          type: 'disabled',
        },
        {
          field: 'skuCode',
          type: 'disabled',
        },
        //已出库数量
        {
          field: 'outboundOutQty',
          type: 'disabled',
          digits: 0,
          sum: true
        },
        //可退数量
        {
          field: 'canReturnQty',
          title: self.$t('可退数量'),
          type: 'disabled',
          digits: 0,
          sum: 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: 'disabled',
        },
        //退货金额
        {
          field: 'outingAmt',
          title: self.$t('退货金额'),
          type: 'disabled',
          digits: 2,
          sum: true,
          negative: true,
        },
        {field: 'nonStdCode', type: 'disabled',}, //非标号
        {field: 'remarks', type: 'text', width: 300},
      ],
      //商品合计信息
      goodsFootFormData: {
        sumQuantity: 0,
        sumAmount: 0,
      },
      showIntoDate: false,//入库日期是否显示
    }
  },
  methods: {
    /**
     * @desc   : 加载数据
     * @author : 付斌
     * @date   : 2024-02-20 15:53
     */
    initData() {
    },

    /**
     * @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.addOrderReturn || this.type === this.$config.formMode.addOutReturn) {
        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) {
      console.log("orderOutReturnService", 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.edit) {
          //系统自动办理出库
          if (this.$store.state.user.setting[this.$config.settingCode.IVT001] == 1) {
            this.formData.flgAutoHandle = true;
          } else {
            this.formData.flgAutoHandle = false;
          }
        }
      }
    },
    /**
     * @desc   : 校验数据
     * @author : 付斌
     * @date   : 2024-03-11 14:37
     */
    validData() {
      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) {
      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.addOrderReturn || this.type === this.$config.formMode.addOutReturn) {
        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   : 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>
