<!-- @desc:采购订单新建编辑  @auth:付斌 @time:2024/02/20 15:15 -->
<template>
  <div class="main-div" style="position: relative;">
    <!--按钮区-->
    <BaseIndexButtonGroup ref="BaseIndexButtonGroup1" id="BaseIndexButtonGroup1">
      <template #right>
        <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="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:'采购供应商'}"
                             @ok="supplierOk"/>
          </DkFormItem>
          <!--收货时间-->
          <DkFormItem :label="$t('收货日期')"
                      prop="pickupDate" :required="true" :data-type="$config.dataType.date">
            <DatePickerPop v-model="formData.pickupDate"
                           :placeholder="$t('inputWords',{'search-name':$t('收货日期')})"
                           type="date" :short-cut-flag="true"/>
          </DkFormItem>
          <!--收货仓库-->
          <DkFormItem prop="whId" :label="$t('wareHouse')">
            <SelectPop v-model="formData.whId" ref="whId"
                       :options="warehouseList"
                       :multiple="false"
                       labelKey="whName" valueKey="whId">
            </SelectPop>
          </DkFormItem>
          <!--收货人-->
          <DkFormItem prop="contactName" :label="$t('contactName')">
            <InputPop :telephone="true" 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"
          ></EditTable>
          <div>
            <DkForm slot="content" ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="5"
                    name="dk-form"
                    class="form-content-class">
            </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.allCanNoEdit?true:false"
                     folder="t_order/annex_paths" :accept="$config.uploadFileConfig.acceptPicType"
                     :format="['jpg','jpeg','png']"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>

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

    <!--以销定采-->
    <DkModal
      :loading="loading"
      v-model="purchaseBasedOnSalesFlag"
      :title="$t('purchaseBasedOnSales')"
      width="1500px"
      @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>
          <!--商品型号-->
          <DkFormItem prop="skuModel" :label="$t('skuModel')">
            <InputPop ref="skuModel" v-model="purchaseBasedOnSalesFormData.skuModel"/>
          </DkFormItem>
          <!--商品编码-->
          <DkFormItem prop="skuCode" :label="$t('goodCode')">
            <InputPop ref="skuCode" v-model="purchaseBasedOnSalesFormData.skuCode"/>
          </DkFormItem>
          <!--商品名称-->
          <DkFormItem prop="skuName" :label="$t('skuName')">
            <InputPop ref="skuName" v-model="purchaseBasedOnSalesFormData.skuName"/>
          </DkFormItem>
          <!--客户名称-->
          <DkFormItem prop="customerName" :label="$t('customerName')">
            <InputPop ref="customerName" v-model="purchaseBasedOnSalesFormData.customerName"/>
          </DkFormItem>
          <!--客户电话-->
          <DkFormItem prop="customerPhone" :label="$t('customerPhone')">
            <InputPop ref="customerPhone" v-model="purchaseBasedOnSalesFormData.customerPhone"/>
          </DkFormItem>
          <!--详细地址-->
          <DkFormItem prop="addressFull" :label="$t('customerAddress')">
            <InputPop ref="addressFull" v-model="purchaseBasedOnSalesFormData.addressFull"/>
          </DkFormItem>
          <!--部门-->
          <DkFormItem prop="orgId" :label="$t('orgId')">
            <SelectMagnifier v-model="purchaseBasedOnSalesFormData.orgId"
                             :display-text="purchaseBasedOnSalesFormData.orgName"
                             :type="this.$config.MagnifierType.staff"
                             :other-condition="{cpId:$store.state.user.cpId}"
                             :multiple="false"/>
          </DkFormItem>
          <!--送货日期-->
          <DkFormItem prop="deliveryTime">
            <DatePickerPop v-model="purchaseBasedOnSalesFormData.deliveryTime"
                           :placeholder="$t('inputWords',{'search-name':$t('estimateDeliveryDate')})"
                           type="date" :short-cut-flag="true"/>
          </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 class-name="fixed-left" type="checkbox" fixed="left"></DkTableColumn>
          <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 {
      //以销定采
      purchaseBasedOnSalesFlag: false,
      purchaseBasedOnSalesTableData: [],
      purchaseBasedOnSalesHeight: 400,
      purchaseBasedOnSalesColumns: [
        {field: 'orderNo'},
        {
          field: 'transferableQuantity',

          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,
        remarks: null,
      },
      //明细
      purchaseItemList: [],
      goodsColumns: [
        {
          field: 'skuCode',
          controlId: 'skuId',
          treeNode: true,
          type: 'tableSelect',
          fixed: 'left',
          promotionType: true,
          dataType: self.$config.tableSelectType.goods,
          tip: self.$t('W_117'),
          fieldUpdate: [
            {updateField: 'skuCode', valueFiled: 'skuCode'},
            {updateField: 'itemQty', valueFiled: 'itemQty', defaultValue: 1},
            {updateField: 'skuId', valueFiled: 'skuId'},
            {updateField: 'skuName', valueFiled: 'skuName'},
            {updateField: 'pricePur', valueFiled: 'pricePurchase'},
            {updateField: 'pricePurchase', valueFiled: 'pricePurchase'},
          ],
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          controlId: 'skuId',
          type: 'tableSelect',
          fixed: 'left',
          promotionType: true,
          dataType: self.$config.tableSelectType.goods,
          fieldUpdate: [
            {updateField: 'skuCode', valueFiled: 'skuCode'},
            {updateField: 'itemQty', valueFiled: 'itemQty', defaultValue: 1},
            {updateField: 'skuId', valueFiled: 'skuId'},
            {updateField: 'skuName', valueFiled: 'skuName'},
            {updateField: 'pricePur', valueFiled: 'pricePurchase'},
            {updateField: 'pricePurchase', valueFiled: 'pricePurchase'},
          ],
          searchDetailFlag: true
        },
        {
          field: 'itemQty',
          type: 'number',
          digits: 0,
          sum: true,
        },//数量
        {
          field: 'pricePur',
          type: 'number',
          digits: 2,
        },//采购价
        {
          field: 'pricePurchase',
          type: 'disabled',
          digits: 2,
          number: true,
          sum: true
        },//采购标价
        {
          field: 'remarks',
        },
      ],
      //商品合计信息
      goodsFootFormData: {
        sumGoodsAmount: 0,
        sumStandard: 0,
        sumPromotion: 0,
        discountPromotion: 0,
        discountStandard: 0,
        sumVolume: 0,
        sumWeight: 0,
        sumQuantity: 0,//总数量
      },
      receiptList: [],//收款集合
      //客户收款
      feeFormData: {
        sumAmount: 0, //合计金额
        sumFeeAmount: 0,//费用金额
        sumReceiptAmount: 0,//定金金额
        sumUsePrestore: 0,//使用预存
        usablePrestore: 0,//可用预存
        sumReceivableAmount: 0,// 定金+使用预存
        receivable: 0, //剩余应收
        sumReceiptList: [],//收款
      },
      warehouseList: [],//仓库
    }
  },

  methods: {
    /**
     * @desc   : 分页
     * @author : 付斌
     * @date   : 2024-02-19 10:44
     */
    purchaseBasedOnSalePageSizeChange(pageInfo) {
    },
    /**
     * @desc   : 以销定采弹窗打开并查询数据
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    purchaseBasedOnSales(modalOpenFlag) {
      this.purchaseBasedOnSalesFlag = true
    },
    /**
     * @desc   : 以销定采选择商品确认带回方法
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    purchaseBasedOnSalesOk() {

    },
    /**
     * @desc   : 关闭弹窗
     * @author : 付斌
     * @date   : 2024-02-19 10:45
     */
    clearPurchaseBasedOnSales() {
    },

    /**
     * @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.pricePurchase)) {
        this.$Message.warning(this.$t('W_001', {param: this.$t('pricePurchase')}))
        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 = '10112024-0221-0000-0000-000000011b49';
      // 员工
      this.params.staffId = '10112024-0222-0000-0000-0000000bef4d';
      // 制单员
      this.params.makeStaff = '10112024-0222-0000-0000-0000000bef4d'
      // 公司
      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();
        let editTable = this.countItem(changeTable)
        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/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.purchaseItemList = data.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() {
    this.resizeTableFlag = true;  // 计算表格高度
  },
}
</script>
