<!-- @desc:采购订单新建编辑  @auth:付斌 @time:2024/02/20 15:15 -->
<template>
  <div class="main-div" style="position: relative;">
    <!--按钮区-->
    <BaseIndexButtonGroup ref="BaseIndexButtonGroup1" id="BaseIndexButtonGroup1">
      <template #left>
        <BaseIndexButton ref="purchaseBasedOnSales" name="purchaseBasedOnSales"
                         @click="purchaseBasedOnSales"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>

    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData"
                style="width:100%" :label-max-words="5">
          <!--来源单号-->
          <DkFormItem prop="fromNo" :label="$t('fromNo')">
            <InputPop ref="fromNo" v-model="formData.fromNos" :readonly="true"/>
          </DkFormItem>
          <!--采购单号-->
          <DkFormItem prop="purNo" :label="$t('purNo')">
            <InputPop ref="purNo" v-model="formData.purNo" :readonly="true"/>
          </DkFormItem>
          <!--供应商-->
          <DkFormItem prop="supId" :label="$t('supplierName')" :required="true">
            <SelectMagnifier v-model="formData.supId" :display-text="formData.supplierName"
                             :type="this.$config.MagnifierType.supplier"
                             :multiple="false"
                             :otherCondition="{supplierType:this.$config.kindCode.supplierPur}"
                             @ok="supplierOk"/>
          </DkFormItem>
          <!--收货时间-->
          <DkFormItem :label="$t('DeliveryDate')"
                      prop="pickupDate" :required="true" :data-type="$config.dataType.date">
            <DatePickerPop v-model="formData.pickupDate"
                           :placeholder="$t('inputWords',{'search-name':$t('DeliveryDate')})"
                           type="date" :short-cut-flag="true"/>
          </DkFormItem>
          <!--收货仓库-->
          <DkFormItem prop="whId" :label="$t('wareHouse')" :required="true">
            <SelectPop v-model="formData.whId" ref="whId"
                       :options="warehouseList"
                       :multiple="false"
                       labelKey="whName" valueKey="whId">
            </SelectPop>
          </DkFormItem>
          <!--收货人-->
          <DkFormItem prop="contactName" :label="$t('contactName')">
            <InputPop ref="contactName" :readonly="true" v-model="formData.contactName"/>
          </DkFormItem>
          <!--收货电话-->
          <DkFormItem prop="contactPhone" :label="$t('contactPhone')">
            <InputPop :telephone="true" ref="contactPhone" :readonly="true" v-model="formData.contactPhone"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks">
            <InputPop ref="remarks" v-model="formData.remarks"
                      maxlength=500 textareaFlag/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--商品信息-->
      <DkPanel prop="goodsInformation">
        <div id="search-cond-div-goods-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable slot="left"
                     ref="detailTable"
                     majorField="itemId"
                     :data="purchaseItemList"
                     :columns="goodsColumns"
                     :height="400"
                     :freeze="false"
                     :show-footer="true"
                     :canDelete="canDeleteLeft"
                     :add-flag="this.chooseFlag"
                     controlId="skuId"
                     @on-choose="getTotals"
                     @changeValue="getTotals"
                     @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.purchase" :accept="$config.uploadFileConfig.acceptPicType"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>

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

    <!--以销定采-->
    <DkModal
      :loading="loading"
      v-model="purchaseBasedOnSalesFlag"
      :title="$t('purchaseBasedOnSales')"
      width="1000px"
      @modalOk="purchaseBasedOnSalesOk"
      @modalCancel="clearPurchaseBasedOnSales"
    >
      <card :padding=0 style="margin-top: 1px;padding: 0">
        <!--按钮区-->
        <BaseIndexButtonGroup ref="BaseIndexButtonGroup" id="BaseIndexButtonGroup">
          <template #left>
            <BaseIndexButton ref="purchaseBasedOnSales" name="purchaseBasedOnSales"
                             @click="purchaseBasedOnSales(true)"></BaseIndexButton>
            <BaseIndexButton ref="clearPurchaseBasedOnSales" name="clearPurchaseBasedOnSales"
                             @click="clearPurchaseBasedOnSales(true)"></BaseIndexButton>
          </template>
        </BaseIndexButtonGroup>
        <!-- 查询条件-->
        <DkForm ref="purchaseBasedOnSalesFormData" v-model="purchaseBasedOnSalesFormData"
                name="purchase-based-on-sales-form"
                class="form-content-class" style="margin-top: 5px">
          <!--订单单号-->
          <DkFormItem prop="orderNo" :label="$t('orderNo')">
            <InputPop ref="orderNo" v-model="purchaseBasedOnSalesFormData.orderNo"/>
          </DkFormItem>
        </DkForm>
        <DkTable primaryKey="itemId"
                 ref="table-purchase-based-on-sales-select"
                 :id="'table-'+$options.name"
                 name="table"
                 :data="purchaseBasedOnSalesTableData"
                 :height="purchaseBasedOnSalesHeight"
                 :lazy="false"
                 :selectFlag="false"
                 :operateFlag="false"
                 :link-click-checked="true"
                 @pageChange="purchaseBasedOnSalePageSizeChange">
          <DkTableColumn v-for="(item,index) in purchaseBasedOnSalesColumns" :key="index" :field="item.field"
                         :title="item.title"
                         :width="item.width"
                         :filter="false"
                         :resize-flag="index === purchaseBasedOnSalesColumns.length - 1"></DkTableColumn>
        </DkTable>
      </card>
    </DkModal>
  </div>
</template>

<script>

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

export default {
  components: {},
  mixins: [formMixin],
  data() {
    let self = this
    return {
      //小数位数
      decimalPlaces:0,
      chooseFlag: true ,//商品信息新增
      procureList: [],//每次以销定采选择后存放数据
      //以销定采
      purchaseBasedOnSalesFlag: false,
      purchaseBasedOnSalesTableData: [],
      purchaseBasedOnSalesHeight: 400,
      purchaseBasedOnSalesColumns: [
        {field: 'orderNo', width: '200px'},
        {
          field: 'transferableQuantity',
          title:'可转采购数量',
          type: 'number',
          digits: 0,
          sum: true
        },//可转采购数量
        {field: 'skuModel'},//商品型号
        {field: 'skuName'},//商品名称
        {field: 'skuCode'},//商品编码
        // {field: 'makingTime'},//订单日期
        // {field: 'entryTime'},//预计送货日期
        // {field: 'outStatusStringDetail'},//单据状态
        // {field: 'customerName'},//客户名称
        // {field: 'customerPhone'},//客户电话
        // {field: 'addressFull'},//客户地址
        // {field: 'orgName'},//业务部门
        // {field: 'staffName'},//业务员
        // {field: 'priceSale'},//销售单价
        // {field: 'itemAmount'},//销售金额
        // {field: 'warehouseName'},//仓库
        // {field: 'brandName'},//商品品牌
        // {field: 'nonStandardCode'},//非标号
        // {field: 'skuWeight', type: 'number', digits: 2, sum: true},//重量
        // {field: 'skuVolume', type: 'number', digits: 2, sum: true},//体积
        // {field: 'remarks'},//备注
      ],
      orderId: null,
      //连接业务接口
      purchaseBasedOnSalesFormData: {
        orderNo: null,//订单单号
        deliveryTime: null,//送货日期
        customerName: null,//客户名称
        customerPhone: null,//客户电话
        addressFull: null,//详细地址
        orgId: null,//业务部门
        orgName: null,//业务名称
        skuModel: null,//商品型号
        skuCode: null,//商品名称
        skuName: null,//商品编码
      },
      loading: false,
      allCanNoEdit: false, //是否所有的都不允许编辑
      formData: {
        purId: null,
        purNo: null,
        supId: null,
        supName:null,
        whId:null,
        whName:null,
        pickupDate: new Date().addDays(1),
        contactName: null,
        contactPhone: null,
        fromIds:null,
        fromNos:null,
        remarks: null,
        annexPaths:null,
      },
      //明细
      purchaseItemList: [],
      goodsColumns: [
        {
          field: 'skuCode',
          controlId: 'skuId',
          treeNode: true,
          type: 'tableSelect',
          fixed: 'left',
          promotionType: true,
          dataType: self.$config.tableSelectType.goodsForPurchase,
          tip: self.$t('W_117'),
          fieldUpdate:self.$updateColumns.purchaseColum,
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          controlId: 'skuId',
          type: 'tableSelect',
          fixed: 'left',
          promotionType: true,
          dataType: self.$config.tableSelectType.goodsForPurchase,
          fieldUpdate: self.$updateColumns.purchaseColum,
          searchDetailFlag: true
        },
        {
          field: 'itemQty',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            box: ['itemQty/packBox', 'itemQty', 'packBox'],
            piece: ['itemQty%packBox', 'itemQty', 'packBox'],
          }
        },//数量
        {
          field: 'pricePur',
          type: 'number',
          digits: 2,
        },//采购价
        {
          field: 'pricePurchase',
          type: 'disabled',
          digits: 2,
          number: true,
          sum: true
        },//采购标价
        {
          field: 'ingIntoQty',
          title: self.$t('已转入库数量'),
          type: 'disabled',
          digits: 2,
          number: true,
          sum: true
        },//可转入库数量
        {
          field: 'intoStatusName',
          type: 'disabled',
        },//入库状态
        //基本单位
        {
          field: 'unitName',
          title: self.$t('piece'),
          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: 'unitInfo',
          title: self.$t('boxPiece'),
          type: 'nonStandard',
        },
        {
          field: 'remarks',
        },
      ],
      warehouseList: [],//仓库
      //商品合计信息
      goodsFootFormData: {
        sumQuantity: 0,
        sumAmount: 0,
        sumStandard: 0,
      },
    }
  },

  methods: {
    /**
     * @desc   : 分页
     * @author : 付斌
     * @date   : 2024-02-19 10:44
     */
    purchaseBasedOnSalePageSizeChange(pageInfo) {
    },

    /**
     * @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]['priceSale']
      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   : 2022/5/30 15:31
     *   @author : 付斌
     */
    getTotals(field, row, rowIndex) {
      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']

          // if (!row["whId"] || row["whId"] == '') {
          //   this.$set(row, 'whId', this.defaultWh.whId);
          //   this.$set(row, 'whName', this.defaultWh.whName);
          // }
        })
      }
    },


    /**
     * @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"])
          sumStandard += parseFloat(row["pricePurchase"]) * parseFloat(row["itemQty"]);
        })
      }
      this.goodsFootFormData.sumQuantity = sumQuantity;
      this.goodsFootFormData.sumAmount = sumAmount;
      this.goodsFootFormData.sumStandard = sumStandard;
      this.goodsFootFormData.saleDiscount = (sumAmount / sumStandard * 100).toFixed(2);
    },

    /**
     * @desc   : 以销定采弹窗打开并查询数据
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    purchaseBasedOnSales(modalOpenFlag) {
      this.purchaseBasedOnSalesFlag = true
      let param = {
        'cpId': this.$store.state.user.cpId,
        //订单单号
        orderNo: this.purchaseBasedOnSalesFormData.orderNo,
      }
      this.loading = true;
      this.excute(this.$service.orderItemService, this.$service.orderItemService.purchaseBasedOnSaleSelectOrder, param).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.purchaseBasedOnSalesTableData = res.data.list
        } else {
          this.$Message.warning(res.message)
          this.purchaseBasedOnSalesTableData = []
        }
        this.loading = false;
      })
    },
    /**
     * @desc   : 以销定采选择商品确认带回方法
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    purchaseBasedOnSalesOk() {
      this.purchaseBasedOnSalesFlag = false
      let arr = this.$refs['table-purchase-based-on-sales-select'].batchRows
      //本次选择的数据
      if(arr){
        arr.map(row =>{
          let item = row
          //采购数量
          this.$set(item, 'itemQty', row['transferableQuantity'])
          //采购价
          this.$set(item, 'pricePur', row['priceStd'])
          //采购标价
          this.$set(item, 'pricePurchase', row['priceStd'])
          //销售订单ID
          this.$set(item, 'fromId', row['orderId'])
          //销售订单明细ID
          this.$set(item, 'fromItemId', row['itemId'])
          // 不可查询
          this.$set(item, 'readOnly', ['skuCode','skuName'])
          // 去掉销售订单明细Id
          delete row['itemId']
        })
        this.purchaseItemList = arr

        //不重复Id集合
        let ids = []
        //不重复数据集合
        let fromNos = []
        let fromIds = []
        for (let i = 0; i < arr.length; i++) {
          if (ids.indexOf(arr[i].orderId) == -1) {
            ids.push(arr[i].orderId)
            fromNos.push(JSON.parse(JSON.stringify(arr[i]['orderNo'])))
            fromIds.push(JSON.parse(JSON.stringify(arr[i]['orderId'])))
          }
        }
        this.formData.fromNos = fromNos
        this.formData.fromIds = fromIds
        this.chooseFlag = false
      }
    },

    /**
    * @desc   : 合并以销定采数量
    * @author : 常皓宁
    * @date   : 2024/3/29 8:56
    */
    mergeProcureQuantity(list) {
      //不重复Id集合
      let ids = []
      //不重复数据集合
      let arr = []
      for (let i = 0; i < list.length; i++) {
        if (ids.indexOf(list[i].skuId) == -1) {
          ids.push(list[i].skuId)
          arr.push(JSON.parse(JSON.stringify(list[i])))
        }
      }
      //把重复的数据中的可转采购数量相加
      for (let index in arr) {
        let orderS2tobuyVOList = []
        arr[index].transferableQuantity = list.filter(it => it.skuId == arr[index].skuId).sum('transferableQuantity')
        arr[index].itemQuantity = arr[index].transferableQuantity
        arr[index].transferableFlag = true
        for (let item = 0; item < list.length; item++) {
          if (list[item].skuId == arr[index].skuId) {
            let json = {}
            json.s2orderNo = list[item].orderNo
            json.s2orderId = list[item].orderId
            json.s2orderItemId = list[item].itemId
            json.buyQuantity = list[item].transferableQuantity
            orderS2tobuyVOList.push(json)
          }
        }
        arr[index].orderS2tobuyVOList = orderS2tobuyVOList
      }
      return arr
    },

    /**
     * @desc   : 关闭弹窗
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    clearPurchaseBasedOnSales() {
      this.$refs.purchaseBasedOnSalesFormData.$refs['purchase-based-on-sales-form'].resetFields();
    },

    /**
     * @desc   : 供应商选择后事件
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    supplierOk(val) {
      this.formData.contactName = val[0]['contactName']
      this.formData.contactPhone = val[0]['contactPhone']
    },


    /**
    * @desc   : 数据校验
    * @author : 常皓宁
    * @date   : 2024/3/2 9:51
    */
    validData() {
      // 明细必须有数据
      if (!this.$refs.detailTable.tableData.filter(f => f.skuId).length) {
        this.$Message.warning(this.$t('W_012'))
        return false
      }
      // 商品数量不能为空
      if (this.$refs.detailTable.tableData.some(s => !s.itemQty)) {
        this.$Message.warning(this.$t('W_001', {param: this.$t('itemQty')}))
        return false
      }
      // 采购价不能为空
      if (this.$refs.detailTable.tableData.some(s => !s.pricePur)) {
        this.$Message.warning(this.$t('W_001', {param: this.$t('pricePur')}))
        return false
      }
      // 明细必须有数据
      let itemTable = this.$refs['detailTable'].getTableDataFilter();
      for (let i = 0; i < itemTable.length; i++) {
        // 编辑时 商品数量不能小于已转入库数量
        if (itemTable[i].itemQty < itemTable[i].ingIntoQty) {
          this.$message.warning(this.$t('W_009', {'param1': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('itemQty'),'param2':this.$t('已转入库数量')}))
          return false;
        }
      }
      return true
    },

    /**
     *   @desc   : 清空参数
     *   @date   : 2022/12/20 15:33
     *   @author : 常皓宁
     */
    clear() {
      this.formData = {
        purNo: null,
        supId: null,
        supName:null,
        pickupDate: null,
        contactName: null,
        contactPhone: null,
        remarks: null,
      }
      this.purchaseItemList = []
    },

    /**
     * @desc   : 给参数赋值
     * @author : 常皓宁
     * @date   : 2024/2/28 13:41
     */
    setParams() {
      this.params = {...this.formData}
      // 取货日期
      if (this.formData.pickupDate) {
        this.params.pickupDate = this.formData.pickupDate.format('yyyy-MM-dd')
      }
      // 部门
      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.type === this.$config.formMode.add) {
        let tableFilter = this.$refs['detailTable'].getTableDataFilter();
        let insertTale = this.countItem(tableFilter)
        // 采购订单明细
        this.params.purchaseItemVOList = insertTale
        // 商品总数量
        this.params.sumQuantity = insertTale.sum('itemQty')
        // 标价合计
        this.params.sumStandard = insertTale.sum('sumStandard').toFixed(2)
        // 合计金额
        this.params.sumAmount = insertTale.sum('sumAmount').toFixed(2)
        // 采购折扣
        this.params.purDiscount = (parseFloat(insertTale.sum('sumAmount').toFixed(2) )/ parseFloat(insertTale.sum('sumStandard').toFixed(2)) * 100).toFixed(2)
        // 应付金额
        this.params.amtPayable = this.params.sumAmount
        // 还款金额
        this.params.amtHandle = 0
        // 剩余应付
        this.params.amtResidue = parseFloat(this.params.amtPayable - this.params.amtHandle)
      }
      else if (this.type === this.$config.formMode.edit){
        // 修改的表数据 和 新增的表数据
        // let changeTable = this.$refs.detailTable.getTableChangeData();
        // console.log('changeTable',changeTable)
        let tableData = this.$refs.detailTable.getTableData()
        console.log('tableData',tableData)
        let editTable = this.countItem(tableData)
        this.params.editPurchaseItemList = editTable
        // 商品总数量
        this.params.sumQuantity = editTable.sum('itemQty')
        // 标价合计
        this.params.sumStandard = editTable.sum('sumStandard').toFixed(2)
        // 合计金额
        this.params.sumAmount = editTable.sum('sumAmount').toFixed(2)
        // 采购折扣
        this.params.purDiscount = (parseFloat(editTable.sum('sumAmount').toFixed(2) )/ parseFloat(editTable.sum('sumStandard').toFixed(2)) * 100).toFixed(2)
        // 应付金额
        this.params.amtPayable = this.params.sumAmount
        // 还款金额
        this.params.amtHandle = 0
        // 剩余应付
        this.params.amtResidue = parseFloat(this.params.amtPayable - this.params.amtHandle)

        // 删除的表数据
        let deleteTable =  this.$refs['detailTable'].getDeleteData();
        this.params.deletePurchaseItemList = deleteTable

      }

    },

    /**
    * @desc   : 计算明细数据
    * @author : 常皓宁
    * @date   : 2024/3/2 13:33
    */
    countItem(table){
      let itemTable = table
      itemTable.map(row => {
        let item = row
        // 标价合计 = 商品数量 * 采购标价
        let sumStandard = parseFloat(row['itemQty']) * parseFloat(row['pricePurchase'])
        // 合计金额 = 商品数量 * 采购价
        let sumAmount = parseFloat(row['itemQty']) * parseFloat(row['pricePur']);
        // 折扣
        let priceDiscount =  (parseFloat(row['pricePur']) / parseFloat(row['pricePurchase']) * 100).toFixed(2);
        this.$set(item, 'sumStandard', sumStandard)
        this.$set(item, 'sumAmount', sumAmount)
        // 标价
        this.$set(item, 'priceStd', row['pricePurchase'])
        // 标价金额 = 商品数量 * 标价
        this.$set(item, 'amtStd', sumStandard)
        // 采购价
        this.$set(item, 'pricePur', row['pricePur'])
        // 采购金额 = 商品数量 * 采购价
        this.$set(item, 'itemAmt', sumAmount)
        // 折扣
        this.$set(item, 'priceDiscount', priceDiscount)
        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)
      return this.type === this.$config.formMode.add ?
        this.excute(this.$service.purOrderService, this.$service.purOrderService.insert, this.params)
        : this.excute(this.$service.purOrderService, this.$service.purOrderService.update, this.params)
    },
    /***************************列表及其他事件************************************/

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

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

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

    /**
    * @desc   : 删除按钮不显示
    * @author : 常皓宁
    * @date   : 2024/3/26 10:24
    */
    canDeleteLeft (row) {
      return row['intoStatus'] && row['intoStatus'] == this.$config.intoStatus.daiRuKu
    },
    /**
     * @desc   : 编辑页面赋值
     * @author : 常皓宁
     * @date   : 2024/2/29 9:49
     */
    setValuesByEdit(data) {
      this.formData.purId = data.purId
      this.formData.purNo = data.purNo
      this.formData.supId = data.supId
      this.formData.supplierName = data.supplierName
      this.formData.whId = data.whId
      this.formData.whName = data.whName
      this.formData.pickupDate = data.pickupDate
      this.formData.contactName = data.contactName
      this.formData.contactPhone = data.contactPhone
      this.formData.remarks = data.remarks
      this.formData.fromIds = data.fromIds
      this.formData.fromNos = data.fromNos
      this.formData.annexPaths = data.annexPaths

      this.goodsFootFormData.sumQuantity = data.sumQuantity;
      this.goodsFootFormData.sumAmount = data.sumAmount;
      this.goodsFootFormData.sumStandard = data.sumStandard;

      let purchaseItemResponseList = data.purchaseItemResponseList
      purchaseItemResponseList.map(row =>{
        let item = row
        //可转入库数量
        this.$set(item, 'ingIntoQty', row['intoQty'] + row['intoingQty'])
        //包装规格
        this.$set(item, 'unitInfo', row['specsName'])
        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'}
          ]
        }
        console.log('row',row)
        if(row['intoStatus'] != this.$config.intoStatus.daiRuKu){
          // 不可查询
          this.$set(item, 'readOnly', ['skuCode','skuName'])
        }
      })
      this.purchaseItemList = purchaseItemResponseList
    },


    /**
     * @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 warehouseList = this.warehouseList
          warehouseList.forEach(it =>{
            if(it.flgDefault){
              this.formData.whName = it.whName
              this.formData.whId= it.whId
            }
          })
        }
      })
    },

    /**
     * @desc   : 加载数据
     * @author : 常皓宁
     * @date   : 2024/2/28 14:37
     */
    initData() {
      if (this.type === this.$config.formMode.add || this.type === this.$config.formMode.edit) {
        this.getWareHouseList();   // 获取仓库数据
      }
    },
  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 寇珊珊
   * @date   : 2022/3/3 10:32
   */
  created() {
    console.log('ttt',this.$route)
    this.resizeTableFlag = true;  // 计算表格高度
    if(this.type === this.$config.formMode.add){
      this.goodsColumns = this.goodsColumns.filter(it=> it.field != 'ingIntoQty')
      this.goodsColumns = this.goodsColumns.filter(it=> it.field != 'intoStatusName')
    }
  },
}
</script>
