<template>
  <div>
    <Modal v-model="showModal" width="1300" class="modal-footer-none zIndex-1100">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <Row>
        <Form
          v-show="searchOpen"
          id="sample-preparation-form"
          inline
          onsubmit="return false"
          :label-width="75"
          class="search-form"
        >
          <label class="label-sign" />
          <Form-item class="search-item" label="耗材编号:">
            <input v-model="orderId" type="hidden" name="orderId"></input>
            <Input v-model="formObj.chemicalNum" name="chemicalNum" placeholder="请输入耗材编号" @on-enter="_formSearch" /></Input>
          </Form-item>
          <Form-item class="search-item" label="耗材名称:">
            <Input v-model="formObj.chemicalName" name="chemicalName" placeholder="请输入耗材名称" @on-enter="_formSearch" /></Input>
          </Form-item>
          <Form-item class="search-item" label="供应商:">
            <Input v-model="formObj.supplier" name="supplier" placeholder="请输入供应商" @on-enter="_formSearch" /></Input>
          </Form-item>
          <Form-item class="search-item" label="规格:">
            <Input v-model="formObj.spec" name="spec" placeholder="请输入规格" @on-enter="_formSearch" /></Input>
          </Form-item>
          <Form-item class="search-item" label="制造厂商:">
            <Input v-model="formObj.manufacturer" name="manufacturer" placeholder="请输入制造厂商" @on-enter="_formSearch" /></Input>
          </Form-item>
          <Form-item class="search-btn">
            <Button type="primary" @click="_formSearch">
              搜索
            </Button>
          </Form-item>
        </Form>
        <!--        <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" />-->
        <el-button type="primary" @click="_buyOk">
          采购完成
        </el-button>
        <Col />
        <element-table
          ref="pageTable"
          :page-columns="pageColumns"
          :table-height="tableHeight"
          :get-page="getPage"
          show-check-box
          select-data
          hide-page
          @on-result-change="_tableResultChange"
        >
          <el-table-column
            v-for="item in pageColumns"
            :key="item.key"
            show-overflow-tooltip
            sortable
            :prop="item.key"
            :label="item.title"
            :align="item.align"
            :width="item.width"
            :min-width="200"
            :fixed="item.fixed?item.fixed:undefined"
          >
            <template slot-scope="scope">
              <template v-if="item.key==='preparationType'">
                <el-select
                  v-model="scope.row.preparationType"
                  placeholder="请选择类别"
                  size="small"
                  style="width:100%"
                  @change="_typeChange"
                >
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </template>
              <template v-else-if="item.key === 'sampleNum'">
                <el-select
                  v-model="scope.row.sampleNum"
                  placeholder="请选择缀名"
                  size="small"
                  style="width:100%"
                  @change="_codeChange"
                >
                  <el-option
                    v-for="item in codeList"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </template>
              <template v-else-if="item.key==='printNum'">
                <el-input v-model="scope.row.printNum" placeholder="份数" size="small" />
              </template>
              <template v-else-if="item.key==='preparationQuantity'">
                <el-input v-model="scope.row.preparationQuantity" placeholder="制备质量" size="small">
                  <el-select
                    slot="append"
                    v-model="scope.row.unit"
                    name="name"
                    placeholder="请选择类别"
                    size="small"
                    style="width: 75px;"
                  >
                    <el-option
                      v-for="item in qualityList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    />
                  </el-select>
                </el-input>
              </template>
              <template v-else-if="item.key==='storagePeriod'">
                <el-input v-model="scope.row.storagePeriod" type="number" placeholder="天数" size="small" />
              </template>
              <template v-else-if="item.key==='storageLocation'">
                <el-input v-model="scope.row.storageLocation" placeholder="位置" size="small" />
              </template>
              <template v-else-if="item.key==='preparationTime'">
                <Date-picker
                  v-model="scope.row.preparationTime"
                  type="datetime"
                  placeholder="制备时间"
                  style="width: 100%;"
                  :editable="false"
                  transfer
                />
              </template>
              <template v-else-if="item.key==='remark'">
                <el-input v-model="scope.row.remark" placeholder="备注" size="small" />
              </template>
              <template v-else>
                {{ scope.row[item.key] }}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            :width="100"
            fixed="right"
          >
            <template slot-scope="scope">
              <icon-list :msg="iconMsg" :row-data="scope.row" @on-result-change="_iconClick" />
            </template>
          </el-table-column>
        </element-table>
        </Col>
      </Row>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>
    <!--下载插件-->
    <downloadPlugin ref="downloadPlugin" />
  </div>
</template>

<script>
import { consumeRelPurchase } from './../../../api'
export default {
  name: 'Preparation',
  components: {},
  data() {
    return {
      showModal: false,
      purchaseOrder: {},
      status: '',
      orderId: '',
      formObj: {
        chemicalNum: '',
        chemicalName: '',
        supplier: '',
        spec: '',
        manufacturer: ''
      },
      modalTitle: '',
      btn: [
        // { id: '', type: 'success', name: '添加' },
        // { id: '', type: 'primary', name: '打印标签' }
      ],
      iconMsg: [{ id: '', type: 'pt-a-trash', name: '删除' }],
      pageColumns: [
        { title: '耗材编号', key: 'chemicalNum', width: 100 },
        { title: '耗材名称', key: 'chemicalName', width: 120 },
        { title: '状态', key: 'stateDisplay', width: 120 },
        { title: '单价', key: 'price', width: 100, price: true },
        { title: '采购量', key: 'quantity', width: 120, quantity: true },
        { title: '已入库数量', key: 'alreadyQuantity', width: 140 },
        { title: '计量单位', key: 'unit', width: 100 },
        { title: '规格', key: 'spec', width: 100, spec: true },
        { title: '等级（纯度）', key: 'quality', width: 120, quality: true },
        { title: '供应商', key: 'supplier', width: 200, supplier: true },
        {
          title: '制造厂商',
          key: 'manufacturer',
          width: 200,
          manufacturer: true
        },
        { title: '备注', key: 'remark', width: 285, remark: true }
      ],
      typeList: [
        { label: '送检样', value: 1 },
        { label: '备样', value: 2 },
        { label: '原大样', value: 3 }
      ],
      qualityList: [{ label: 'g', value: 1 }, { label: 'mg', value: 2 }],
      footerList: [{ id: '', name: '采购完成', type: 'primary' }],
      getPage: {
        records: []
      },
      searchOpen: true,
      selectData: [],
      selectIds: [],
      sampleIds: [],
      codeList: [],
      firstData: {},
      alreadyCodeList: [],
      sampleMaker: '',
      sampleMakerId: ''
    }
  },
  computed: {
    tableHeight() {
      return this.$tableHeight('search')
    }
  },
  methods: {
    _open(purchaseOrder) {
      this.showModal = true
      this.purchaseOrder = purchaseOrder
      this.orderId = this.purchaseOrder.id
      $('input[name=orderId]').val(this.purchaseOrder.id)
      this.modalTitle =
        purchaseOrder.num +
        '-' +
        (purchaseOrder.status === 0 ? '待提交' : '正常')

      this.status = purchaseOrder.status
      if (this.status === 0 || this.status === '审批驳回') {
        this.footerList = [
          { id: '', name: '取消', type: '' },
          { id: '', name: '提交审批', type: 'primary' }
        ]
      } else {
        this.footerList = [{ id: '', name: '取消', type: '' }]
      }
      this._page()
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const database = this.$serializeForm(this.formObj)
      console.log(database)
      const result = await consumeRelPurchase.page(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _typeChange(data) {
      console.log(data)
    },
    _buyOk() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this._purchaseEnd(this.selectIds)
      }
    },

    _purchaseEnd: async function() {
      const result = await consumeRelPurchase.finishPurchase(this.selectIds)
      if (result) {
        this.$Message.success('提交成功')
      }
    },

    _btnClick: function(msg, data) {
      switch (msg) {
        case '批量删除':
          this._deleteSelected()
          break
        case '添加':
          this._addItem()
          break
      }
    },
    _addItem() {
      const len = this.getPage.records.length
      const data = this.$extend({}, this.firstData)
      data.sampleNum = ''
      this.getPage.records.splice(len, 0, data)
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          //
          break
        case 'selectData':
          this.selectData = data
          const selectIds = []
          for (let i = 0; i < data.length; i++) {
            selectIds.push(data[i].id)
          }
          this.selectIds = selectIds
          break
      }
    },
    _iconClick(msg, data) {
      switch (msg) {
        case '删除':
          this._deleteById(data)
          break
      }
    },
    _footerResult(msg) {
      switch (msg) {
        case '制备完成':
          this._ok()
          break
        case '取消':
          this._cancel()
          break
      }
    },

    // 操作的序号
    _handleIndex(data) {
      this.currentIndex = data.$index
    },
    _cancel() {
      this.showModal = false
    },
    _ok() {
      const data = this.getPage.records
      if (!data.find(i => i.preparationType === '送检样')) {
        this.$Message.warning('制备类型至少含有一个送检样!')
        return
      }
      const preList = data.map(i => ({
        sampleId: i.sampleId,
        name: i.name,
        sampleNum: i.sampleNum,
        preparationType: i.preparationType,
        preparationTime: this.$dateformat(
          i.preparationTime,
          'yyyy-mm-dd HH:MM:ss'
        ),
        preparationQuantity: `${i.preparationQuantity}${i.unit}`,
        sampleMaker: this.sampleMaker,
        sampleMakerId: this.sampleMakerId,
        storageLocation: i.storageLocation,
        printNum: i.printNum,
        storagePeriod: i.storagePeriod,
        remark: i.remark
      }))
      this._saveData(preList)
    },
    async _saveData(preList) {
      const result = await consumeRelPurchase.backupsAdd({
        backupsDTOS: preList
      })
      if (result) {
        this._resultChange('制备完成!')
      }
      this._hideLoading()
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this.showModal = false
      this.$emit('on-result-change')
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _deleteById(rows, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录?',
        onOk: () => {
          const index = this.getPage.records.indexOf(rows)
          this.getPage.records.splice(index, 1)
          this.$Message.success('删除成功')
          this._codeChange()
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
