<!-- @desc:采购入库新建  @auth:常皓宁 @time:2024/03/14 14:15 -->
<template>
  <div class="main-div" style="position: relative;">
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <BaseIndexButtonGroup id="BaseIndexButtonGroup">
      <template #left>
        <!--    选择来源单    -->
        <BaseIndexButton ref="choosePurchase" name="choosePurchase"
                         :disabled="choosePurchaseFlag"
                         @click="open($config.routeUrl.purEnter.choosePurchase)"/>
        <!--    清空条件    -->
        <BaseIndexButton ref="clearDetail" name="clearDetail" :disabled="choosePurchaseFlag"
                         @click="open($config.routeUrl.purEnter.clearDetail)"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData" style="width:100%">
          <!--供应商-->
          <DkFormItem prop="supId" :label="$t('supplierName')" :required="true">
            <SelectMagnifier v-model="formData.supId" :display-text="formData.supplierName"
                             :type="this.$config.MagnifierType.supplier"
                             :multiple="false"
                             :disabled="!showAutoFlag"
                             :otherCondition="{supplierType:this.$config.kindCode.supplierPur}"/>
          </DkFormItem>
          <!--收货仓库-->
          <DkFormItem prop="whId" :label="$t('wareHouse')" :required="true">
            <SelectPop v-model="formData.whId" ref="whId"
                       :options="warehouseList"
                       :multiple="false"
                       :disabled="!showAutoFlag"
                       labelKey="whName" valueKey="whId"
                        @on-select="changItemWhId">
            </SelectPop>
          </DkFormItem>
          <!-- 采购人 -->
          <DkFormItem prop="makingUser" :label="'采购人'">
            <SelectMagnifier v-model="formData.makingUser"
                             :display-text="formData.makingUserName"
                             :multiple="false"
                             :disabled="!showAutoFlag"
                             :type="this.$config.MagnifierType.staff">
            </SelectMagnifier>
          </DkFormItem>
          <!--部门-->
          <DkFormItem prop="orgId" :label="$t('department')">
            <SelectMagnifier v-model="formData.orgId"
                             :display-text="formData.orgName"
                             :multiple="false"
                             :disabled="!showAutoFlag"
                             :type="this.$config.MagnifierType.organization"></SelectMagnifier>
          </DkFormItem>
          <!--来源单号-->
          <DkFormItem prop="fromNo">
            <InputPop ref="fromNo" v-model="formData.fromNo" :readonly="true"/>
          </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>
      </DkPanel>
      <!--商品信息-->
      <DkPanel prop="goodsInformation">
        <div id="search-cond-div-goods-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable slot="left"
                     ref="detailTable"
                     majorField="itemId"
                     :data="purchaseItemList"
                     :columns="goodsColumns"
                     :height="400"
                     :freeze="false"
                     :show-footer="true"
                     :add-flag="this.addFlag"
                     :delete-flag="this.deleteFlag"
                     @changeValue="changeValue"
                     @on-choose="changeValue"
                     @changeNonStandard="changeNonStandard"
          ></EditTable>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="5" name="dk-form"
                    class="read-only-form">
              <!--合计数量-->
              <DkFormItem prop="sumQuantity">
                <InputNumberPop ref="sumQuantity" v-model="goodsFootFormData.sumQuantity" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--货物金额-->
              <DkFormItem prop="sumAmount" class="amount">
                <InputNumberPop ref="sumAmount" :v-model="goodsFootFormData.sumAmount" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--标价总额-->
              <DkFormItem prop="sumStandard" class="amount">
                <InputNumberPop ref="sumStandard" v-model="goodsFootFormData.sumStandard" :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"
                     :table="$config.tables.inbound" :accept="$config.uploadFileConfig.acceptPicType"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>

    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save" @close="close"></DkSaveButton>

    <!--选择采购订单弹窗-->
    <DkModal
      :loading="loading"
      ref="modal_search"
      id="search-data-class"
      class-name="change-class"
      width="1100px"
      v-model="chooseModal"
      :shortcut-flag="false"
      @modalOk="modalOk"
      @modalCancel="modalCancel"
      @on-visible-change="openPurchaseModal"
      :title="modalTitle">
      <BaseIndexButtonGroup id="ButtonGroup">
        <template #left>
          <BaseIndexButton ref="search" name="search" @click="getDataTable"></BaseIndexButton>
          <BaseIndexButton :finalFlag="true" ref="clear" name="clear"
                           @click="$refs['searchCond'].clearCondition()"></BaseIndexButton>
        </template>
      </BaseIndexButtonGroup>
      <SearchCond id="search-cond-div" width="1000px" class="search-cond-class"
                  v-if="searchContent && searchContent.length > 0" ref="searchCond"
                  v-model="searchCond" :setFlag="false" :searchContent="searchContent" :col-count="4"></SearchCond>
      <DkSplit mode="vertical" v-model="split" :height="chooseTableHeight">
        <div slot="top">
          <DkTable
            ref="purTable"
            :data="purList"
            :height="this.chooseTableHeight * split"
            :page-flag="false"
            :show-setting-flag="false"
            :freeze="false"
            :multiple="false"
            :choose-flag="false"
            :clearCheckFlag="false"
            :auto-width-flag="false"
            primaryKey="purId"
            :showCheckboxHeader="false"
            :chooseCheckFlag="false"
            :showSettingFlag="false"
            @current-change="currentChange($event)">
            <!--采购单号-->
            <DkTableColumn field="purNo"></DkTableColumn>
            <!--部门-->
            <DkTableColumn field="orgName"></DkTableColumn>
            <!--员工-->
            <DkTableColumn field="staffName"></DkTableColumn>
            <!--供应商-->
            <DkTableColumn field="supplierName"></DkTableColumn>
            <!--联系人-->
            <DkTableColumn field="contactName"></DkTableColumn>
            <!--联系电话-->
            <DkTableColumn field="contactPhone"></DkTableColumn>
            <!--取货日期-->
            <DkTableColumn field="pickupDate"></DkTableColumn>
          </DkTable>
        </div>
        <div slot="bottom">
          <!--订单明细-->
          <DkTable :pageFlag="false"
                   :pageTotalFlag="false"
                   primaryKey="itemId"
                   :id="'table-'+$options.name"
                   :show-footer="true"
                   ref="detail-select"
                   :showSettingFlag="false"
                   :data="tableDataDetail_goodsDetail"
                   :height="this.chooseTableHeight * (1-split)">
            <DkTableColumn
              v-for="(item, index) in tableDataTitle_goodsDetail"
              :key="'goodsDetail'+index"
              align="center"
              :type="item.type"
              :field="item.field"
              :title="item.title"
              :sum="item.sum"
              :digits="item.digits"
              :width="item.width"
              :dataType="item.dataType"
              :tree-node="item.treeNode"
            >
            </DkTableColumn>
          </DkTable>
        </div>
      </DkSplit>
    </DkModal>
  </div>
</template>

<script>

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

export default {
  components: {},
  mixins: [formMixin],
  data() {
    let self = this
    return {
      //入库日期是否显示
      showIntoDate: false,
      //来源订单Id
      purFromId:null,
      //是否显示自动办理入库标识
      showAutoFlag: true,
      tableHeight: 450,
      tableDataDetail_goodsDetail: [],  // 用于存放订单明细数据
      tableDataTitle_goodsDetail: [
        {field: 'skuName'},
        {field: 'skuCode'},
        //采购数量
        {
          field: 'itemQty',
          title: self.$t('purchaseQuantity'),
          type: 'number',
          digits: 0,
          sum: true
        },
        // //标价
        // {
        //   field: 'pricePurchase',
        //   title: self.$t('priceStd'),
        //   digits: 2,
        //   type: 'number',
        //   UserSensitiveFlag: true
        // },
        // //标价金额
        // {
        //   field: 'amtStd',
        //   title: self.$t('amtStd'),
        //   type: 'number',
        //   digits: 2,
        //   sum: true,
        //   UserSensitiveFlag: true
        // },

        //采购价
        {
          field: 'pricePur',
          title: self.$t('pricePur'),
          type: 'number',
          digits: 2,
          sum: true
        },
        //采购金额
        {
          field: 'itemAmt',
          title: self.$t('itemPurAmt'),
          type: 'number',
          digits: 2,
          sum: true
        },
        //包装
        {field: 'packBox',title: self.$t('packBox')},
        //包装单位
        {field: 'box',title: self.$t('box')},
        //基本单位
        {field: 'piece',title: self.$t('piece')},
        //箱片规格
        {field: 'specsName',title: self.$t('boxPiece')},
        //折扣
        {field: 'priceDiscount', title: self.$t('priceDiscount')},
        //非标号
        {field: 'nonStdCode', title: self.$t('nonStandardCode')},
        //入库状态
        {
          field: 'intoStatus',
          title: self.$t('intoStatusName'),
          type: 'text',
        },
        //入库中数量
        {
          field: 'intoingQty',
          title: self.$t('intoingQty'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true
        },
        //入库中金额
        {
          field: 'intoingAmt',
          title: self.$t('intoingAmt'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true
        },
        //入库中包装单位
        {field: 'intoingBox',title: self.$t('intoingBox')},
        //入库中基本单位
        {field: 'intoingPiece',title: self.$t('intoingPiece')},
        //已入库数量
        {
          field: 'intoQty',
          title: self.$t('intoQty'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true
        },
        //已入库金额
        {
          field: 'intoAmt',
          title: self.$t('intoAmt'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true
        },
        //已入库包装单位
        {field: 'intoBox',title: self.$t('intoBox')},
        //已入库基本单位
        {field: 'intoPiece',title: self.$t('intoPiece')},
        //已入库退货数量
        {
          field: 'returnQty',
          title: self.$t('returnIntoQty'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true
        },
        //已入库退货金额
        {
          field: 'returnAmt',
          title: self.$t('returnIntoAmt'),
          type: 'number',
          digits: 0,
          dataType: 'number',
          sum: true
        },
        //备注
        {field: 'remarks'},
      ],
      split: 0.5,// 分区的默认
      choosePurchaseFlag: false,
      chooseTableHeight: 600,
      purList: [],// 选择采购订单
      // 查询条件
      searchCond: {},
      // 选择采购订单弹窗查询条件
      searchContent:
        [
          {
            itemCode: '采购单号-文本',
            itemName: 'purNo',
            valueFormat: {code: 'purNo'},
            valueKind: 'STR'
          },
        ],
      //明细明细分页
      detailPageInfo: {
        total: 0,
        pageSize: this.$config.pageSize,
        currentPage: 1
      },
      modalTitle: '选择采购订单',//选择源单名称
      chooseModal: false,//选择源单model
      purItemId: null,
      addFlag: true ,//商品信息新增
      deleteFlag:true,//商品明细删除标识
      loading: false,
      allCanNoEdit: false, //是否所有的都不允许编辑
      formData: {
        intoId: null,//入库单Id
        fromId: null,//来源单Id
        fromNo: null,//来源单号
        makeStaff: null,//采购人
        intoDate:null,//入库日期
        purId: null,//采购订单Id
        purNo: null,//采购订单号
        supId: null,//供应商Id
        supplierName: null,//供应商
        whId: null,//仓库Id
        whName: null,//仓库
        flgAutoHandle: false,//自动入库标识
        remarks: null,
        annexPaths: null,
        limitEdit:true,//小编辑标识 true不是 false是
      },
      //明细
      purchaseItemList: [],
      goodsColumns: [
        {
          field: 'skuCode',
          controlId: 'skuId',
          treeNode: true,
          type: 'tableSelect',
          // type: 'disabled',
          fixed: 'left',
          promotionType: true,
          dataType: self.$config.tableSelectType.goodsForPurchase,
          tip: self.$t('W_117'),
          fieldUpdate: self.$updateColumns.purchaseEntryColum,
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          controlId: 'skuId',
          type: 'tableSelect',
          fixed: 'left',
          promotionType: true,
          dataType: self.$config.tableSelectType.goodsForPurchase,
          fieldUpdate: self.$updateColumns.purchaseEntryColum,
          searchDetailFlag: true
        },
        // 入库数量
        {
          field: 'itemQty',
          title: self.$t('entryQty'),
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            itemAmt: ['pricePur*itemQty', 'pricePur', 'itemQty'],
            box: ['itemQty/packBox', 'itemQty', 'packBox'],
            piece: ['itemQty%packBox', 'itemQty', 'packBox'],
          },
        },
        // 可入库数量
        {
          field: 'canQty',
          title: self.$t('可入库数量'),
          type: 'disabled',
          digits: 0,
          sum: true,
        },
        //入库单价
        {
          field: 'pricePur',
          type: 'disabled',
          digits: 2,
          flgUserSensitive: true,
          formula: {
            itemAmt: ['pricePur*itemQty', 'pricePur', 'itemQty'],
          },
        },
        //入库金额
        {
          field: 'itemAmt',
          title: self.$t('entryAmt'),
          type: 'number',
          digits: 2,
          sum: true,
        },
        {
          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: 'unitName',
          title: self.$t('piece'),
          type: 'disabled',
        },
        {
          field: 'unitInfo',
          title: self.$t('boxPiece'),
          type: 'nonStandard',
        },
        // //包装
        // {
        //   field: 'packBox',
        //   type: 'disabled',
        // },
        // //箱
        // {
        //   field: 'box',
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     itemQty: ['box*packBox+piece', 'box', 'packBox' ,'piece'],
        //   },
        // },
        // //片
        // {
        //   field: 'piece',
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     itemQty: ['box*packBox+piece', 'piece','box','packBox'],
        //     box: ['(box*packBox+piece)/packBox', 'piece', 'box' , 'packBox','packBox'],
        //     piece: ['(box*packBox+piece)%packBox', 'piece','box', 'packBox', 'packBox'],
        //   },
        // },
        {
          field: 'remarks',
        },
      ],
      warehouseList: [],//仓库
      //商品合计信息
      goodsFootFormData: {
        sumQuantity: 0,
        sumAmount: 0,
        sumStandard: 0,
        saleDiscount: 0,
      },
    }
  },

  methods: {

    /**
     * @desc   : desc
     * @author : 常皓宁
     * @date   : 2024/3/15 15:41
     */
    clearDetail() {
      this.purchaseItemList = null
    },

    /**
    * @desc   : 总单仓库修改明细仓库
    * @author : 常皓宁
    * @date   : 2024/3/19 9:23
    */
    changItemWhId(){
      let itemData = this.$refs['detailTable'].getTableDataFilter();
      let whName = this.warehouseList.filter(it => it.whId  == this.formData.whId)
      if(itemData && itemData.length > 0){
        itemData.forEach(it =>{
          it.whId = this.formData.whId
          it.whId_Name = whName[0].whName
          it.whName = whName[0].whName
        })
        this.$refs['detailTable'].$refs.xTable.reloadData(itemData)
      }
    },

    /**
     * @desc   : 选择采购订单
     * @author : 常皓宁
     * @date   : 2024/3/15 13:02
     */
    choosePurchase() {
      console.log('sss')
      this.chooseModal = true
    },

    /**
     * @desc   : 打开采购订单modal
     * @author : 常皓宁
     * @date   : 2024/3/15 13:06
     */
    openPurchaseModal(e) {
      this.$nextTick(() => {
        if (e) {
          this.modalVisible = true;
        } else {
          this.modalVisible = false;
          // 清空列表和查询条件
          this.$refs['searchCond'].clearCondition()
          // 清空数据源
          this.moldlineList = []
        }
      })
    },

    /**
     * @desc   : 清空选择框
     * @author : 周兴
     * @date   : 2023/2/21 15:34
     */
    modalCancel() {
      this.$refs['searchCond'].clearCondition()
      // 清空数据源
      this.moldlineList = []
    },

    /**
     * @desc   : 选择采购订单确定事件
     * @author : 常皓宁
     * @date   : 2024/3/15 15:23
     */
    modalOk() {
      let batchRows = []
      let itemBatchRows = []
      //包括左侧
      if (this.purList) {
        batchRows = this.$refs['purTable'].batchRows
        itemBatchRows = this.$refs['detail-select'].batchRows
        // 总单
        if (batchRows) {
          this.formData.fromId = batchRows[0].purId
          this.formData.fromNo = batchRows[0].purNo
          this.formData.supId = batchRows[0].supId
          this.formData.supplierName = batchRows[0].supplierName
          this.formData.whId = batchRows[0].whId
          this.formData.whName = batchRows[0].whName
        }
        // 明细
        if (itemBatchRows) {
          itemBatchRows.map(row =>{
            let item = row
            // 仓库
            this.$set(item, 'whId', this.formData.whId)
            this.$set(item, 'whName', this.formData.whName)
            // 可入库数量
            this.$set(item, 'canQty', row['itemQty'] - row['intoQty'] - row['intoingQty'])
            // 不可查询
            this.$set(item, 'readOnly', ['skuCode','skuName'])
            //包装数量
            this.$set(item,'unitInfo',row['specsName'])
          })
          this.purchaseItemList = itemBatchRows
          console.log('this.purchaseItemList',this.purchaseItemList)
          //关闭选择弹框
          this.modalCancel() // 清空选择界面
          this.chooseModal = false
          this.addFlag = false
          // this.goodsColumns[0].type = 'disabled'
        }
      }
    },

    /**
     * @desc   : 行点击事件
     * @author : 常皓宁
     * @date   : 2024/2/28 15:01
     */
    currentChange({row}) {
      if (row != null) {
        this.purId = row.purId
        //查询采购订单明细
        this.getDetail(1)
      }
    },

    /**
     * @desc   : 获取总单id对应明细
     * @author : 常皓宁
     * @date   : 2024/2/28 15:03
     */
    getDetail(currentPage) {
      if (currentPage) {
        this.detailPageInfo.currentPage = currentPage
      }
      let params = {
        purId: this.purId,
        pageSize: this.detailPageInfo.pageSize,
        currentPage: this.detailPageInfo.currentPage
      }
      // 查询数据
      return this.excute(this.$service.purchaseItemService, this.$service.purchaseItemService.selectByCond, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          let tableDataDetail_goodsDetail = res.data.list
          let data = tableDataDetail_goodsDetail.filter(it => it.itemQty - it.intoingQty > 0)
          this.tableDataDetail_goodsDetail = data
          // 全选
          this.$nextTick(()=>{
            this.$refs['detail-select'].checkAll();
          })
          this.$refs['detail-select'].pageInfo.total = res.data.total
        } else {
          this.tableDataDetail_goodsDetail = []
        }
      })
    },

    /**
     * @desc   : 数据校验
     * @author : 常皓宁
     * @date   : 2024/3/2 9:51
     */
    validData() {
      // 明细必须有数据
      let itemTable = this.$refs['detailTable'].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].itemQty || itemTable[i].itemQty === '') {
          this.$message.warning(this.$t('W_041', {'param': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('itemQty')}))
          return false;
        }
        if (!itemTable[i].pricePur || itemTable[i].pricePur === '') {
          this.$message.warning(this.$t('W_041', {'param': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('pricePur')}))
          return false;
        }
        if (itemTable[i].canQty && (itemTable[i].itemQty > itemTable[i].canQty)) {
          this.$message.warning(this.$t('W_008', {'param1': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('entryQty'),'param2':this.$t('可入库数量')}))
          return false;
        }
      }
      return true
    },

    /**
     *   @desc   : 清空参数
     *   @date   : 2022/12/20 15:33
     *   @author : 常皓宁
     */
    clear() {
      this.formData = {
        fromId: null,//来源单Id
        fromNo: null,//来源单号
        intoDate: null,//入库日期
        purId: null,
        purNo: null,
        supId: null,
        supName: null,
        whId: null,
        whName: null,
        remarks: null,
        annexPaths: null,
        flgAutoHandle: false,//自动入库标识
      },
        this.purchaseItemList = []
    },

    /**
     * @desc   : 修改包装数
     * @author : 周兴
     * @date   : 2024/5/24 15:02
     */
    changeNonStandard({row,rowIndex,field}){
      let table = this.$refs['detailTable'].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]['itemQty'] = row['packBox'] * (row['nonStandardForm']['box']?row['nonStandardForm']['box']:0) + (row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0)
      table[rowIndex]['itemAmt'] = table[rowIndex]['itemQty'] * table[rowIndex]['pricePur']
      table[rowIndex]['box'] = row['nonStandardForm']['box']?row['nonStandardForm']['box']:0
      table[rowIndex]['piece'] = row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0
      this.getTotale(table)
    },

    /**
    * @desc   : 行改变事件
    * @author : 常皓宁
    * @date   : 2024/3/19 10:51
    */
    changeValue(field, row, rowIndex) {
      if(field && (field == 'skuCode' || field == 'skuName')){
        this.choosePurchaseFlag = true
        this.addFlag = true
      }else {
        // let sum = 0
        // sum = parseFloat(row['pricePur'] * row[field]).toFixed(2)
        // this.$set(row, 'itemAmt', sum);
        //选择数据带出默认仓库
        if (!row.whId || row.whId === 0 || row.whId === null) {
          this.$set(row, 'whId', this.whId);
          this.$set(row, 'whId_Name', this.whName);
        }
      }
      let table = this.$refs['detailTable'].tableData
      console.log('table', table)
      if (table && table.length > 0) {
        //计算合计
        this.getTotale(table)
        table.forEach(row => {
          if (!row["itemQty"] || row["itemQty"] == '') {
            this.$set(row, 'itemQty', 0);
          }
          if (!row["itemAmt"] || row["itemQty"] == '') {
            this.$set(row, 'itemAmt', 0);
          }

          this.decimalPlaces = row['decimalPlaces']

          if (row['subUnitId']) {
            row.nonStandardForm = {
              formula: (row['subUnitName'] ? '1' + row['subUnitName'] + '=' : '') + row['packBox'] + row['unitName'],
              box: (row['itemQty'] / row['packBox'] >= 1 ? Math.floor(row['itemQty'] / row['packBox']) : 0),
              piece: row['itemQty'] % 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['itemQty'] / row['packBox'] >= 1 ? Math.floor(row['itemQty'] / row['packBox']) : 0) + row['subUnitName'] + (row['itemQty'] % row['packBox']).toFixed(this.decimalPlaces) + row['unitName']
          } else {
            row.nonStandardForm = {
              formula: (row['subUnitName'] ? '1' + row['subUnitName'] + '=' : '') + row['packBox'] + row['unitName'],
              piece: row['itemQty'],
            }
            row.nonStandardItems = [
              {code: 'formula', label: '计算公式', type: 'text', readonly: true},
              {code: 'piece', label: row['unitName'], type: 'number', digits: this.decimalPlaces}
            ]
            row['unitInfo'] = row['itemQty'] + 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;    // 货物金额
      let sumStandard = 0;  // 标价总额
      if (table && table.length > 0) {
        table.forEach(row => {
          sumQuantity += parseFloat(row["itemQty"]);
          sumAmount += parseFloat(row["itemAmt"])
          this.$set(row, 'amtStd', parseFloat(row["itemQty"]) * parseFloat(row["priceStd"]));
          sumStandard += parseFloat(row["amtStd"]);
        })
      }
      this.goodsFootFormData.sumQuantity = sumQuantity;
      this.goodsFootFormData.sumAmount = sumAmount;
      this.goodsFootFormData.sumStandard = sumStandard;
      this.goodsFootFormData.saleDiscount = (sumAmount / sumStandard * 100).toFixed(2);
    },

    /**
     * @desc   : 自动入库标识变更
     * @author : 夏常明
     * @date   : 2023/9/1 16:34
     */
    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   : 给参数赋值
     * @author : 常皓宁
     * @date   : 2024/2/28 13:41
     */
    setParams() {
      this.params = {...this.formData}
      // 部门
      this.params.orgId = this.$store.state.user.orgId
      // 员工
      this.params.staffId = this.$store.state.user.staffId
      // 制单员
      this.params.makeStaff = this.$store.state.user.staffId
      // 公司
      this.params.cpId = this.$store.state.user.cpId

      //入库时间
      if(this.formData.intoDate){
        this.formData.intoDate  = new Date(this.formData.intoDate).format('yyyy-MM-dd')
      }

      //附件
      if (this.formData.annexPaths && this.formData.annexPaths.length > 0) {
        this.params.annexPaths = this.formData.annexPaths.map(m => {
          return {
            name: m.name,
            url: m.path,
            type: m.type,
            createTime: m.createTime
          }
        })
      }

      // 新建
      if (this.type === this.$config.formMode.add) {
        let tableFilter = this.$refs['detailTable'].getTableDataFilter();
        let insertTale = this.countItem(tableFilter)
        // 采购入库明细
        this.params.itemList = insertTale
        // 入库中数量
        this.params.intoingQty = insertTale.sum('itemQty')
        // 入库中金额
        this.params.intoingAmt = insertTale.sum('itemAmt')
      }
      // 入库办理
      if (this.type === this.$config.formMode.handle) {
        let tableFilter = this.$refs['detailTable'].getTableDataFilter();
        // 采购入库明细
        this.params.itemList = tableFilter
      }
    },

    /**
     * @desc   : 计算明细数据
     * @author : 常皓宁
     * @date   : 2024/3/2 13:33
     */
    countItem(table) {
      let itemTable = table
      itemTable.map(row => {
        let item = row
        // 采购价（入库价）
        this.$set(item, 'priceInto', row['pricePur'])
        // 出库数量
        this.$set(item, 'outQty', 0)
        // 来源单Id
        this.$set(item, 'fromId', row['purId'])
        // 来源单明细Id
        this.$set(item, 'fromItemId', row['itemId'])
        // 待入库数量
        this.$set(item, 'intoingQty', row['itemQty'])
        // 待入库金额
        this.$set(item, 'intoingAmt', row['itemAmt'])
        //是否自动办理入库
        if(this.formData.flgAutoHandle){
          // 箱（已入库）
          this.$set(item, 'intoBox', row['box'])
          // 片（已入库）
          this.$set(item, 'intoPiece', row['piece'])
          // 箱（入库中）
          this.$set(item, 'intoingBox', 0)
          // 片（入库中）
          this.$set(item, 'intoingPiece',0)
        }else{
          // 箱（已入库）
          this.$set(item, 'intoBox', 0)
          // 片（已入库）
          this.$set(item, 'intoPiece', 0)
          // 箱（入库中）
          this.$set(item, 'intoingBox', row['box'])
          // 片（入库中）
          this.$set(item, 'intoingPiece', row['piece'])
        }
        // 去掉采购订单明细Id
        delete row['itemId']
        return item
      })


      let itemIndex = 1
      itemTable.forEach(it => {
        this.$set(it, 'itemIndex', itemIndex)
        itemIndex++
      })
      return itemTable
    },

    /**
     * @desc   : 提交事件
     * @author : 付斌
     * @date   : 2024-02-19 10:47
     */
    saveData() {
      console.log('this.params', this.params)
      // this.loading = false
      // 新建
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.purEnterService, this.$service.purEnterService.purchaseInboundInsert, this.params)
      }
      //编辑
      if(this.type === this.$config.formMode.edit){
        return this.excute(this.$service.purEnterService, this.$service.purEnterService.purchaseInboundUpdate, this.params)
      }
      //入库办理
      else if(this.type === this.$config.formMode.handle) {
        return this.excute(this.$service.purEnterService, this.$service.purEnterService.purchaseHandleInbound, this.params)
      }
    },
    /***************************列表及其他事件************************************/

    /***************************设定参数函数************************************/

    /***************************created调用数据接口函数************************************/

    /**
     * @desc   : 获取采购订单数据
     * @author : 常皓宁
     * @date   : 2024/3/15 13:08
     */
    getDataTable() {
      let param = {}
      param.purId = this.purFromId
      param.cpId = this.$store.state.user.cpId
      param.intoStatusList = [this.$config.intoStatus.daiRuKu,this.$config.intoStatus.ruKuZhong]
      param = Object.assign(param, this.searchCond._value)
      this.loading = true;
      this.excute(this.$service.purOrderService, this.$service.purOrderService.selectByCond, param).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.purList = res.data.list
        } else {
          this.$Message.warning(res.message)
          this.purList = []
          this.tableDataDetail_goodsDetail = []
        }
        this.loading = false;
      })
    },

    /**
     * @desc   : 通过id查询
     * @author : 常皓宁
     * @date   : 2024/2/29 8:49
     */
    detail(id) {
      return this.excuteNoParam(this.$service.purEnterService, this.$service.purEnterService.selectByUpdate, [id])
    },

    /**
     * @desc   : 编辑页面赋值
     * @author : 常皓宁
     * @date   : 2024/2/29 9:49
     */
    setValuesByEdit(data) {
      console.log('data',data)
      this.purFromId = data.data.fromId
      this.formData.intoId = data.data.intoId
      this.formData.fromId = data.data.fromId
      this.formData.fromNo = data.data.fromNo
      this.formData.supId = data.data.supId
      this.formData.supplierName = data.data.supplierName
      this.formData.whId = data.data.whId
      this.formData.whName = data.data.whName
      this.formData.remarks = data.data.remarks
      this.formData.annexPaths = data.data.annexPaths
      this.formData.intoDate = new Date().format("yyyy-MM-dd")
      let dataItem = data.dataItem
      dataItem.map(row => {
        let item = row
        // 采购价（入库价）
        this.$set(item, 'pricePur', row['priceInto'])
        // 入库金额
        this.$set(item, 'itemAmt', row['intoingAmt'])
        // 不可查询
        this.$set(item, 'readOnly', ['skuCode','skuName'])
        if(row.intoStatus == this.$config.intoStatus.ruKuZhong){
          //包装规格
          this.$set(item, 'unitInfo', row['ingBoxPiece'])
          // 入库数量
          this.$set(item, 'itemQty', row['intoingQty'])
          // 可入库数量
          this.$set(item, 'canQty', row['intoingQty'] - row['intoQty'])
          // 箱
          this.$set(item, 'box', row['intoingBox'])
          // 片
          this.$set(item, 'piece', row['intoingPiece'])

          this.goodsFootFormData.sumQuantity = data.data.intoingQty;
          this.goodsFootFormData.sumAmount = data.data.intoingAmt;
        } else {
          //包装规格
          this.$set(item, 'unitInfo', row['boxPiece'])
          // 入库数量
          this.$set(item, 'itemQty', row['intoQty'])
          // 可入库数量
          this.$set(item, 'canQty', row['intoQty'])
          // 箱（已入库）
          this.$set(item, 'box', row['intoBox'])
          // 片（已入库）
          this.$set(item, 'piece', row['intoPiece'])

          this.goodsFootFormData.sumQuantity = data.data.intoQty;
          this.goodsFootFormData.sumAmount = data.data.intoAmt;
        }
        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.purchaseItemList = dataItem
      //大编辑标识
      if(this.type === this.$config.formMode.edit){
        //系统自动办理入库
        if(this.$store.state.user.setting[this.$config.settingCode.IVT001] == 1){
          //已入库未收款可以大编辑
          if(data.data.paymentFlag){
            this.formData.limitEdit= false
            this.$refs.detailTable.enabledEdit = false
          }else{
            this.formData.limitEdit= true
            this.$refs.detailTable.enabledEdit = true
          }
        }
        //手动办理入库
        else{
          //已入库能小编辑
          if(data.data.intoStatus == this.$config.intoStatus.yiRuKu){
            this.formData.limitEdit= false
            this.$refs.detailTable.enabledEdit = false
            this.addFlag = false
            this.deleteFlag = false
          }else{
            this.formData.limitEdit= true
            this.$refs.detailTable.enabledEdit = true
          }
        }
      }
      //办理
      else if(this.type === this.$config.formMode.handle){
        this.deleteFlag = false;
        this.addFlag = false;
      }
    },


    /**
     * @desc   : 获取仓库
     * @author : 常皓宁
     * @date   : 2024/2/28 14:39
     */
    getWareHouseList() {
      let params = {
        cpId: this.$store.state.user.cpId
      }
      this.excute(this.$service.commonService, this.$service.commonService.getWarehouse, params, false).then(res => {//调用api查询方法
        if (res.code === this.$config.SUCCESS_CODE) {
          this.warehouseList = res.data
          //赋值默认仓库 组件需要
          let newList = res.data.filter(it => it.flgDefault)
          console.log('newList',newList)
          this.whId = newList[0].whId
          this.whName = newList[0].whName
        }
      })
    },

    /**
     * @desc   : 加载数据
     * @author : 常皓宁
     * @date   : 2024/2/28 14:37
     */
    initData() {
      this.getWareHouseList();   // 获取仓库数据
    },
  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 寇珊珊
   * @date   : 2022/3/3 10:32
   */
  created() {
    this.resizeTableFlag = true;  // 计算表格高度
    //设置默认值
    if (this.$route.params.id){
      // 入库办理
      if (this.type === this.$config.formMode.handle) {
        this.showAutoFlag = false;
        this.choosePurchaseFlag = true;
        this.showIntoDate = true;
      }
    }
  },

  activated() {
    console.log('this.$route.query',this.$route)
    if (this.$route.params.row && this.$route.params.row.purId) {
      this.purFromId = this.$route.params.row.purId
      this.choosePurchase()
    }
  },
}
</script>


<style scoped>


/deep/ .ivu-modal-body {
  background: #EAEDF7 !important;
}

</style>
