<!-- @desc:其它出库新建 @auth:常皓宁 @time : 2024/2/19 9:38 -->
<template>
  <div class="main-div">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <!-- 页面区域-->
    <DkCollapse ref="collapse" @on-change="changeCollapse">
      <!--基本信息-->
      <DkPanel prop="essentialInformation">
          <DkForm slot="content" ref="formInline" v-model="formData" style="width:100%" >
            <!--出库单号-->
            <DkFormItem prop="outNo">
              <InputPop ref="outNo" v-model="formData.outNo"
                        :readonly="true"/>
            </DkFormItem>
            <!-- 出库对象 -->
            <DkFormItem prop="objId"  :label="$t('objOutId')" >
              <SelectMagnifier v-model="formData.objId"
                               ref="objId"
                               primary-key="objId"
                               :display-text="formData.outboundObjectName"
                               :multiple=false
                               :disabled="canEditFlag"
                               @ok="inboundObjectChange"
                               :type="this.$config.MagnifierType.supplierAndCustomer">
              </SelectMagnifier>
            </DkFormItem>
            <!-- 出库原因 -->
            <DkFormItem prop="outReason" :required="true" >
              <SelectPop v-model="formData.outReason" :multiple="false" :options="inboundReasonList"
                         ref="outReason"
                         :labelInValue="true"
                         :disabled="canEditFlag"
                         labelKey="dataValue"
                         valueKey=dataId>
              </SelectPop>
            </DkFormItem>
            <!-- 责任人 -->
            <DkFormItem prop="makeStaff" :label="$t('directorMan')" :required="true">
              <SelectMagnifier v-model="formData.makeStaff"
                               :display-text="formData.makeStaffName"
                               primary-key="staffId"
                               :multiple=false
                               :other-condition="{}"
                               :init-search-flag="true"
                               ref="makeStaff"
                               :disabled="canEditFlag"
                               :type="this.$config.MagnifierType.staff">
              </SelectMagnifier>
            </DkFormItem>
            <!--部门-->
            <DkFormItem prop="orgId" :label="$t('department')" :required="true">
              <SelectMagnifier v-model="formData.orgId"
                               :display-text="formData.orgName"
                               primary-key="orgId"
                               :multiple=false
                               :other-condition="{}"
                               :init-search-flag="true"
                               :disabled="canEditFlag"
                               ref="orgId"
                               :type="this.$config.MagnifierType.organization"></SelectMagnifier>
            </DkFormItem>
            <!--自动出库标识-->
            <DkFormItem prop="autoOutFlag" v-show="showAutoFlag">
              <template>
                <i-switch v-model="formData.flgAutoHandle" @on-change="changeIntoStatus"
                          :disabled="type === $config.formMode.handle">
                  <span slot="open"></span>
                  <span slot="close"></span>
                </i-switch>
              </template>
            </DkFormItem>
            <!--出库日期-->
            <DkFormItem prop="outDate"  v-show="showoutDate">
              <DatePickerPop v-model="formData.outDate"
                             :placeholder="$t('inputWords',{'search-name':$t('outDate')})"
                             type="date" :short-cut-flag="true"/>
            </DkFormItem>
            <!--备注-->
            <DkFormItem prop="remarks" :span="12">
              <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"
                     :columns="goodsColumns "
                     :new-row-flag="this.type === this.$config.formMode.add"
                     controlId="skuId"
                     @on-choose="getTotals"
                     @changeValue="changeValue"
                     @cell-click="handleClickTable"
                     :add-flag="this.addFlag"
                     :delete-flag="this.deleteFlag"
                     @changeNonStandard="changeNonStandard"
          ></EditTable>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="5" name="dk-form"
                    class="read-only-form">
              <!--货物金额-->
              <DkFormItem prop="sumGoodsAmount" class="amount">
                <InputNumberPop ref="sumGoodsAmount" v-model="goodsFootFormData.sumGoodsAmount" :clearable="false"
                                :digits="2"  :readonly="true"/>
              </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" :disabled="this.canEditFlag?true:false"
                     :table="$config.tables.inbound" :accept="$config.uploadFileConfig.acceptPicType"
                     :format="['jpg','jpeg','png']"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save" @close="close"></DkSaveButton>
  </div>
</template>

<script>
  import {formMixin} from '@/mixins/form'
  export default {
    mixins: [ formMixin],
    data() {
      let self = this
      return {
        //画面模式选项角标
        bottomList: ['1', '2', '3', '5'],
        //出库原因
        inboundReasonList: [],
        //是否显示自动办理出库标识
        showAutoFlag: true,
        //出库日期是否显示
        showoutDate: false,
        // 画面表单数据
        formData: {
          outId: null,//出库单Id
          objId: null,//出库对象id
          outNo: null,//出库单号
          outDate:null,//出库日期
          outReason: null,//出库原因
          flgAutoHandle: false,//自动出库标识
          cusId: null,//客户id
          cusName: null,//客户名称
          cusPhone: null,//客户电话
          orgId: null,//业务部门
          makeStaff: null,//责任人
          makeTime:new Date().format(),//制单日期
          supId: null,//供应商id
          remarks: null,//备注
          // 附件
          annexPaths: [],
          staffId:null,
          outingAmt:0,
          outingQty:0,
          itemList:[],//明细LIST
          deleteItemList: [],//删除明细List
          limitEdit:true,//小编辑标识 true不是 false是
        },
        goodsColumns: [
          // 商品型号
          {
            field: 'skuModel',
            controlId: 'skuId',
            type: 'tableSelect',
            width: 200,
            dataType: self.$config.tableSelectType.inventory,
            fieldUpdate: self.$updateColumns.outChooseIvt,
            searchDetailFlag: true
          },
          // 商品名称
          {
            field: 'skuName',
            controlId: 'skuId',
            type: 'tableSelect',
            width: 200,
            dataType: self.$config.tableSelectType.inventory,
            fieldUpdate: self.$updateColumns.outChooseIvt,
            searchDetailFlag: true
          },
          {field: 'brandName', type: 'disabled'},//商品品牌
          {field: 'skuSpec', type: 'disabled'}, //规格
          //仓库名称
          {
            field: 'whName',
            type: 'disabled',
          },
          //非标号
          {
            field: 'nonStdCode',  type: 'disabled',
          },
          {
            field: 'packBox',
            type: 'disabled',
          },
          //库存数量
          {
            field: 'invQty',
            type: 'disabled',
          },
          // 出库数量
          {
            field: 'outingQty',
            title: self.$t('outQuantity'),
            type: 'number',
            digits: 0,
            sum: true,
            formula: {
              outingAmt: ['priceInto*outingQty', 'priceInto', 'outingQty'],
              outingBox: ['outingQty/packBox', 'outingQty', 'packBox'],
              outingPiece: ['outingQty%packBox', 'outingQty', 'packBox'],
            },
          },
          //基本单位
          {
            field: 'unitName',
            title: self.$t('piece'),
            type: 'disabled',
          },
          //包装规格
          {
            field: 'unitInfo',
            title: self.$t('boxPiece'),
            type: 'nonStandard',
          },
          // //箱（出库中）
          // {
          //   field: 'outingBox',
          //   title: this.$t('thisOutBox'),
          //   type: 'number',
          //   digits: 0,
          //   sum: true,
          //   formula: {
          //     outingQty: ['outingBox*packBox', 'outingBox', 'packBox'],
          //     outingAmt: ['outingBox*packBox*priceInto', 'priceInto', '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', 'priceInto'],
          //   },
          // },
          //出库单价
          {
            field: 'priceInto',
            title: self.$t('priceOut'),
            type: 'disabled',
            digits: 2,
            formula: {
              outingAmt: ['priceInto*outingQty', 'priceInto', 'outingQty'],
            },
          },
          //出库金额
          {
            field: 'outingAmt',
            title: self.$t('outAmount'),
            type: 'disabled',
            digits: 2,
            sum: true,
            formula: {
              priceInto: ['outingAmt/outingQty', 'outingAmt', 'outingQty'],
            },
          },
          {field: 'remarks', type: 'text', equal: true,},
        ],
        //商品合计信息
        goodsFootFormData: {
          sumGoodsAmount: 0,
        },
        //可以编辑标识
        canEditFlag:false,
        addFlag: true ,//商品信息新增
        deleteFlag:true,//商品明细删除标识
      }
    },
    methods: {
      /**
       *   @desc   : 出库对象改变事件
       *   @date   : 2024/3/13 10:55
       *   @author : 寇珊珊
       */
      inboundObjectChange(val) {
        if (val) {
          if (val[0].objType == 2)//客户
          {
            this.formData.cusId = val[0].objId;
            this.formData.cusName = val[0].objName;
            this.formData.cusPhone = val[0].cusPhone;
          } else { //供应商
            this.formData.supId = val[0].objId;
          }
        }
      },
      /**
       *   @desc   : 自动出库标识变更
       *   @date   : 2024/4/8 15:31
       *   @author : 寇珊珊
       */
      changeIntoStatus() {
        if (this.type === this.$config.formMode.add) {
          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   : 表格点击事件
       *   @date   : 2024/4/8 14:35
       *   @author : 寇珊珊
       */
      handleClickTable(e) {
        if (e) {
          this.currentRow = e.row
        }
      },
      /**
       *   @desc   : 行改变事件
       *   @date   : 2024/3/13 11:04
       *   @author : 寇珊珊
       */
      changeValue(field, row, rowIndex) {
        // 计算合计值
        this.getTotals(field, row, rowIndex);
      },

      /**
       * @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'] = 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]['outBox'] = row['nonStandardForm']['box'] ? row['nonStandardForm']['box'] : 0
        table[rowIndex]['outPiece'] = 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']
        }
      },

      /**
       * @desc   : 计算合计
       * @author : 常皓宁
       * @date   : 2024/5/29 13:27
       */
      getTotale(table){
        let itemAmount = 0; // 货物总额
        let outingQty = 0; // 总金额
        let outingAmt = 0; // 总数量
        let quantityName = this.type == this.$config.formMode.edit ? 'outingQty' : 'outingQty'
        let amountName = this.type == this.$config.formMode.edit ? 'outingAmt' : 'outingAmt'
        if (table && table.length > 0) {
          table.forEach(row => {
            if (row[amountName]) {
              // 金额
              itemAmount += parseFloat(row[amountName]);
              // 总金额
              outingAmt += parseFloat(row[amountName]);
              //总数量
              outingQty += parseFloat(row[quantityName]);
            }
          })
        }
        this.goodsFootFormData.sumGoodsAmount = itemAmount;
        this.formData.outingAmt = outingAmt;
        this.formData.outingQty = outingQty;
      },

      /**
       *   @desc   : 获取数据字典
       *   @date   : 2024/3/14 9:24
       *   @author : 寇珊珊
       */
      getDictionaryData() {
        let params = {
          'cpId': this.$store.state.user.cpId,
          'dictCode': this.$config.kindCode.basicOut,
          'flgValid': true
        }
        this.excute(this.$service.commonService, this.$service.commonService.getDictionaryData, params, false).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            this.inboundReasonList = res.data
          }
        })
      },
      /**
       *   @desc   : 加载数据
       *   @date   : 2024/3/14 8:47
       *   @author : 寇珊珊
       */
      initData() {
        //获取数据字典
        this.getDictionaryData()
      },
      /**
       *   @desc   : 校验数据
       *   @date   : 2024/3/14 10:37
       *   @author : 寇珊珊
       */
      validData() {
        let itemTable = this.$refs['goodsTable'].getTableDataFilter();
        if (!itemTable || itemTable.length == 0) {
          this.$Message.warning(this.$t('W_012'))
          return false;
        }
        for (let i = 0; i < itemTable.length; i++) {
          if (!itemTable[i].outingQty || itemTable[i].outingQty === '') {
            this.$message.warning(this.$t('W_041', {'param': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('outingQty')}))
            return false;
          }
          if (!itemTable[i].priceInto || itemTable[i].priceInto === '') {
            this.$message.warning(this.$t('W_041', {'param': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('priceOut')}))
            return false;
          }
          if (itemTable[i].outingQty > itemTable[i].usableQty) {
            this.$message.warning(this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('W_119'))
            // this.$Message.warning(this.$t('W_007', {'param': '本次出库数量不能大于库存量'}))
            return false;
          }
        }
        return true;
      },
      /**
       *   @desc   : 参数赋值
       *   @date   : 2024/3/14 10:36
       *   @author : 寇珊珊
       */
      setParams(arg) {
        if (this.type === this.$config.formMode.handle || this.type  === this.$config.formMode.edit) {
          // 删除的表数据
          let deleteItemTable = this.$refs['goodsTable'].getDeleteData();
          this.formData.deleteItemList = deleteItemTable
          this.formData.outingQty =null
          this.formData.outingAmt = null
        }
        //出库时间
        if(this.formData.outDate){
          this.formData.outDate  = new Date(this.formData.outDate).format('yyyy-MM-dd')
        }
        // 修改新增的表数据
        let itemTable = this.$refs['goodsTable'].getTableDataFilter();
        itemTable.map(row => {
          let item = row
          if(this.formData.flgAutoHandle){
            // 箱（出库中）
            this.$set(item, 'outingBox', 0)
            // 片（出库中）
            this.$set(item, 'outingPiece',0)
          }else{
            // 箱（出库中）
            this.$set(item, 'outingBox', row['outBox'])
            // 片（出库中）
            this.$set(item, 'outingPiece',row['outPiece'])
            // 箱（已出库）
            this.$set(item, 'outBox', 0)
            // 片（已出库）
            this.$set(item, 'outPiece',0)
          }
        })
        //出库价赋值
        for(let i=0;i<itemTable.length;i++){
          itemTable[i].priceOut = itemTable[i].priceInto
        }
        this.formData.staffId = this.formData.makeStaff
        this.formData.itemList = itemTable;
        Object.assign(this.params, this.formData, this.goodsFootFormData)
      },
      /**
       *   @desc   : 保存数据
       *   @date   : 2024/3/14 10:32
       *   @author : 寇珊珊
       */
      saveData() {
        //新建
        if (this.type === this.$config.formMode.add) {
          return this.excute(this.$service.otherOutboundService, this.$service.otherOutboundService.outboundInsert, this.params)
        }
        //出库办理
        else if(this.type === this.$config.formMode.handle) {
          return this.excute(this.$service.otherOutboundService, this.$service.otherOutboundService.handleOutbound, this.params)
        }
        //编辑
        else if(this.type === this.$config.formMode.edit){
          return this.excute(this.$service.otherOutboundService, this.$service.otherOutboundService.outboundUpdate, this.params)
        }
      },
      /**
       *   @desc   : 保存完毕后清空窗体
       *   @date   : 2024/3/14 13:53
       *   @author : 寇珊珊
       */
      clear() {
        this.formData = {
          outId: null,//出库单Id
          inboundObject: null,//出库对象id
          outNo: null,//出库单号
          outDate: null,//出库日期
          outReason: null,//出库原因
          flgAutoHandle: false,//自动出库标识
          cusId: null,//客户id
          cusName: null,//客户名称
          cusPhone: null,//客户电话
          orgId: null,//业务部门
          makeStaff: null,//责任人
          makeTime:new Date().format(),//制单日期
          supId: null,//供应商id
          remarks: null,//备注
          // 附件
          annexPaths: [],
          staffId:null,
        }
        // 清空数据源
        this.$refs['goodsTable'].clearTable();
        //商品合计信息
        this.goodsFootFormData.sumGoodsAmount =0;
      },
      /**
       *   @desc   : 通过id查询
       *   @date   : 2024/3/14 16:29
       *   @author : 寇珊珊
       */
      detail(id) {
        return this.excuteNoParam(this.$service.otherOutboundService, this.$service.otherOutboundService.selectByUpdate, [id]);
      },
      /**
       *   @desc   : 编辑页面赋值
       *   @date   : 2024/3/14 16:42
       *   @author : 寇珊珊
       */
      setValuesByEdit(data) {
        if (data) {
          this.formData = data["data"];
          this.formData.limitEdit= true
          this.formData.outDate = new Date().format("yyyy-MM-dd")
          //出库对象赋值
          if(data['data'].supId && data["data"].supId!=null){
            this.formData.objId = data["data"].supId
            this.formData.outboundObjectName = data["data"].supplierName
          }else if(data['data'].cusId && data["data"].cusId!=null){
            this.formData.objId = data["data"].cusId
            this.formData.outboundObjectName = data["data"].cusName
          }
          //明细赋值
          for(let i=0;i<data["dataItem"].length;i++){
            data["dataItem"][i].priceInto = data["dataItem"][i].priceOut
          }
          this.formData.itemList = data["dataItem"];
          this.goodsFootFormData.sumGoodsAmount = this.formData.outingAmt;
          //办理
          if(this.type === this.$config.formMode.handle ){
            this.canEditFlag = true
            this.addFlag = false;
            let dataItem = data.dataItem
            dataItem.map(row => {
              let item = row
              // 不可查询
              this.$set(item, 'readOnly', ['skuModel','skuName','whId'])
              return item
            })
            this.formData.itemList = dataItem;
          }
          //编辑  手动---自动办理参数为false  小编辑
          if(this.type === this.$config.formMode.edit && !data["data"].flgHandleSetting &&
            data["data"].intoStatus === this.$config.intoStatus.yiRuKu){
            this.formData.limitEdit= false
            this.canEditFlag = true
            this.deleteFlag = false;
            this.addFlag = false;
            let dataItem = data.dataItem
            dataItem.map(row => {
              let item = row
              // 不可查询
              this.$set(item, 'readOnly', ['skuModel','skuName','outingQty','whId'])
              return item
            })
            this.formData.itemList = dataItem;
          }
        }
      },
    },
    created() {
      this.focusItem = 'outId';    // 给第一个组件赋值，可以在混入中自动去聚焦
      this.primaryKey = 'outId'  // 设置主键Id
      //设置默认值
      if (this.$route.params.id){
        // 出库办理
        if (this.type === this.$config.formMode.handle) {
          this.showAutoFlag = false;
          this.showoutDate = true;
        }
      }
    }
  }
</script>

<style>

</style>
