<!-- @desc:新建销售出库  @auth:付斌  @time:2023-09-25 14:10 -->
<template>
  <div class="main-div">
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData" :labelMaxWords="6" style="width:100%;">
          <!--出库单号-->
          <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"
                      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="addOutItemColumns" controlId="skuId" @changeNonStandard="changeNonStandard"
                     @cell-click="handleClickTable" @on-choose="getTotals" @changeValue="getTotals"
          ></EditTable>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="6" name="dk-form"
                    class="form-content-class">
              <!--合计数量-->
              <DkFormItem prop="sumOutingQty">
                <InputNumberPop ref="sumOutingQty" v-model="goodsFootFormData.sumOutingQty" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--货物金额-->
              <DkFormItem prop="sumOutingAmt">
                <InputNumberPop ref="sumOutingAmt" v-model="goodsFootFormData.sumOutingAmt" :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 {
  components: {},
  name: 'sale-return',
  mixins: [formMixin],
  data() {
    let self = this
    return {
      //小数位数
      decimalPlaces:0,
      showAutoFlag: true, //是否显示自动办理出库标识
      showOutDate: true, //是否显示自动办理出库标识
      currentRow: null,   // 表格中的当前行
      formData: {
        outId: null,
        outNo: null,
        outType: null,
        fromId: null,
        fromNo: null,
        orderId: null,
        orderNo: 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,
        outDate: new Date(),
        remarks: null,
        itemList: [],
        deleteItemList: [],
        staffList: [],    //存放从业务员id和分配百分比
        orgList: [],      //存放从业务部门id和分配百分比
        staffId: null,
        staffName: null,
        orgId: null,
        orgName: null,
        outStatus: this.$config.outStatus.chuKuZhong,
        makeStaff: this.$store.state.user.id,
        annexPaths: null,
        outingQty: null,
        outingAmt: null,
        flgAutoHandle: true,
      },
      addressArea: [],
      cityData: [],
      channelList: [],
      cusFromList: [],
      addOutItemColumns: [
        {
          field: 'skuModel',
          type: 'disabled',
        },
        {
          field: 'skuName',
          type: 'disabled',
        },
        {
          field: 'skuCode',
          type: 'disabled',
        },
        //订单数量
        {
          field: 'orderQty',
          type: 'disabled',
          digits: 0,
          sum: true
        },
        //基本单位
        {
          field: 'unitName',
          title: self.$t('piece'),
          type: 'disabled',
        },
        //包装数量
        {
          field: 'boxPiece',
          type: 'disabled',
        },
        // //可出库数量
        // {
        //   field: 'canOutingQty',
        //   type: 'disabled',
        //   digits: 0,
        //   sum: true
        // },
        //出库数量
        {
          field: 'outingQty',
          title: this.$t('thisOutingQty'),
          type: 'number',
          digits: this.decimalPlaces,
          dataType: 'number',
          sum: true,
          formula: {
            outingAmt: ['outingQty*priceOut', 'outingQty', 'priceOut'],
            outingBox: ['outingQty/packBox', 'outingQty', 'packBox'],
            outingPiece: ['outingQty%packBox', 'outingQty', 'packBox'],
          }
        },
        //包装规格
        {
          field: 'unitInfo',
          title: self.$t('thisOutBoxPiece'),
          type: 'nonStandard',
        },
        // //箱（出库中）
        // {
        //   field: 'outingBox',
        //   title: this.$t('thisOutBox'),
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     outingQty: ['outingBox*packBox', 'outingBox', 'packBox'],
        //     outingAmt: ['outingBox*packBox*priceOut', 'priceOut', 'outingBox', 'packBox'],
        //   },
        // },
        // //片（出库中）
        // {
        //   field: 'outingPiece',
        //   title: this.$t('thisOutPiece'),
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     outingQty: ['outingBox*packBox+outingPiece', 'outingPiece','outingBox','packBox'],
        //     outingBox: ['(outingBox*packBox+outingPiece)/packBox', 'outingPiece', 'outingBox' , 'packBox','packBox'],
        //     outingPiece: ['(outingBox*packBox+outingPiece)%packBox', 'outingPiece','outingBox', 'packBox', 'packBox'],
        //     outingAmt: ['(outingBox*packBox+outingPiece)*priceOut', 'outingPiece','outingBox', 'packBox', 'priceOut'],
        //   },
        // },
        {
          field: 'whName',
          type: 'tableSelect',
          multiple: false,
          sortBoolean: false,
          dataType: self.$config.tableSelectType.inventory,
          otherSearchParam: () => {
            return {
              skuId: self.currentRow?.skuId,
              nonStdCode: self.currentRow?.nonStdCode,
            }
          },
          fieldUpdate: [
            {updateField: 'invQty', valueFiled: 'invQty'},
            {updateField: 'usableQty', valueFiled: 'usableQty'},
            {updateField: 'invId', valueFiled: 'invId'},
            {updateField: 'whId', valueFiled: 'whId'},
            {updateField: 'whName', valueFiled: 'whName'},
          ],
          searchDetailFlag: true
        },
        //单价
        {
          field: 'priceOut',
          type: 'disabled',
          formula: {
            outingAmt: ['priceOut*outingQty', 'priceOut', 'outingQty'],
          }
        },
        //出库金额
        {
          field: 'outingAmt',
          type: 'disabled',
          digits: 0,
          sum: true
        },
        //库存量
        {
          field: 'invQty',
          type: 'disabled',
        },
        //可售量
        {
          field: 'usableQty',
          type: 'disabled',
        },
        //非标号
        {
          field: 'nonStdCode', type: 'disabled', equal: true,
        },
        //备注
        {field: 'remarks'},
      ],
      //商品合计信息
      goodsFootFormData: {
        sumOutingQty: 0,
        sumOutingAmt: 0,
      },
    }
  },
  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
      console.log('table',table,rowIndex,row)
      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'] = 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]['outingBox'] = row['nonStandardForm']['box'] ? row['nonStandardForm']['box'] : 0
      table[rowIndex]['outingPiece'] = 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:(row['outingQty']/row['packBox'] >= 1 ? Math.floor(row['outingQty']/row['packBox']):0),
          piece:row['outingQty']%row['packBox'],
        }
        row.nonStandardItems = [
          {code:'formula',label:'计算公式',type:'text',readonly:true},
          {code:'box',label:row['subUnitName'],type:'number' },
          {code:'piece',label:row['unitName'],type:'number',digits:this.decimalPlaces}
        ]
        row['unitInfo'] = (row['outingQty']/row['packBox'] >= 1 ? Math.floor(row['outingQty']/row['packBox']):0) + row['subUnitName'] + (row['outingQty']%row['packBox']).toFixed(this.decimalPlaces) + row['unitName']
      }else{
        row.nonStandardForm = {
          formula: (row['subUnitName']?'1'+row['subUnitName']+ '=':'' ) + row['packBox'] + row['unitName'],
          piece:row['outingQty'],
        }
        row.nonStandardItems = [
          {code:'formula',label:'计算公式',type:'text',readonly:true},
          {code:'piece',label:row['unitName'],type:'number',digits: this.decimalPlaces}
        ]
        row['unitInfo'] = row['outingQty'] + row['unitName']
      }
      row['outingBox'] = row['nonStandardForm']['box']
      row['outingPiece'] = row['nonStandardForm']['piece']
    },

    /**
     * @desc   : 计算合计
     * @author : 常皓宁
     * @date   : 2024/5/29 13:27
     */
    getTotale(table){
      let sumOutingQty = 0;  // 合计数量
      let sumOutingAmt = 0;    // 货物金额
      if (table && table.length > 0) {
        table.forEach(row => {
          if (row["outingQty"]) {
            sumOutingQty += parseFloat(row["outingQty"]);
          }
          if (row["outingAmt"]) {
            sumOutingAmt += parseFloat(row["outingAmt"]);
          }
        })
        this.goodsFootFormData.sumOutingQty = sumOutingQty;
        this.goodsFootFormData.sumOutingAmt = sumOutingAmt;
      }
    },

    /**
     * @desc   :表格点击事件
     * @author : 付斌
     * @date   : 2024-03-06 10:39
     */
    handleClickTable(e) {
      if (e) {
        this.currentRow = e.row
      }
    },
    /**
     * @desc   : 自动出库标识变更
     * @author : 付斌
     * @date   : 2024-04-11 14:47
     */
    changeOutStatus() {
      if (this.type === this.$config.formMode.addOrderOut) {
        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，编辑、办理用出库单ID
      if (this.type === this.$config.formMode.addOrderOut) {
        return this.excuteNoParam(this.$service.orderService, this.$service.orderService.getOrderForOut, [id]);
      } else if (this.type === this.$config.formMode.edit) {
        return this.excuteNoParam(this.$service.orderOutService, this.$service.orderOutService.getOutboundForUpdate, [id]);
      }
    },
    /**
     * @desc   : 编辑页面赋值
     * @author : 付斌
     * @date   : 2024-03-03 9:33
     */
    setValuesByEdit(data) {
      if (data) {
        this.formData = data["data"];

        if (this.type === this.$config.formMode.addOrderOut) {
          this.goodsFootFormData.sumOutingQty = this.formData.sumQuantity;
          this.goodsFootFormData.sumOutingAmt = this.formData.sumAmount;
          //系统自动办理出库
          if (this.$store.state.user.setting[this.$config.settingCode.IVT001] == 1) {
            this.formData.flgAutoHandle = true;
          } else {
            this.formData.flgAutoHandle = false;
          }
        } else if (this.type === this.$config.formMode.edit) {
          this.goodsFootFormData.sumOutingQty = this.formData.outingQty;
          this.goodsFootFormData.sumOutingAmt = this.formData.outingAmt;
        }
        if (!this.formData.outDate) {
          this.formData.outDate = new Date();
        }
        if (!this.formData.outStatus) {
          this.formData.outStatus = this.$config.outStatus.chuKuZhong;
        }
        if (!this.formData.makeStaff) {
          this.formData.makeStaff = this.$store.state.user.id;
        }

        let itemList = data["dataItem"];
        itemList.map(row=>{
          let item = row
          // 箱
          this.$set(item, 'box', row['outingBox'])
          // 片
          this.$set(item, 'piece', row['outingPiece'])

          row.nonStandardForm = {
            formula: (row['subUnitName']?'1'+row['subUnitName']:'' ) + row['packBox'] + row['unitName'],
            box:row['box'],
            piece:row['piece'],
          }
          //包装
          if(row['subUnitId']){
            row.nonStandardItems = [
              {code:'formula',label:'计算公式',type:'text',readonly:true},
              {code:'box',label:row['subUnitName'],type:'number'},
              {code:'piece',label:row['unitName'],type:'number'}
            ]
          }else{
            row.nonStandardItems = [
              {code:'formula',label:'计算公式',type:'text',readonly:true},
              {code:'piece',label:row['unitName'],type:'number',field:'piece'}
            ]
          }
          return item
        })
        this.formData.itemList = itemList
      }
    },
    /**
     * @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.canOutingQty) {
          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.addOrderOut) {
        this.formData.fromId = this.formData.orderId;
        this.formData.fromNo = this.formData.orderNo;
      }
      this.formData.outingQty = this.goodsFootFormData.sumOutingQty;
      this.formData.outingAmt = this.goodsFootFormData.sumOutingAmt;
      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.$set(item, 'outBox', row['outingBox'])
          // 片（已出库）
          this.$set(item, 'outPiece',row['outingPiece'])
          // 箱（出库中）
          this.$set(item, 'outingBox', 0)
          // 片（出库中）
          this.$set(item, 'outingPiece',0)
        }else{
          // 箱（已出库）
          this.$set(item, 'outBox', 0)
          // 片（已出库）
          this.$set(item, 'outPiece',0)
        }
        return item
      })

      // itemTable.forEach((it, index) => {
      //   this.$set(it, 'fromNo', this.formData.orderNo);
      // });
      this.formData.itemList = itemTable
      this.params = {...this.formData};
      this.params.outDate = new Date(this.formData.outDate).toDateStr();
      // console.log('this.params',this.params)
    },
    /**
     * @desc   : 保存数据
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    saveData() {
      console.log('this.params',this.params)
      // this.loading = false
      if (this.type === this.$config.formMode.addOrderOut) {
        return this.excute(this.$service.orderOutService, this.$service.orderOutService.outboundInsert, this.params);
      } else if (this.type === this.$config.formMode.edit) {
        return this.excute(this.$service.orderOutService, this.$service.orderOutService.outboundUpdate, this.params);
      }
    },


    /**
     * @desc   : 判断列是否可以编辑
     * @author : 付斌
     * @date   : 2022/6/21 16:42
     */
    checkColumnIsEdit(field) {

    },
  },

  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 付斌
   * @date   : 2022/3/3 10:32
   */
  created() {
    this.focusItem = 'outId';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'outId'  // 设置主键Id

    //设置默认值
    if (this.$route.params.id) {
      // 出库办理
      if (this.type === this.$config.formMode.handle) {
        this.showAutoFlag = false;
      }
    }
  },
}
</script>
