<template>
  <div>
    <Modal v-model="showModal" :mask-closable="false" :fullscreen="true" width="100" class="zIndex-1000">
      <p slot="header">制备</p>
      <Row>
        <!--操作-->
        <Col span="24">
          <btn-list :msg="btn" @on-result-change="_btnClick" class="contHide"></btn-list>
        </Col>
        <!--内容-->
        <Col span="24">
          <PTVXETableHeight
            ref="pageTable"
            :table-height="tableHeight"
            :get-page="getPage"
            :form-id="formId"
            @on-result-change="_tableResultChange"
            select-data
            is-edit
            hide-page>
            <vxe-table-column
              v-for="item in pageColumns"
              :key="item.key"
              :field="item.key"
              :title="item.title"
              :min-width="item.width?item.width:200"
              :fixed="item.fixed?item.fixed:undefined"
              :edit-render="item.editCell?{autofocus: 'input'}:null"
              sortable
            >
              <!--可编辑模板-->
              <template v-slot:edit="scope">
                <div v-if="item.key==='prepareWay'" @click="_handleRow(scope)">
                  <AutoComplete v-model="scope.row.prepareWay" :down-data="preparationWayData" :way-data="wayData"
                                 :handle-obj="scope" @on-result-change="_preparationChange" clearable
                                 placeholder="输入或选择制备方式"></AutoComplete>
                </div>
                <div v-else-if="item.key==='unit'" @click="_handleRow(scope)">
                  <el-input v-model="scope.row.unit" name="unit" placeholder="输入或选择单位">
                  </el-input>
                </div>
                <div v-else-if="item.key==='quantity'" @click="_handleRow(scope)">
                  <el-input v-model="scope.row.quantity" name="quantity" placeholder="输入数量">
                  </el-input>
                </div>
                <span v-else-if="item.key==='type'">{{ scope.row[item.key]===0? '检样':'备样' }}</span>
                <div v-else-if="item.key==='keepWay'" @click="_handleRow(scope)">
                  <AutoComplete v-model="scope.row.keepWay" :handle-obj="scope" :down-data="saveWayData"
                                @on-result-change="_saveChange" clearable
                                placeholder="输入或选择保存方式" show-key="name"></AutoComplete>
                </div>
                <div v-else-if="item.key==='keepContainer'" @click="_handleRow(scope)">
                  <AutoComplete v-model="scope.row.keepContainer" :handle-obj="scope" :down-data="packList"
                                @on-result-change="_packSaveChange" clearable
                                placeholder="输入或选择保存容器" show-key="name"></AutoComplete>
                </div>
<!--                <div v-else-if="item.key==='prepareDate'" @click="_handleTimeRow(scope)">-->
<!--                  <el-date-picker-->
<!--                    v-model="scope.row.prepareDate"-->
<!--                    type="datetime"-->
<!--                    placeholder="选择日期时间">-->
<!--                  </el-date-picker>-->
<!--                </div>-->
                <div v-else-if="item.key==='prepareDate'" @click="_handleRow(scope)">
                  <el-date-picker v-model="scope.row.prepareDate" @change="timeChange(scope.row)" type="datetime" format="yyyy-MM-dd HH:mm" style="width:100%;"
                               placeholder="请选择日期"></el-date-picker>
                </div>
                <div v-else-if="item.key==='preparer'" @click="_handleRow(scope)">
                  <el-input v-model="scope.row.preparer" @focus="_handleRow(scope)"
                            placeholder="制备人" size="small" name="preparer"></el-input>
                </div>
                <div v-else-if="item.key==='remark'" @click="_handleRow(scope)">
                  <el-input v-model="scope.row.remark" @focus="_handleRow(scope)" placeholder="备注"
                            size="small"></el-input>
                </div>
                <span v-else>{{scope.row[item.key]}}</span>
              </template>
              <!--只读模板-->
              <template v-slot="scope">
                <div v-if="item.key==='num'">
                  <div v-if="scope.row.itemPreparation===0">{{scope.row[item.key]}}</div>
                  <div v-else-if="scope.row.itemPreparation===1" class="red-color">
                    {{scope.row[item.key]}}
                  </div>
                </div>
                <div v-else-if="item.date">
                  {{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM'):''}}
                </div>
                <span v-else-if="item.key==='type'">{{ scope.row[item.key]===0? '检样':'余样' }}</span>
                <span v-else-if="item.key==='status'">{{ scope.row[item.key].display }}</span>
                <div v-else>{{scope.row[item.key]}}</div>
              </template>
            </vxe-table-column>
          </PTVXETableHeight>
        </Col>
      </Row>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult"></modal-footer>
      </div>
      <!--打印标签-->
      <!--选择人员-->
    </Modal>
    <!--下载插件-->
    <downloadPlugin ref="downloadPlugin" />
    <SampleParpareBatchEdit ref="batchEdit" @on-result-change="backData"></SampleParpareBatchEdit>
  </div>
</template>

<script>
import AutoComplete from '../../../components/base/AutoCompletes'
import { soilEntrust } from '../../../api'
import { getLodop } from '../../../plugins/clodop/LodopFuncs'
// eslint-disable-next-line no-unused-vars
import downloadPlugin from '../../../plugins/download/downloadPlugin'
import SampleParpareBatchEdit from './SampleParpareBatchEdit'
let LODOP

export default {
  components: {
    AutoComplete,
    downloadPlugin,
    SampleParpareBatchEdit
  },
  data() {
    return {
      formId: 'preparationModal',
      showModal: false,
      wayData: new Map(),
      formObj: {},
      tableHeight: document.documentElement.clientHeight - 215,
      footerList: [],
      list: [
        { name: '取消', type: '', id: '' },
        { name: '制备完成', type: 'primary', id: '' }
      ],
      btn: [
        { type: 'success', id: '', name: '打印标签' },
        { type: 'error', id: '', name: '删除' },
        { type: 'success', id: '', name: '批量填写制备信息' }
      ],
      iconMsg: [
        // { type: 'md-create', id: '', name: '批量赋值' },
        // { type: 'md-trash', id: '', name: '删除' }
      ],
      getPage: {
        records: []
      },
      selectData: [],
      selectIds: [],
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 130 },
        { title: '试样深度', key: 'sampleDepth', width: 130 },
        { title: '检验科室', key: 'groupName', width: 130 },
        // 暂时屏蔽
        // {title: '打印份数', key: 'printNum', width: 110},
        { title: '制备类型', key: 'type', width: 130 },
        {
          title: '制备方式',
          key: 'prepareWay',
          width: 130,
          editCell: true
        },
        {
          title: '制备数量',
          key: 'quantity',
          width: 150,
          editCell: true
        },
        { title: '单位', key: 'unit', width: 110, editCell: true },
        { title: '状态', key: 'status', width: 150 },
        { title: '保存方式', key: 'keepWay', width: 150, editCell: true },
        { title: '保存容器', key: 'keepContainer', width: 150, editCell: true },
        {
          title: '制备时间',
          key: 'prepareDate',
          width: 200,
          date: true,
          editCell: true
        },
        {
          title: '制备人',
          key: 'preparer',
          width: 130,
          editCell: true
        },
        { title: '备注', key: 'remark', width: 150, editCell: true }
      ],
      currentRow: {},
      preparationWayData: [],
      resultStateWayData: [],
      saveWayData: [],
      sampleIds: '',

      unitData: [],
      locationList: [],
      packList: [],
      isAccurate: ''
    }
  },
  mounted() {
    this.$refs.pageTable._showLoading()
  },
  methods: {
    // 获取存储位置
    _locationChange(msg, data, handleObj) {
      this.currentRow = handleObj
      switch (msg) {
        case 'select':
          this.$set(this.currentRow, 'storePlace', data)
          break
        case 'query':
          this.$set(this.currentRow, 'storePlace', data)
          this._getLocation(data)
          break
        case 'focus':
          this._getLocation()
          break
      }
    },
    // 单位
    _unitChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.unit = data
          break
        case 'query':
          this.currentRow.unit = data
          break
      }
    },
    backData(data) {
      this.$forceUpdate()
      console.log(data)
      console.log(this.selectData)
      for (let i = 0; i < this.selectData.length; i++) {
        Object.assign(this.selectData[i], data)
      }
      console.log('合并后', this.selectData)
    },
    _preparationChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      this.currentRow.prepareWay = data
    },
    _testItemChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      this.currentRow.resultState = data.name
    },
    _saveChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      this.currentRow.keepWay = data.name
    },
    timeChange(data) {
      console.log(data)
      this.$forceUpdate()
      this.currentRow.prepareDate = data.prepareDate
      console.log(this.getPage.records)
    },
    _packSaveChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      this.currentRow.keepContainer = data.name
    },
    _open(sampleIds) {
      this.$refs.pageTable._showLoading()
      this.sampleIds = sampleIds
      console.log(this.sampleIds)
      this.showModal = true
      this.getPage.records = []
      this.unitData = []
      this.footerList = []
      for (let i = 0; i < this.list.length; i++) {
        if (this.$showBtn(this.list[i].id)) {
          this.footerList.push(this.list[i])
        }
      }
      this._page()
      // this._dicSearch()
    },
    _page: async function() {
      const result = await soilEntrust.preparePage(this.sampleIds)
      if (result) {
        console.log(result)
        this.getPage.records = result
        for (let j = 0; j < result.length; j++) {
          console.log(result[j].prepareDate)
          console.log(new Date(result[j].prepareDate))
          this.getPage.records[j].prepareDate = new Date(result[j].prepareDate)
        }
        this.$refs.pageTable._hideLoading()
      }
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '仅流转微生物':
          this._changeMic()
          break
        case '制备完成':
          this._ok()
          break
      }
    },
    _cancel() {
      this.showModal = false
      this._hideLoading()
    },
    _ok() {
      console.log(this.getPage.records)
      const prepareList = []
      for (let i = 0; i < this.getPage.records.length; i++) {
        prepareList.push(this.getPage.records[i])
      }
      if (prepareList.length === 0) {
        this.$Message.warning('制备数据不能为空')
        this._hideLoading()
        return false
      }
      this.save({ prepareList: prepareList })
    },
    save: async function(data) {
      const result = await soilEntrust.savePrepare(data)
      console.log(result)
      this._resultChange('制备成功')
    },
    _resultChange(msg) {
      this.showModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
      this._hideLoading()
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._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
        case 'iconClick':
          this._iconClick(
            data.name,
            data.rowData,
            data.componentName,
            data.rowIndex
          )
          break
      }
    },
    _btnClick(msg) {
      switch (msg) {
        case '打印标签':
          if (this.selectData.length > 0) {
            this._printMessage()
          } else {
            this.$Message.warning('请至少选择一条数据')
          }
          break
        case '批量填写制备信息':
          this._writeInfo()
          break
        case '删除':
          this._deleteSelected()
          break
      }
    },
    // 下载插件
    _pluginDownload() {
      this.$refs.downloadPlugin._open()
    },
    _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'
        )
        LODOP.ADD_PRINT_BARCODE(
          '0.08mm',
          '18.39mm',
          '58.87mm',
          '24.74mm',
          'QRCode',
          data[i].sampleCode + '-' + data[i].groupId
        )
        LODOP.ADD_PRINT_TEXT(
          130,
          13,
          186,
          20,
          this._formatDate(data[i].prepareDate)
        )
        LODOP.SET_PRINT_STYLEA(0, 'Alignment', 2)
        LODOP.ADD_PRINT_TEXT(113, 13, 187, 20, data[i].groupName)
        LODOP.SET_PRINT_STYLEA(0, 'Alignment', 2)
        LODOP.ADD_PRINT_TEXT(95, 12, 188, 20, data[i].sampleCode)
        LODOP.SET_PRINT_STYLEA(0, 'Alignment', 2)

        LODOP.PRINT_DESIGN()
      }
    },
    // 时间戳转换方法    date:时间戳数字
    _formatDate(time) {
      const date = new Date(time)
      const YY = date.getFullYear() + '-'
      const MM =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-'
      const DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      const hh =
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const mm =
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
        ':'
      const ss =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return YY + MM + DD + ' ' + hh + mm + ss
    },
    _writeInfo() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this.$refs.batchEdit._open(this.selectIds)
      }
    },
    _printerResult(data) {
      this.$refs.printNumber._open(this.selectData, data.printerVal)
    },
    _deleteSelected() {
      // 批量删除
      const selectData = this.selectData
      if (selectData.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(
          selectData,
          '确定删除 ' + selectData.length + ' 条记录？'
        )
      }
    },
    _iconClick(res, data, componentName, rowIndex) {
      this.currentRow = data
      switch (res) {
        case '批量赋值':
          this._copyPlan(data)
          break
        case '删除':
          this._deleteByIds([data])
          break
      }
    },
    _deleteByIds(rows, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          for (let i = 0; i < rows.length; i++) {
            const index = this.getPage.records.indexOf(rows[i])
            this.getPage.records.splice(index, 1)
          }
          this.$Message.success('操作成功')
          this.selectData = []
          this.selectIds = []
        }
      })
    },
    _selectStaff() {
      this.$refs.userModal._open('preparationPerson')
    },
    _userData(data) {
      // 选择人员返回数据
      this.currentRow.preparationPerson = data.realname
      this.currentRow.preparationPersonId = data.userId
    },

    // 批量赋值(这里用index判断，不用id是因为id有时候没有值，而且id不能随意赋值)
    _copyPlan(data) {
      const ids = this.selectData
      const records = this.getPage.records
      if (ids.length === 0) {
        this.$Message.warning('请勾选数据进行赋值！')
      } else {
        for (let i = 0; i < ids.length; i++) {
          for (let j = 0; j < records.length; j++) {
            if (ids[i].currentIndex === records[j].currentIndex) {
              this._singleCopy(j, data)
            }
          }
        }
      }
    },
    // 单独赋值信息
    _singleCopy(j, data) {
      const tempData = {
        preparationWay: data.preparationWay,
        resultQuantity: data.resultQuantity ? data.resultQuantity : 0,
        unit: data.unit,
        resultState: data.resultState ? data.resultState : '',
        saveWay: data.saveWay ? data.saveWay : '',
        pack: data.pack ? data.pack : '',
        storePlace: data.storePlace ? data.storePlace : '',
        printNum: data.printNum ? data.printNum : 1,
        remark: data.remark ? data.remark : ''
      }
      this.getPage.records[j].preparationWay = tempData.preparationWay
      this.getPage.records[j].resultQuantity = tempData.resultQuantity
      this.getPage.records[j].unit = tempData.unit
      this.getPage.records[j].resultState = tempData.resultState
      this.getPage.records[j].saveWay = tempData.saveWay
      this.getPage.records[j].pack = tempData.pack
      this.getPage.records[j].storePlace = tempData.storePlace
      this.getPage.records[j].printNum = tempData.printNum
      this.getPage.records[j].remark = tempData.remark
    },
    // 操作的序号
    _handleRow(data) {
      console.log(data)
      this.currentIndex = data.index
      this.currentRow = data.row
    },
    _handleTimeRow(data) {
      console.log(this.currentRow)
      this.currentRow = data.row
    }
  }
}
</script>
