<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==='printNum'" @click="_handleRow(scope)">
                  <el-input v-model="scope.row.printNum" @input="inputChange(scope)" name="printNum"  placeholder="输入打印数量">
                  </el-input>
                </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="输入或选择保存方式"></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="输入或选择保存容器"></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==='preparer'" @click="_handleRow(scope)">
                  <AutoComplete v-model="scope.row.preparer" :handle-obj="scope" :down-data="preparerList"
                                @on-result-change="_preparerChange" clearable
                                placeholder="制备人"></AutoComplete>
                </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>
    <SelectPrinter ref="selectPrint" @on-result-change="_printResult"></SelectPrinter>
  </div>
</template>

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

export default {
  components: {
    AutoComplete,
    downloadPlugin,
    SampleParpareBatchEdit,
    SelectPrinter
  },
  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: []
      },
      labelCode: {},
      currentIndex: -1,
      selectData: [],
      selectIds: [],
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 130 },
        { title: '试样深度', key: 'sampleDepth', width: 130 },
        { title: '打印数量', key: 'printNum', width: 130, editCell: true },
        { 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: [],
      preparerList: [],
      sampleIds: '',

      unitData: [],
      locationList: [],
      packList: [],
      isAccurate: ''
    }
  },
  mounted() {
    this.$refs.pageTable._showLoading()
  },
  methods: {
    inputChange(data) {
      this.$forceUpdate()
      this.getPage.records[data.$rowIndex].printNum = data.row.printNum
    },
    _printResult(data) {
      console.log(data)
      if (data) {
        console.log('data.printerVal')
        this.printerVal = data.printerVal
        this._getLabelInfo()
      }
    },
    // 获取存储位置
    _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
      }
    },
    _getLocation(data) {
      const obj = {}
      if (data) {
        obj.storePlace = data
      }
      this.$store
        .dispatch('FoodSamplePreparation/getPositionList', obj)
        .then(() => {
          this.locationList = this.$store.state.FoodSamplePreparation.list
        })
    },
    // 单位
    _unitChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.unit = data
          break
        case 'query':
          this.currentRow.unit = data
          break
      }
    },
    // 多个参数查询
    // _dicSearch: async function() {
    //   const data = ['制备方式', '保存方式', '保存容器']
    //   const result = await soilSample.getDictList(data)
    //   if (result) {
    //     this.keepWayList = result
    //   }
    // },
    _getUserList: async function() {
      const result = await soilSample.getUserList()
      if (result) {
        console.log('result==============', result)
        for (let i = 0; i < result.records.length; i++) {
          this.preparerList.push(result.records[i].realname)
        }
        console.log(this.preparerList)
      }
    },
    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) {
      console.log('data', data)
      this._handleRow(handleObj)
      this.currentRow.prepareWay = data
    },
    _testItemChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      this.currentRow.resultState = data.name
    },
    _saveChange(msg, data, handleObj) {
      console.log('data', data)
      this._handleRow(handleObj)
      this.currentRow.keepWay = data
    },
    _preparerChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      this.currentRow.preparer = data
    },
    timeChange(data) {
      console.log(data)
      this.$forceUpdate()
      this.currentRow.prepareDate = data.prepareDate
      console.log(this.getPage.records)
    },
    _packSaveChange(msg, data, handleObj) {
      console.log('data', data)
      this._handleRow(handleObj)
      this.currentRow.keepContainer = data
    },
    _open(sampleIds) {
      this.$refs.pageTable._showLoading()
      this.sampleIds = sampleIds
      this.showModal = true
      this.getPage.records = []
      this.preparationWayData = []
      this.saveWayData = []
      this.packList = []
      this.unitData = []
      this.preparerList = []
      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._getPrepareWay()
      this._getkeepWayList()
      this._getkeepContainerList()
      this._getUserList()
    },
    _page: async function() {
      const result = await soilEntrust.preparePage({ ids: this.sampleIds })
      if (result) {
        this.getPage.records = result
        for (let j = 0; j < result.length; j++) {
          this.getPage.records[j].prepareDate = new Date(result[j].prepareDate)
          this.getPage.records[j].printNum = 1
        }
        this.$refs.pageTable._hideLoading()
      }
    },
    _getPrepareWay: async function() {
      const result = await soilSample.getDictList('制备方式')
      if (result) {
        for (let i = 0; i < result.length; i++) {
          this.preparationWayData.push(result[i].name)
        }
      }
    },
    _getkeepWayList: async function() {
      const result = await soilSample.getDictList('保存方式')
      if (result) {
        for (let i = 0; i < result.length; i++) {
          this.saveWayData.push(result[i].name)
        }
        console.log(this.saveWayData)
      }
    },
    _getkeepContainerList: async function() {
      const result = await soilSample.getDictList('保存容器')
      if (result) {
        for (let j = 0; j < result.length; j++) {
          this.packList.push(result[j].name)
        }
      }
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '仅流转微生物':
          this._changeMic()
          break
        case '制备完成':
          this._ok()
          break
      }
    },
    _cancel() {
      this.showModal = false
      this._hideLoading()
    },
    _ok() {
      this.$refs.pageTable._showLoading()
      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.$refs.pageTable._hideLoading()
        this._hideLoading()
        return false
      }
      this.save({ prepareList: prepareList })
    },
    save: async function(data) {
      this.$refs.pageTable._showLoading()
      const result = await soilEntrust.savePrepare(data)
      if (result) {
        this._resultChange('制备成功')
      }
    },
    _resultChange(msg) {
      this.showModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
      this._hideLoading()
      this.$refs.pageTable._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
      }
    },
    _getLabelInfo: async function() {
      console.log('this._getLabelInfo')
      const result = await soilStatistics._getLabel(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        for (let i = 0; i < result.records.length; i++) {
          if (result.records[i].type.display === '打印上机标签') {
            this.labelCode = result.records[i].code
          }
        }
        console.log(result)
      }
      this._printMessage()
    },
    _btnClick(msg) {
      switch (msg) {
        case '打印标签':
          if (this.selectData.length > 0) {
            // this._goto()
            this.$refs.selectPrint._open()
            // this._getLabelInfo()
            // this._printMessage()
          } else {
            this.$Message.warning('请至少选择一条数据')
          }
          break
        case '批量填写制备信息':
          this._writeInfo()
          break
        case '删除':
          this._deleteSelected()
          break
      }
    },
    _goto(methodId) {
      const routeData = this.$router.resolve({
        path: '/blank/item_by_method',
        query: { id: 123456 }
      })
      window.open(routeData.href, '_blank')
    },
    // 下载插件
    _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++) {
        for (let j = 0; j < data[i].printNum; j++) {
          this._printLabelOk(data[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()
          // LODOP.PRINT()
        }
      }
    },
    _printLabelOk(row) {
      LODOP.PRINT_INITA('') // 必须在设置打印机之前
      // 返回的标签代码
      // eslint-disable-next-line no-eval
      eval(this._replaceCodes(row))
      // 设置打印机
      LODOP.SET_PRINTER_INDEX(this.printerVal)
      // 打开设计模式
      // LODOP.PRINT_DESIGN()
      LODOP.PRINT()
    },
    _replaceCodes(row) {
      // /g表示全局替换
      let result = this.labelCode
      result = result.replace(
        /\$sampleCode\$/g,
        undefined !== row.sampleCode ? row.sampleCode : ''
      )
      result = result.replace(
        /\$groupId\$/g,
        undefined !== row.groupId ? row.groupId : ''
      )
      result = result.replace(
        /\$groupName\$/g,
        undefined !== row.groupName ? row.groupName : ''
      )
      result = result.replace(
        /\$prepareDate\$/g,
        undefined !== row.prepareDate ? this._formatDate(row.prepareDate) : ''
      )
      result = result.replace(/\$num\$/g, undefined !== row.num ? row.num : '')
      result = result.replace(/\$resultDateTemp\$/g, row.resultDateTemp)
      // 检测项目
      result = result.replace(
        /\$items\$/g,
        undefined !== row.specialItems ? row.specialItems : ''
      )
      // 二维码地址
      result = result.replace(
        /\$qrCode\$/g,
        undefined !== row.qrCode ? row.qrCode : ''
      )
      return result
    },
    // 时间戳转换方法    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>
