<!-- @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">
        <div id="search-cond-div" ref="search-cond-div" slot="content" class="form-content-class">
          <DkForm slot="content" ref="formInline" v-model="formData" style="width:100%" >
            <!--入库单号-->
            <DkFormItem prop="intoNo">
              <InputPop ref="intoNo" v-model="formData.intoNo"
                        :readonly="true"/>
            </DkFormItem>
            <!-- 入库对象 -->
            <DkFormItem prop="objId" >
              <SelectMagnifier v-model="formData.objId"
                               ref="objId"
                               primary-key="objId"
                               :display-text="formData.inboundObjectName"
                               :multiple=false
                               :disabled="canEditFlag"
                               @ok="inboundObjectChange"
                               :type="this.$config.MagnifierType.supplierAndCustomer">
              </SelectMagnifier>
            </DkFormItem>
            <!-- 入库原因 -->
            <DkFormItem prop="intoReason" :required="true" >
              <SelectPop v-model="formData.intoReason" :multiple="false" :options="inboundReasonList"
                         ref="intoReason"
                         :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="autoFlag" 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="intoDate"  v-show="showIntoDate">
              <DatePickerPop v-model="formData.intoDate"
                             :placeholder="$t('inputWords',{'search-name':$t('intoDate')})"
                             type="date" :short-cut-flag="true" />
            </DkFormItem>
            <!--备注-->
            <DkFormItem prop="remarks" :span="12">
              <InputPop ref="remarks" v-model="formData.remarks"
                        maxlength=500 textareaFlag/>
            </DkFormItem>
          </DkForm>
        </div>
      </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"
                     @onBatchChoose="batchChoose"
                     :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,
        //入库日期是否显示
        showIntoDate: false,
        // 画面表单数据
        formData: {
          intoId: null,//入库单Id
          objId: null,//入库对象id
          intoNo: null,//入库单号
          intoDate:null,//入库日期
          intoReason: null,//入库原因
          flgAutoHandle: false,//自动入库标识
          cusId: null,//客户id
          cusName: null,//客户名称
          cusPhone: null,//客户电话
          orgId: null,//业务部门
          makeStaff: null,//责任人
          makeTime:new Date().format(),//制单日期
          supId: null,//供应商id
          remarks: null,//备注
          defWhId: null,//部门默认仓库ID
          // 附件
          annexPaths: [],
          staffId:null,
          intoingAmt:0,
          intoingQty:0,
          itemList:[],//明细LIST
          deleteItemList: [],//删除明细List
          limitEdit:true,//小编辑标识 true不是 false是
        },
        goodsColumns: [
          // 商品型号
          {
            field: 'skuModel',
            controlId: 'skuId',
            type: 'tableSelect',
            width: 200,
            dataType: self.$config.tableSelectType.goodsForInto,
            fieldUpdate: self.$updateColumns.intoChooseIvt,
            searchDetailFlag: true
          },
          // 商品名称
          {
            field: 'skuName',
            controlId: 'skuId',
            type: 'tableSelect',
            width: 200,
            dataType: self.$config.tableSelectType.goodsForInto,
            fieldUpdate: self.$updateColumns.intoChooseIvt,
            searchDetailFlag: true
          },
          // 入库数量
          {
            field: 'intoingQty',
            title: self.$t('entryQty'),
            type: 'number',
            digits: 0,
            sum: true,
            formula: {
              intoingAmt: ['priceInto*intoingQty', 'priceInto', 'intoingQty'],
            },
          },
          //入库单价
          {
            field: 'priceInto',
            type: 'number',
            digits: 2,
            flgUserSensitive: true,
            formula: {
              intoingAmt: ['priceInto*intoingQty', 'priceInto', 'intoingQty'],
            },
          },
          //入库金额
          {
            field: 'intoingAmt',
            title: self.$t('entryAmt'),
            type: 'disabled',
            digits: 2,
            sum: true,
            formula: {
              priceInto: ['intoingAmt/intoingQty', 'intoingAmt', 'intoingQty'],
            },
          },
          //基本单位
          {
            field: 'unitName',
            title: self.$t('piece'),
            type: 'disabled',
          },
          {
            field: 'unitInfo',
            title: self.$t('boxPiece'),
            type: 'nonStandard',
          },
          // {
          //   field: 'packBox',
          //   type: 'disabled',
          // },
          //箱（入库中）
          // {
          //   field: 'intoingBox',
          //   type: 'number',
          //   digits: 0,
          //   sum: true,
          //   formula: {
          //     intoingQty: ['intoingBox*packBox', 'intoingBox', 'packBox'],
          //     intoingAmt: ['intoingBox*packBox*priceInto', 'priceInto', 'intoingBox', 'packBox'],
          //   },
          // },
          // //片（入库中）
          // {
          //   field: 'intoingPiece',
          //   type: 'number',
          //   digits: 0,
          //   sum: true,
          //   formula: {
          //     intoingQty: ['intoingBox*packBox+intoingPiece', 'intoingPiece','intoingBox','packBox'],
          //     intoingBox: ['(intoingBox*packBox+intoingPiece)/packBox', 'intoingPiece', 'intoingBox' , 'packBox','packBox'],
          //     intoingPiece: ['(intoingBox*packBox+intoingPiece)%packBox', 'intoingPiece','intoingBox', 'packBox', 'packBox'],
          //     intoingAmt: ['(intoingBox*packBox+intoingPiece)*priceOut', 'intoingPiece','intoingBox', 'packBox', 'priceInto'],
          //   },
          // },
          //仓库名称
          {
            field: 'whId',
            type: 'select',
            options: () => self.warehouseList,
            labelKey: 'whName',
            valueKey: 'whId',
            dataType: self.$config.tableSelectType.warehouse,
            fieldUpdate: [
              {updateField: 'whName', valueFiled: 'whName'},
              {updateField: 'whId', valueFiled: 'whId'},
            ],
            searchDataFlag: false,
          },
          {field: 'brandName', type: 'disabled'},//商品品牌
          {field: 'skuSpec', type: 'disabled'}, //规格
          {field: 'remarks', type: 'text', equal: true,},
        ],
        //商品合计信息
        goodsFootFormData: {
          sumGoodsAmount: 0,
        },
        //仓库
        warehouseList: [],
        whId:null,
        whName:null,
        //可以编辑标识
        canEditFlag:false,
        addFlag: true ,//商品信息新增
        deleteFlag:true,//商品明细删除标识
      }
    },
    methods: {
      /**
       * @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]['intoingQty'] = row['packBox'] * (row['nonStandardForm']['box']?row['nonStandardForm']['box']:0) + (row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0)
        table[rowIndex]['intoingAmt'] = table[rowIndex]['intoingQty'] * table[rowIndex]['priceInto']
        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   : 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:32
       *   @author : 寇珊珊
       */
      changeIntoStatus() {
        if (this.type === this.$config.formMode.add) {
          if (this.formData.flgAutoHandle) {
            this.formData.intoDate = new Date().format("yyyy-MM-dd")
            this.showIntoDate = true
          }else{
            this.formData.intoDate = null
            this.showIntoDate = false
          }
        }else {
          this.formData.intoDate = new Date().format("yyyy-MM-dd")
        }
      },
      /**
       *   @desc   : 行改变事件
       *   @date   : 2024/3/13 11:04
       *   @author : 寇珊珊
       */
      changeValue(field, row, rowIndex) {
        // 计算合计值
        this.getTotals(field, row, rowIndex);
      },
      /**
       *   @desc   : 获取商品表格中数量、金额后计算总单信息
       *   @date   : 2022/5/30 15:31
       *   @author : 寇珊珊
       */
      getTotals(field, row, rowIndex) {
        let table = this.$refs['goodsTable'].getTableDataFilter();
       this.getTotale(table)
        if (!row["intoingQty"] || row["intoingQty"] == '') {
          this.$set(row, 'intoingQty', 0);
        }
        if (!row["intoingAmt"] || row["intoingQty"] == '') {
          this.$set(row, 'intoingAmt', 0);
        }

        this.decimalPlaces = row['decimalPlaces']

        if (row['subUnitId']) {
          row.nonStandardForm = {
            formula: (row['subUnitName'] ? '1' + row['subUnitName'] + '=' : '') + row['packBox'] + row['unitName'],
            box: (row['intoingQty'] / row['packBox'] >= 1 ? Math.floor(row['intoingQty'] / row['packBox']) : 0),
            piece: row['intoingQty'] % 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['intoingQty'] / row['packBox'] >= 1 ? Math.floor(row['intoingQty'] / row['packBox']) : 0) + row['subUnitName'] + (row['intoingQty'] % row['packBox']).toFixed(this.decimalPlaces) + row['unitName']
        } else {
          row.nonStandardForm = {
            formula: (row['subUnitName'] ? '1' + row['subUnitName'] + '=' : '') + row['packBox'] + row['unitName'],
            piece: row['intoingQty'],
          }
          row.nonStandardItems = [
            {code: 'formula', label: '计算公式', type: 'text', readonly: true},
            {code: 'piece', label: row['unitName'], type: 'number', digits: this.decimalPlaces}
          ]
          row['unitInfo'] = row['intoingQty'] + row['unitName']
        }
        //选择数据带出默认仓库
        if (!row.whId || row.whId === 0 || row.whId === null) {
          this.$set(row, 'whId', this.whId);
          this.$set(row, 'whId_Name', this.whName);
        }
      },

      /**
       * @desc   : 计算合计
       * @author : 常皓宁
       * @date   : 2024/5/29 13:27
       */
      getTotale(table){
        let itemAmount = 0; // 货物总额
        let intoingQty = 0; // 总金额
        let intoingAmt = 0; // 总数量
        let quantityName = this.type == this.$config.formMode.edit ? 'intoingQty' : 'intoingQty'
        let amountName = this.type == this.$config.formMode.edit ? 'intoingAmt' : 'intoingAmt'
        if (table && table.length > 0) {
          table.forEach(row => {
            if (row[amountName]) {
              // 金额
              itemAmount += parseFloat(row[amountName]);
              // 总金额
              intoingAmt += parseFloat(row[amountName]);
              //总数量
              intoingQty += parseFloat(row[quantityName]);
            }
          })
        }
        this.goodsFootFormData.sumGoodsAmount = itemAmount;
        this.formData.intoingAmt = intoingAmt;
        this.formData.intoingQty = intoingQty;
      },
      /**
       *   @desc   : 批量选择
       *   @date   : 2024/3/14 10:04
       *   @author : 寇珊珊
       */
      batchChoose(batchRows,rowIndex){
        batchRows.forEach(it=> {
          if(!it.whId || it.whId === 0 || it.whId === null){
            this.$set(it,'whId',this.whId);
            this.$set(it,'whId_Name',this.whName);
          }
        })
      },
      /**
       *   @desc   : 查询仓库
       *   @date   : 2024/3/14 8:45
       *   @author : 寇珊珊
       */
      getWarehouse() {
        let params = {
          'cpId': this.$store.state.user.cpId,
          'flgValid': true
        }
        this.excute(this.$service.commonService, this.$service.commonService.getWarehouse, params, false).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            this.warehouseList = res.data
            //赋值默认仓库 组件需要
            let newList = res.data.filter(it=>it.flgDefault)
            this.whId = newList[0].whId
            this.whName = newList[0].whName
          }
        })
      },
      /**
       *   @desc   : 获取数据字典
       *   @date   : 2024/3/14 9:24
       *   @author : 寇珊珊
       */
      getDictionaryData() {
        let params = {
          'cpId': this.$store.state.user.cpId,
          'dictCode': this.$config.kindCode.basicEnter,
          '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.getWarehouse()
        //获取数据字典
        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].intoingQty || itemTable[i].intoingQty === '') {
            this.$message.warning(this.$t('W_041', {'param': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('intoingQty')}))
            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('priceInto')}))
            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.intoingQty =null
          this.formData.intoingAmt = null
        }
        //入库时间
        if(this.formData.intoDate){
           this.formData.intoDate  = new Date(this.formData.intoDate).format('yyyy-MM-dd')
        }
        // 修改新增的表数据
        let itemTable = this.$refs['goodsTable'].getTableDataFilter();
        if(itemTable.filter(it=>it.whId).length==itemTable.length){
          this.params.whId =itemTable[0].whId
        }
        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.otherInboundService, this.$service.otherInboundService.inboundInsert, this.params)
        }
        //入库办理
        else if(this.type === this.$config.formMode.handle) {
          return this.excute(this.$service.otherInboundService, this.$service.otherInboundService.handleInbound, this.params)
        }
        //编辑
        else if(this.type === this.$config.formMode.edit){
          return this.excute(this.$service.otherInboundService, this.$service.otherInboundService.inboundUpdate, this.params)
        }
      },
      /**
       *   @desc   : 保存完毕后清空窗体
       *   @date   : 2024/3/14 13:53
       *   @author : 寇珊珊
       */
      clear() {
        this.formData = {
          intoId: null,//入库单Id
          inboundObject: null,//入库对象id
          intoNo: null,//入库单号
          intoDate: null,//入库日期
          intoReason: null,//入库原因
          flgAutoHandle: false,//自动入库标识
          cusId: null,//客户id
          cusName: null,//客户名称
          cusPhone: null,//客户电话
          orgId: null,//业务部门
          makeStaff: null,//责任人
          makeTime:new Date().format(),//制单日期
          supId: null,//供应商id
          remarks: null,//备注
          defWhId: null,//部门默认仓库ID
          // 附件
          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.otherInboundService, this.$service.otherInboundService.selectByUpdate, [id]);
      },
      /**
       *   @desc   : 编辑页面赋值
       *   @date   : 2024/3/14 16:42
       *   @author : 寇珊珊
       */
      setValuesByEdit(data) {
        if (data) {
          this.formData = data["data"];
          this.formData.limitEdit= true
          this.formData.intoDate = new Date().format("yyyy-MM-dd")
          //入库对象赋值
          if(data['data'].supId && data["data"].supId!=null){
            this.formData.objId = data["data"].supId
            this.formData.inboundObjectName = data["data"].supplierName
          }else if(data['data'].cusId && data["data"].cusId!=null){
            this.formData.objId = data["data"].cusId
            this.formData.inboundObjectName = data["data"].cusName
          }
          //明细赋值
          this.formData.itemList = data["dataItem"];
          this.goodsFootFormData.sumGoodsAmount = this.formData.intoingAmt;
          //办理
          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','intoingQty','intoingAmt','priceInto','whId'])
              return item
            })
            this.formData.itemList = dataItem;
          }
        }
      },
    },
    created() {
      this.focusItem = 'intoId';    // 给第一个组件赋值，可以在混入中自动去聚焦
      this.primaryKey = 'intoId'  // 设置主键Id
      //设置默认值
      if (this.$route.params.id){
        // 入库办理
        if (this.type === this.$config.formMode.handle) {
          this.showAutoFlag = false;
          this.showIntoDate = true;
        }
      }
    }
  }
</script>

<style>

</style>
