<template>
  <div>
    <Modal v-model="showModal" width="100" :mask-closable="false" class="zIndex-1000 full-screen" :styles="{marginTop:'-80px'}">
      <p slot="header">
        制备
      </p>
      <Row>
        <!--        <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" />-->

        <Button type="primary" style="margin-bottom: 5px" @click="_printLabel">
          打印标签
        </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==='type'">
                <el-select
                  v-model="scope.row.type"
                  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==='quantity'">
                <el-input v-model="scope.row.quantity" 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==='timeLimit'">
                <el-input v-model="scope.row.timeLimit" type="number" placeholder="天数" size="small" />
              </template>
              <template v-else-if="item.key==='position'">
                <el-input v-model="scope.row.position" placeholder="位置" size="small" />
              </template>
              <template v-else-if="item.key==='keepTime'">
                <Date-picker
                  v-model="scope.row.keepTime"
                  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 { getLodop } from '../../plugins/clodop/LodopFuncs'
import { drugSampleKeep } from './../../api'
import global from './../../api/config'
import downloadPlugin from './download/downloadPlugin'
let LODOP
const letter = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
]
export default {
  name: 'Preparation',
  components: {
    downloadPlugin
  },
  data() {
    return {
      showModal: false,
      btn: [
        // { id: '', type: 'success', name: '添加' },
        { id: '', type: 'primary', name: '打印标签' }
      ],
      iconMsg: [{ id: '', type: 'pt-a-trash', name: '删除' }],
      pageColumns: [
        {
          title: '样本编号',
          key: 'sampleCode',
          width: 120,
          fixed: 'left',
          align: 'center'
        },
        { title: '物品名称', key: 'name', width: 120, align: 'center' },
        { title: '物品编号', key: 'code', width: 120, align: 'center' },
        {
          title: '制备类型',
          key: 'type',
          width: 120,
          align: 'center'
        },
        { title: '打印份数', key: 'printNum', width: 120, align: 'center' },
        {
          title: '取样数量',
          key: 'quantity',
          width: 200,
          align: 'center'
        },
        {
          title: '储存期限(天)',
          key: 'timeLimit',
          width: 120,
          align: 'center'
        },
        {
          title: '存储位置',
          key: 'position',
          width: 120,
          align: 'center'
        },
        {
          title: '制备时间',
          key: 'keepTime',
          width: 210,
          align: 'center'
        },
        { title: '备注', key: 'remark', align: 'center' }
      ],
      typeList: [{ label: '送检样', value: 1 }, { label: '留样', value: 2 }],
      qualityList: [
        { label: 'g', value: 1 },
        { label: 'mg', value: 2 },
        { label: 'ml', value: 3 },
        { label: 'L', value: 4 }
      ],
      footerList: [
        { id: '', name: '制备完成', type: 'primary' },
        { id: '', name: '取消', type: '' }
      ],
      getPage: {
        records: []
      },
      searchOpen: false,
      selectData: [],
      selectIds: [],
      sampleIds: [],
      codeList: [],
      firstData: {},
      alreadyCodeList: [],
      keeper: '',
      keeperId: ''
    }
  },
  computed: {
    tableHeight() {
      return this.$tableHeight('search')
    }
  },
  methods: {
    _open(data, ids) {
      this.showModal = true
      this.alreadyCodeList = ['S', 'B', 'Y']
      this.getPage.records = []
      this._hideLoading()
      this._getCodeList()
      this._page(data)
      this.sampleIds = ids
      this.keeper = global.getUserInfo().realname
      this.keeperId = global.getUserInfo().id
    },
    _getCodeList() {
      this.codeList = letter.filter(i => this.alreadyCodeList.indexOf(i) === -1)
    },
    _printLabel() {
      if (this.selectData.length > 0) {
        this.$Modal.confirm({
          title: '提示',
          content: `确定打印 ${this.selectData.length} 条信息吗?`,
          onOk: () => {
            this._printMessage()
          }
        })
      } else {
        this.$Message.warning('请至少选择一条数据')
      }
    },
    _page(data) {
      for (let i = 0; i < data.length; i++) {
        this.getPage.records.push(
          {
            sampleId: data[i].id,
            name: data[i].name,
            sampleNum: 'S',
            sampleCode: data[i].sampleCode,
            code: data[i].code,
            spec: data[i].spec,
            supplier: data[i].supplier,
            type: data[i].type ? data[i].type : '送检样',
            keepTime: this.$dateformat(data[i].keepTime, 'yyyy-mm-dd HH:MM:ss'),
            inspectionDate: data[i].inspectionDate
              ? this.$dateformat(data[i].inspectionDate, 'yyyy-mm-dd HH:MM:ss')
              : '',
            position: '#01',
            printNum: data[i].printNum ? data[i].printNum : 1,
            quantity: data[i].quantity ? data[i].quantity : 10,
            timeLimit: '30',
            unit: 'g',
            declarationName: data[i].declarationName,
            remark: ''
          },
          {
            sampleId: data[i].id,
            name: data[i].name,
            sampleNum: 'B',
            sampleCode: data[i].sampleCode,
            code: data[i].code,
            modelSpec: data[i].modelSpec,
            supplier: data[i].supplier,
            type: data[i].type ? data[i].type : '留样',
            keepTime: this.$dateformat(data[i].keepTime, 'yyyy-mm-dd HH:MM:ss'),
            inspectionDate: data[i].inspectionDate
              ? this.$dateformat(data[i].inspectionDate, 'yyyy-mm-dd HH:MM:ss')
              : '',
            position: '#01',
            printNum: data[i].printNum ? data[i].printNum : 1,
            quantity: data[i].quantity ? data[i].quantity : 10,
            timeLimit: '30',
            unit: 'g',
            declarationName: data[i].declarationName,
            remark: ''
          }
        )
      }
      this.firstData = this.getPage.records[0]
      this.$refs.pageTable._initTable()
    },
    _typeChange(data) {
      console.log(data)
    },
    _btnClick: function(msg, data) {
      switch (msg) {
        case '打印标签':
          if (this.selectData.length > 0) {
            this.$Modal.confirm({
              title: '提示',
              content: `确定打印 ${this.selectData.length} 条信息吗?`,
              onOk: () => {
                this._printMessage()
              }
            })
          } else {
            this.$Message.warning('请至少选择一条数据')
          }
          break
        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)
    },
    _printMessage: function() {
      LODOP = getLodop()
      if (LODOP === 'undefined' || LODOP === undefined) {
        this._pluginDownload()
        return false
      }
      if (LODOP.GET_PRINTER_COUNT() === 0) {
        this.$Messager.warning('系统未关联打印机,请确认....')
        return false
      }
      const data = this.selectData
      for (let i = 0; i < data.length; i++) {
        LODOP.PRINT_INITA(
          '0mm',
          '0mm',
          '60.01mm',
          '40.01mm',
          '打印控件功能演示_Lodop功能_打印图片3'
        )
        if (data[i].type === '留样') {
          LODOP.ADD_PRINT_BARCODE(
            '0.88mm',
            '5.16mm',
            '18.65mm',
            '19.71mm',
            'QRCode',
            `${data[i].sampleCode}`
          )
          LODOP.ADD_PRINT_TEXT(
            107,
            4,
            180,
            20,
            '样品编号：' + data[i].sampleCode
          )
          LODOP.ADD_PRINT_TEXT(130, 3, 180, 20, '物品名称：' + data[i].name)
          LODOP.ADD_PRINT_TEXT(
            85,
            4,
            180,
            20,
            '制备时间：' +
              this.$dateformat(data[i].keepTime, 'yyyy-mm-dd HH:MM')
          )
          LODOP.ADD_PRINT_TEXT(63, 3, 180, 20, '保存期限：' + data[i].timeLimit)
          LODOP.ADD_PRINT_TEXT(20, 106, 75, 31, '留样')
          LODOP.SET_PRINT_STYLEA(0, 'FontSize', 15)
        } else if (data[i].type === '送检样') {
          LODOP.ADD_PRINT_BARCODE(
            '0.87mm',
            '5.16mm',
            '18.65mm',
            '19.71mm',
            'QRCode',
            'D2020030006'
          )
          LODOP.ADD_PRINT_TEXT(
            94,
            4,
            180,
            20,
            '样品编号：' + data[i].sampleCode
          )
          LODOP.ADD_PRINT_TEXT(68, 4, 180, 20, '物品名称：' + data[i].name)
          LODOP.ADD_PRINT_TEXT(
            120,
            3,
            180,
            20,
            '制备时间：' +
              this.$dateformat(data[i].keepTime, 'yyyy-mm-dd HH:MM')
          )
          LODOP.ADD_PRINT_TEXT(20, 106, 75, 31, '检样')
          LODOP.SET_PRINT_STYLEA(0, 'FontSize', 16)
        }

        // LODOP.ADD_PRINT_TEXT(100, 112, 217, 19, data[i].name)
        // LODOP.SET_PRINT_STYLEA(0, 'FontSize', 12)
        // LODOP.SET_PRINT_STYLEA(0, 'Angle', 90)
        // LODOP.ADD_PRINT_BARCODE(
        //   '0.66mm',
        //   '5.16mm',
        //   '18.65mm',
        //   '19.71mm',
        //   'QRCode',
        //   `${data[i].sampleCode}`
        // )
        // LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
        // LODOP.SET_PRINT_STYLEA(0, 'Vorient', 2)
        // LODOP.SET_PRINT_STYLEA(0, 'Angle', 90)
        // LODOP.ADD_PRINT_TEXT(100, 138, 217, 19, data[i].sampleCode)
        // LODOP.SET_PRINT_STYLEA(0, 'FontSize', 12)
        // LODOP.SET_PRINT_STYLEA(0, 'Angle', 90)
        // LODOP.ADD_PRINT_TEXT(
        //   100,
        //   163,
        //   210,
        //   19,
        //   this.$dateformat(data[i].pcTime, 'yyyy-mm-dd HH:MM')
        // )
        // LODOP.SET_PRINT_STYLEA(0, 'FontSize', 10)
        // LODOP.SET_PRINT_STYLEA(0, 'Angle', 90)
        // LODOP.ADD_PRINT_TEXT(100, 186, 200, 19, data[i].pcDepart)
        // LODOP.SET_PRINT_STYLEA(0, 'FontSize', 10)

        // LODOP.SET_PRINT_STYLEA(0, 'Angle', 90)
        // LODOP.SET_PRINT_COPIES(data[i].printNum)
        LODOP.PRINT_DESIGN()
        // LODOP.PRINT_DESIGN()
      }
    },
    // 下载插件
    _pluginDownload() {
      this.$refs.downloadPlugin._open()
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          //
          break
        case 'selectData':
          this._selectData(data)
          break
      }
    },
    _selectData(data) {
      this.selectData = data
      const selectIds = []
      for (let i = 0; i < data.length; i++) {
        selectIds.push(data[i].id)
      }
      this.selectIds = selectIds
    },
    _iconClick(msg, data) {
      switch (msg) {
        case '删除':
          this._deleteById(data)
          break
      }
    },
    _footerResult(msg) {
      switch (msg) {
        case '制备完成':
          this._ok()
          break
        case '取消':
          this._cancel()
          break
      }
    },
    // 后缀名操作
    _codeChange() {
      const { records } = this.getPage
      this.alreadyCodeList = records.map(({ sampleNum: i }) => i)
      this._getCodeList()
    },
    // 操作的序号
    _handleIndex(data) {
      this.currentIndex = data.$index
    },
    _cancel() {
      this.showModal = false
    },
    _ok() {
      const data = this.getPage.records
      if (!data.find(i => i.type === '送检样')) {
        this.$Message.warning('制备类型至少含有一个送检样!')
        return
      }
      const preList = data.map(i => ({
        sampleId: i.sampleId,
        name: i.name,
        sampleNum: i.sampleNum,
        type: i.type,
        keepTime: this.$dateformat(i.keepTime, 'yyyy-mm-dd HH:MM:ss'),
        unit: `${i.unit}`,
        quantity: `${i.quantity}`,
        keeper: this.keeper,
        keeperId: this.keeperId,
        position: i.position,
        printNum: i.printNum,
        timeLimit: i.timeLimit,
        remark: i.remark
      }))
      preList.sampleId = this.sampleIds
      this._saveData(preList)
    },
    async _saveData(preList) {
      const result = await drugSampleKeep.makeEnd({
        backupsDTOS: preList,
        sampleId: this.sampleIds[0]
      })
      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>
