<!-- @desc:新建库存盘点 @auth:songy @time : 2024/2/20 9:38 -->
<template>
  <div class="main-div" style="position: relative;">
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData">
          <!--盘点单号-->
          <DkFormItem prop="checkNo">
            <InputPop ref="checkNo" v-model="formData.checkNo" :readonly="true"/>
          </DkFormItem>
          <!--仓库-->
          <DkFormItem prop="whId" :label="$t('whName')" :required="true">
            <SelectMagnifier v-model="formData.whId" :display-text="formData.whName"
                             :type="this.$config.MagnifierType.warehouse"
                             @ok="whOk"
                             :disabled="checkColumnIsEdit('whId')"
                             :multiple="false"/>
          </DkFormItem>
          <!--业务部门-->
          <DkFormItem prop="orgId" :label="$t('checkOrg')" :required="true">
            <SelectMagnifier v-model="formData.orgId" :display-text="formData.checkOrg"
                             :type="this.$config.MagnifierType.org"
                             @ok="orgOk"
                             :multiple="false"/>
          </DkFormItem>
          <!--业务员-->
          <DkFormItem prop="staffId" :label="$t('checkStaff')">
            <SelectMagnifier v-model="formData.staffId" :display-text="formData.checkStaff"
                             :type="this.$config.MagnifierType.staff"
                             @ok="staffOk"
                             :multiple="false"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks">
            <InputPop v-model="formData.remarks" textareaFlag/>
          </DkFormItem>
          <!--锁库标识-->
          <DkFormItem prop="flgLock" :label="$t('flgLock')">
            <dk-switch v-model="formData.flgLock"/>
          </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"
                     control-id="invId"
                     :new-row-flag="true" :height="tableHeight"
                     :operate-flag="formData.whId==null?false:true"
                     :newRowFlag="formData.whId==null?false:true"
                     @changeValue="changeValueLoss"
                     :columns="checkItemColumns"
          ></EditTable>
        </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.check" :accept="$config.uploadFileConfig.acceptPicType"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save(true)" @close="close">
      <DkButton ref="saveQuotation" type="primary" @click="save(false)" style="margin-right: 10px;" :loading="loading">{{ $t('saveT') }}
      </DkButton>
    </DkSaveButton>
    >
  </div>
</template>

<script>

import {formMixin} from '@/mixins/form'

export default {
  components: {},
  mixins: [formMixin],
  data() {
    let self = this
    return {
      //盘点原因
      lossReasonList: [],
      formData: {
        orgId: null,
        checkOrg: null,
        orgCode: null,
        checkStatus: null,
        makeStaff: self.$store.state.user.id,
        staffId: null,
        checkStaff: null,
        staffCode: null,
        whId: null,
        whName: null,
        flgLock: null,
        annexPaths: null, //附件
        remarks: null,
        itemList: [],
        deleteItemList:[],// 删除明细
      },
      // 暂存显示列
      checkItemColumns: [
        // 新建库存商品
        {
          field: 'skuModel',
          type: 'tableSelect',
          controlId: 'invId',
          dataType: self.$config.tableSelectType.inventory,
          // 查询条件
          otherSearchParam: () => {
            return {
              whId: self.formData.whId,
            }
          },
          fieldUpdate:self.$updateColumns.checkChooseIvt,
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          type: 'tableSelect',
          controlId: 'invId',
          dataType: self.$config.tableSelectType.inventory,
          // 查询条件
          otherSearchParam: () => {
            return {
              whId: self.formData.whId,
            }
          },
          fieldUpdate:self.$updateColumns.checkChooseIvt,
          searchDetailFlag: true
        },
        {
          field: 'skuCode',
          type: 'disabled',
        },
        {
          field: 'whName',
          type: 'disabled',
        },
        //库存数量
        {
          field: 'invQty',
          type: 'disabled',
        },
        //盘点数量
        {
          field: 'checkQty',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            balanceQty: ['checkQty-invQty', 'invQty', 'checkQty'],
            intoingAmt: ['checkQty*priceInto', 'checkQty', 'priceInto'],
            box: ['checkQty/packBox', 'checkQty', 'packBox'],
            piece: ['checkQty%packBox', 'checkQty', 'packBox'],
          },
        },
        //包装
        {
          field: 'packBox',
          type: 'disabled',
        },
        //箱
        {
          field: 'box',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            checkQty: ['box*packBox', 'box', 'packBox'],
            balanceQty: ['box*packBox-invQty', 'invQty', 'box', 'packBox'],
            intoingAmt: ['box*packBox*priceInto', 'box', 'packBox', 'priceInto'],
          },
        },
        //片
        {
          field: 'piece',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            checkQty: ['box*packBox+piece', 'piece','box','packBox'],
            box: ['(box*packBox+piece)/packBox', 'piece', 'box' , 'packBox','packBox'],
            piece: ['(box*packBox+piece)%packBox', 'piece','box', 'packBox', 'packBox'],
            balanceQty: ['(box*packBox+piece)-invQty', 'invQty', 'piece','box','packBox'],
            intoingAmt: ['(box*packBox+piece)*priceInto', 'piece','box', 'packBox', 'priceInto'],
          },
        },
        //差异数量
        {
          field: 'balanceQty',
          type: 'disabled',
        },
        //盘盈单价
        {
          field: 'priceInto',
          title: self.$t('checkPrice'),
          type: 'number',
          digits: 0,
          formula: {
            intoingAmt: ['balanceQty*priceInto', 'balanceQty', 'priceInto'],
          },
        },
        //盘盈金额
        {
          field: 'intoingAmt',
          title: self.$t('checkAmt'),
          type: 'number',
          digits: 0,
          formula: {
            priceInto: ['intoingAmt/balanceQty', 'balanceQty', 'intoingAmt'],
          },
        },

        // 盘亏原因
        {
          field: 'lossReason',
          title: self.$t('lossReasonName'),
          type: 'select',
          options: () => self.lossReasonList,
          labelKey: 'dataValue',
          valueKey: 'dataId',
          dataType: self.$config.tableSelectType.dictionaryData,
          fieldUpdate: [
            {updateField: 'lossReason', valueFiled: 'dataValue'},
          ],
          searchDetailFlag: true
        },
        //负责人
        {
          field: 'dutyStaff',
          type: 'tableSelect',
          dataType: self.$config.tableSelectType.staff,
          fieldUpdate: [
            {updateField: 'staffId', valueFiled: 'staffId'},
            {updateField: 'dutyStaff', valueFiled: 'staffName'},
          ],
          searchDetailFlag: true
        },
        //备注
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
    }
  },

  methods: {
    /**
     * @desc   : 加载数据
     * @author : 宋扬
     * @date   : 2024/3/27 15:50
     */
    initData() {
      //获取数据字典
      this.getDictionaryData()
    },
    /**
     * @desc   : 获取部门相关
     * @author : 宋扬
     * @date   : 2024/3/14 15:03
     */
    orgOk(val) {
      if (val && val.length > 0) {
        this.formData.orgId = val[0].orgId
        this.formData.orgCode = val[0].orgCode
        this.formData.orgName = val[0].orgName
      }
    },
    /**
     *   @desc   : 获取业务员相关
     *   @author : 宋扬
     *   @date   : 2024/3/14 15:03
     */
    staffOk(val) {
      if (val && val.length > 0) {
        this.formData.staffId = val[0].staffId
        this.formData.staffCode = val[0].staffCode
        this.formData.staffName = val[0].staffName
        if (this.formData.orgId == null) {
          this.formData.orgId = val[0].orgId
          this.formData.orgCode = val[0].orgCode
          this.formData.orgName = val[0].orgName
        }
      }
    },

    /**
     * @desc   : 仓库信息
     * @author : 宋扬
     * @date   : 2024/3/26 15:03
     */
    whOk(val) {
      if (val && val.length > 0) {
        this.formData.whId = val[0].whId
        this.formData.whCode = val[0].whCode
        this.formData.whName = val[0].whName
      }
    },

    /**
     * @desc   : 赋值盘点实体信息
     * @author : 宋扬
     * @date   : 2024/3/18 10:57
     */
    setParams(val) {
      let table = this.$refs['goodsTable'].getTableDataFilter();
      // 新建时赋值数据
      if (this.type === this.$config.formMode.add) {
        table.forEach((it, index) => {
          // 赋值商品顺序列
          this.$set(it, 'itemIndex', index + 1);
        });
      }
      // 赋值盘点状态
      if (val) {
        this.formData.checkStatus = this.$config.checkStatus.done
      } else {
        this.formData.checkStatus = this.$config.checkStatus.staging
      }
      // 赋值盘点明细信息
      this.formData.itemList = table;
      // 赋值盘点主表信息
      this.params = {...this.formData}
      // 赋值删除明细
      if (this.type === this.$config.formMode.edit) {
        // 删除的表数据
        let deleteItemTable = this.$refs['goodsTable'].getDeleteData();
        this.formData.deleteItemList = deleteItemTable
      }
    },

    /**
     * @desc   : 判断列是否可以编辑
     * @author : 宋扬
     * @date   : 2024/3/21 16:25
     */
    checkColumnIsEdit(field) {
      if(this.type === this.$config.formMode.edit){
        return true;
      }
      else
      {
        return false;
      }
    },

    /**
     * @desc   : 保存数据
     * @author : 宋扬
     * @date   : 2024/3/15 10:03
     */
    saveData() {
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.checkService, this.$service.checkService.insert, this.params);
      } else if (this.type === this.$config.formMode.edit) {
        return this.excute(this.$service.checkService, this.$service.checkService.update, this.params);
      }
    },

    /**
     * @desc   : 通过id查询
     * @author : 宋扬
     * @date   : 2024/3/19 15:27
     */
    detail(id) {
      return this.excuteNoParam(this.$service.checkService, this.$service.checkService.getCheckForUpdate, [id], false);
    },

    /**
     * @desc   : 值改变
     * @author : 宋扬
     * @date   : 2024/3/27 14:11
     */
    changeValueLoss(field, row, rowIndex) {
      let table = this.$refs['goodsTable'].tableData;
      if (table && table.length > 0 && table[rowIndex]) {
        if(row["checkQty"]!=0){
          // 判断库存量小于盘点量为盘盈，则责任人和盘亏原因不可用
          if (row["invQty"] < row["checkQty"]) {
            row['dutyStaff']=null;
            row['lossReason']=null;
            this.$set(table[rowIndex], 'readOnly', ['dutyStaff', 'lossReason']);
          }else{
            row['priceInto']=null;
            row['intoingAmt']=null;
            this.$set(table[rowIndex], 'readOnly', ['priceInto', 'intoingAmt']);
          }
        }
      }
    },

    /**
     * @desc   : 数据字典
     * @author : 宋扬
     * @date   : 2024/3/27 15:51
     */
    getDictionaryData() {
      let params = {
        'dictCode': this.$config.kindCode.basicLossReason,
      }
      this.excute(this.$service.commonService, this.$service.commonService.getDictionaryData, params, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.lossReasonList = res.data
        }
      })
    },

    /**
     * @desc   : 盘点编辑赋值
     * @author : 宋扬
     * @date   : 2024/3/28 15:52
     */
    setValuesByEdit(data) {
      if (data) {
        this.formData = data["data"];
        this.formData.itemList = data["dataItem"];
      }
    },

    /**
     * @desc   : 校验数据
     * @author : 宋扬
     * @date   : 2024/4/7 11:10
     */
    validData(val){
      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(val){
          // 盘点量不能为空或零
          if (it.balanceQty > 0 && (!it.priceInto || it.priceInto === '' || it.priceInto===0)) {
            this.$Message.warning(this.$t('W_042', {'param': this.$t('priceInto')}))
            return false;
          }
          else if(it.balanceQty < 0){
            if(!it.dutyStaff){
              this.$Message.warning(this.$t('W_042', {'param': this.$t('personUser')}))
              return false;
            }else if(!it.lossReason){
              this.$Message.warning(this.$t('W_042', {'param': this.$t('lossReasonName')}))
              return false;
            }
          }
        }
      }
      return true;
    }

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