<!--
@name: 成品入库-康恩贝
@author: 李恒
@time: 2022-06-09 10:51:49
-->
<template>
  <div>
    <p-card title='主要信息' class='overflow-card'>
      <div slot='extra'>
        <p-button type='primary' @click='showExtractTag = true'>提取单据</p-button>
        <p-button class='ml-10' type='primary' @click="onReset">重置</p-button>
        <p-button class='ml-10' type='primary' @click="onSave">保存商品</p-button>
      </div>
      <p-form-model ref='formTargetModal' :label-col='{ span: 8 }' :model='form' :wrapper-col='{ span: 16 }'
                    class='plg-grid-from'>
        <a-row>
          <a-col :span='6'>
            <p-form-model-item label='仓库'>
              <p-input v-model='form.warehouseName' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='货主'>
              <p-input v-model='form.mtlOwnerName' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='订单类型'>
              <p-select v-model='form.rcvTypeName' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='单位'>
              <p-input v-model='form.shippername' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='开票时间'>
              <p-input v-model='form.createdate' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='开票员'>
              <p-input v-model='form.createby' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='ASN单号'>
              <p-input v-model='form.billno' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='关联单号'>
              <p-input v-model='form.asnAutoBillNum' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='订单状态'>
              <p-input v-model='form.status' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='备注'>
              <p-input v-model='form.remark' disabled/>
            </p-form-model-item>
          </a-col>
          <a-col :span='6'>
            <p-form-model-item label='收货员'>
              <p-input v-model='form.createby' disabled/>
            </p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>
      <p-table ref='dataSource'
               :data-source.sync='dataSource'
               :scroll='{x:true}'
               :selectedRowKeys.sync='selectedRowKeys'
               bordered dragle row-key='id'>
        <template slot='title' slot-scope='currentPageData'>
          <div class='table-head'>
            <div class='table-head-title'>商品明细</div>
            <div class='table-head-extra'>
              <p-button type='danger' @click="batchDel">删除</p-button>
            </div>
          </div>
        </template>
        <p-table-column data-index='itemNum' title='商品编码'/>
        <p-table-column data-index='categoryName' title='商品大类'/>
        <p-table-column data-index='itemName' title='商品名称'/>
        <p-table-column data-index='specification' title='商品规格'/>
        <p-table-column data-index='uom' title='包装单位'/>
        <p-table-column data-index='conversionRate' title='包装数量'/>
        <p-table-column data-index='pieceQty' title='待收数量'/>
        <p-table-column data-index='scanQty'>
          <span slot="title" class="txt-green">扫描数量</span>
          <template slot-scope='text, record'>{{ text }}</template>
        </p-table-column>
        <p-table-column data-index='scanCaseQty'>
          <span slot="title" class="txt-green">扫描件数</span>
          <template slot-scope='text, record'>{{ text }}</template>
        </p-table-column>
        <p-table-column data-index='whAreaCategoryCode' :width="120">
          <span slot="title" class="txt-blue">收货库别</span>
          <template slot-scope='text, record'>
            <p-select v-model="record.whAreaCategoryCode" :options="whAreaCategoryCodeOptions" style="width: 100%"/>
          </template>
        </p-table-column>
        <p-table-column data-index='manufacturerLotNum'>
          <span slot="title" class="txt-blue">批号</span>
          <template slot-scope='text, record'>{{ text }}</template>
        </p-table-column>
        <p-table-column data-index='batchProductionDate'>
          <span slot="title" class="txt-blue">生产日期</span>
          <template slot-scope='text, record'>
            {{ text }}
          </template>
        </p-table-column>
        <p-table-column data-index='batchExpiredDate'>
          <span slot="title" class="txt-blue">有效期至</span>
          <template slot-scope='text, record'>{{ text }}</template>
        </p-table-column>
        <p-table-column data-index='manufacturerName' title='生产厂家'/>
        <p-table-column data-index='productionPlace' title='产地'/>
        <p-table-column data-index='itemHealthListedLicensor' title='上市许可证'/>
        <p-table-column data-index='approvalNumber' title='批准文号'/>
        <p-table-column data-index='itemHealthRegisterNbr' title='注册证号'/>
        <p-table-column data-index='operation' fixed='right' title='操作' :width='140'>
          <template slot-scope='text, record,index'>
            <a-space>
              <a @click="rowCollection(record)">数据采集</a>
              <a @click="rowSplit(record,index)" class="ml-10">拆分</a>
            </a-space>
          </template>
        </p-table-column>
      </p-table>
    </p-card>
    <!--提取订单窗口-->
    <extractModal :showModalTag.sync='showExtractTag' @change='extractBill' :rcvTypes="rcvTypes"/>
    <!--数据采集窗口-->
    <collectionModal :selectBill="selectBill" :selectRecord="selectRecord" :showModalTag.sync='showCollectionTag'
                     @change="collectionBill"/>
  </div>
</template>

<script>
import extractModal from '../components/extractModal'
import collectionModal from '../components/collectionModal'
import {save, getAreaCategoryCode, getAreaCategoryCodeOptions} from './api'

export default {
  components: {extractModal, collectionModal},
  data() {
    return {
      form: {},
      showExtractTag: false,
      showCollectionTag: false,
      // 列表参数
      dataSource: [],
      selectedRowKeys: [],
      // 数据采集
      // 当前主单数据
      selectBill: {},
      // 单据类型
      rcvTypes: ['18'],
      // 当前采集行数据
      selectRecord: {},
      // 字典
      areaCategoryDictionary: [],
      whAreaCategoryCodeOptions: [],
    }
  },
  created() {
    // 获取库别字典
    this.getAreaCategoryDictionary()
  },
  methods: {
    // 提取订单回调
    extractBill({selectBill, selectDetail}) {
      console.log(selectBill)
      console.log(selectDetail)
      this.form = {...selectBill}
      this.dataSource = [...selectDetail]
      this.selectBill = selectBill
      this.$nextTick(() => {
        this.getAreaCategoryCode()
      })
    },
    // 数据采集回调
    collectionBill(data = {}) {
      const {containerDataSource = []} = data
      const {asnLineId} = this.selectRecord || {}
      const index = this.dataSource.findIndex(_ => _.asnLineId === asnLineId)
      if (index === -1) return this.$message.error('匹配明细行错误')
      const scanCaseQty = containerDataSource.reduce((pre, cur) => pre + (cur.caseQty * 1 || 0), 0)
      const scanQty = containerDataSource.reduce((pre, cur) => pre + (cur.receiveQty * 1 || 0), 0)
      this.dataSource[index].scanCaseQty = scanCaseQty
      this.dataSource[index].scanQty = scanQty
      this.dataSource = [...this.dataSource]
    },
    rowCollection(record) {
      this.selectRecord = {...record}
      this.showCollectionTag = true
    },
    // 明细拆分
    rowSplit(record, index) {
      const id = 'local' + Math.floor(Math.random() * 1000000)
      this.dataSource.splice(index, 0, {...record, scanCaseQty: '', scanQty: '', id})
    },
    // 删除明细
    batchDel() {
      if (this.selectedRowKeys.length === 0) return this.$message.warn('未选择需要删除的数据！')
      const selectedRowKeys = this.selectedRowKeys
      const self = this
      this.$confirm({
        title: `确定要删除[${selectedRowKeys.length}]条明细?`,
        onOk() {
          self.dataSource = self.dataSource.filter(_ => !selectedRowKeys.includes(_.id))
        }
      })
    },
    // 保存
    onSave() {
      const selectedRowKeys = this.selectedRowKeys
      const dataSource = this.dataSource
      if (dataSource.length === 0) return this.$message.warn('请先提取订单')
      if (selectedRowKeys.length === 0) return this.$message.warn('请选择要保存的明细')
      // 待处理明细列表
      let selectRows = this.dataSource.filter(_ => selectedRowKeys.includes(_.id))
      const rcvDate = this.$moment().format('YYYY-MM-DD HH:mm:ss')
      selectRows = selectRows.map(_ => {
        return {..._, rcvDate}
      })
      const rcvLinesDTOList = selectRows.map(_ => {
        return {..._, rcvLinesProfilesDTO: {..._}}
      })
      const params = {
        rcvHeadersDTO: {...this.form, rcvDate},
        rcvHeadersProfilesDTO: {...this.form},
        rcvHeadersSrcBillsDTOList: [...selectRows],
        rcvLinesDTOList: rcvLinesDTOList
      }
      save(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.onReset()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 重置
    onReset() {
      this.form = {}
      this.dataSource = []
      this.selectedRowKeys = []
      this.selectBill = {}
      this.selectRecord = {}
    },
    // 获取库别字典-字典
    getAreaCategoryDictionary() {
      getAreaCategoryCodeOptions().then(res => {
        if (res.success) {
          this.areaCategoryDictionary = res.data
        }
      })
    },
    // 获取库别字典-策略
    getAreaCategoryCode() {
      const areaCategoryDictionary = this.areaCategoryDictionary
      if (areaCategoryDictionary.length === 0) return
      const {mtlOwnerId, warehouseId, rcvType} = this.form
      const params = {
        enterpriseId: this.$store.state.user.info.enterpriseId,
        category: 'RcvAreaCategoryChoose',
        cargoOwnerId: mtlOwnerId,
        warehouseId: warehouseId
      }
      getAreaCategoryCode(params).then(res => {
        if (!res.success) return
        console.log(res)
        const matchFactors = res.data.rules.map(rule => rule.matchFactors).flat()
        const curFactors = matchFactors.find(_ => _.value.split(',').includes(rcvType))
        if (!curFactors) {
          console.error('库别匹配失败')
          return
        }
        console.log('curFactors', curFactors)
        const curRuleId = curFactors.ruleId
        const curRule = res.data.rules.find(_ => _.id === curRuleId)
        let options = curRule.searchFactors.map(_ => {
          return {label: _.value, value: _.value}
        })
        options = options.map(_ => {
          const matchOption = areaCategoryDictionary.find(item => item.dictCode === _.value)
          if (!matchOption) return _
          const {dictName} = matchOption
          return {..._, label: dictName}
        })
        this.whAreaCategoryCodeOptions = options
      })
    }
  }
}
</script>
