<template>
  <div>
    <div>
      <!--内容-->
      <Row>
        <!--查询-->
        <Col span="24" style="padding-bottom: 5px">
          <Form id="search-wait-scan" :label-width="100" v-show="searchOpen" inline onsubmit="return false">
            <label class="label-sign"></label>
            <Form-item label="试样编号:" class="search-item">
              <Input @on-enter="_formSearch" v-model="formObj.sampleCode" name="sampleCode" placeholder="请输入样品编号" clearable></Input>
            </Form-item>
            <Form-item label="是否有试验项目:" class="search-item">
              <Select v-model="formObj.haveExp" clearable name="groupId" style="width:150px" placeholder="请选择是否有试验项目">
                <Option v-for="(item,index) in itemData" :value="item.value" :key="index">{{item.name}}</Option>
              </Select>
            </Form-item>
            <Form-item label="试验科室:" class="search-item">
              <el-select @change="_selGroup" v-model="formObj.groupId" placeholder="请选择" clearable style="width: 100%">
                <el-option
                  v-for="(item,index) in groupoptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </Form-item>
            <Form-item :label-width="150" label="试验项目/试验项目简写:" class="search-item">
              <Input v-model="formObj.experimentNames" @on-enter="_formSearch" style="width: 150px;" placeholder="请输入试验项目或试验项目简写" clearable />
            </Form-item>
            <Form-item class="search-btn" style="margin-left: 10px;">
              <Button type="primary" @click="_formSearch">搜索</Button>
            </Form-item>
          </Form>
        </Col>
        <Col span="24">
          <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" :show-search-btn="true" class="contHide">
            <!--<template slot="processTask">-->
            <!--<div class="fr process-task">-->
            <!--<Button @click="_exportReceiveRecord">导出交接记录</Button>-->
            <!--</div>-->
            <!--</template>-->
          </btn-list>
        </Col>
        <Col span="24">
          <PTVXETableHeight
            ref="pageTable"
            :tableHeight="tableHeight"
            @on-result-change="_tableResultChange"
            :getPage="getPage"
            :icon-msg="iconMsg"
            select-data>
            <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"
              sortable
            >
              <template slot-scope="scope">
                <div v-if="item.detail"><a @click.stop="_detailModal(scope.row.id)">{{scope.row[item.key]}}</a></div>
                <div v-else-if="item.key ==='shape'">{{scope.row['shape']}} {{scope.row['shapeRemark']}}</div>
                <div v-else-if="item.date">
                  {{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):''}}
                </div>
                <div v-else>{{scope.row[item.key]}}</div>
              </template>
            </vxe-table-column>
          </PTVXETableHeight>
        </Col>
      </Row>
    </div>
    <!--选择领样人-->
    <downloadPlugin ref="downloadPlugin"></downloadPlugin>
    <SelectPrinter ref="selectPrint" @on-result-change="_printResult"></SelectPrinter>
    <PrintNum ref="printNum" @on-result-change="_printNumResult"></PrintNum>
  </div>
</template>
<script>
import { soilAptitude, soilEntrust, soilStatistics } from '../../../../api'
import SelectPrinter from '../../sample-preparation/SelectPrinter'
import { getLodop } from '../../../../plugins/clodop/LodopFuncs'
import downloadPlugin from '../../../../plugins/download/downloadPlugin'
import PrintNum from './PrintNum'
let LODOP
export default {
  components: { PrintNum, SelectPrinter, downloadPlugin },
  data() {
    return {
      btn: [
        { type: 'primary', id: '', name: '发放' },
        { type: 'primary', id: '', name: '发放到高级试验' },
        { type: 'primary', id: '', name: '打印标签' }
      ],
      selectIds: [],
      getPage: {},
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 100, fixed: 'left' },
        { title: '试样深度', key: 'sampleDepth', width: 95 },
        { title: '现场编号', key: 'siteNo', width: 100 },
        { title: '试验项目', key: 'experimentNames', width: 225 },
        { title: '试验项目简写', key: 'experimentShortNames' },
        { title: '土质描述', key: 'sampleDescribe', width: 185 },
        { title: '样品包装类型', key: 'samplePack', width: 120 }
      ],
      iconMsg: [{ type: 'md-cloud-download', id: '', name: '导出样品交接单' }],
      type: '',
      contractId: '', // 合同id
      selectData: [],
      currentComponent: '',
      formObj: {
        samplingNum: '',
        name: '',
        num: '',
        detectType: '',
        standard: '',
        samplingLinkList: [],
        haveExp: undefined,
        groupName: undefined,
        groupId: undefined,
        experimentNames: undefined
      },
      stdList: [],
      groupoptions: [],
      sampleLinkList: [
        { value: 0, name: '食品生产' },
        { value: 1, name: '食品流通' },
        { value: 2, name: '餐饮服务' },
        { value: 3, name: '食用农产品' },
        { value: 4, name: '生产' },
        { value: 5, name: '流通' },
        { value: 6, name: '餐饮' }
      ],
      itemData: [
        {
          name: '是',
          value: 1
        },
        {
          name: '否',
          value: 0
        }
      ],
      searchOpen: true,
      acceptSelectUserValue: ''
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
      } else {
      }
      return this.$tableHeight('tableModal')
    }
  },
  mounted() {},
  methods: {
    _selectSampleLink(data) {
      console.log(data)
    },
    _selGroup(data) {
      console.log(data)
      this.formObj.groupId = data
    },
    _getGroupList: async function() {
      const result = await soilAptitude.getGroupList()
      if (result) {
        this.groupoptions = result
      }
    },
    // 组件返回值
    _componentResult(data, msg) {
      switch (this.currentComponent) {
        case 'SelectPrinter':
          this._printerResult(data)
          break
        case 'ReceiveScan':
          // 扫码接收
          this._searchTop()
          break
        default:
          this._search()
      }
    },
    _open(contractId, type) {
      this.formObj = this.$resetFields(this.formObj)
      $('input[name=contractId]').val(contractId)
      this.entrustId = contractId
      this.type = type
      this.selectIds = []
      this._getGroupList()
      this.$nextTick(() => {
        this._page()
      })
    },
    _page: async function() {
      this.selectData = []
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj.entrustId = this.entrustId
      const result = await soilEntrust.pageSend(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _iconClick(res, data, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (res) {
          case '编辑':
            this._editModal(true, data)
            break
          case '导出样品交接单':
            console.log(data)
            break
          case '复制':
            this._copySample(data)
            break
          case '操作日志':
            this.$refs.refModal._open(data.id)
            break
          case '删除':
            this._deleteById(data.id)
            break
          case '附件':
            this.$refs.refModal._open(data.id, 'sampleId')
            break
        }
      })
    },
    _btnClick(msg, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (msg) {
          case '发放':
            this._submitSend()
            break
          case '发放到高级试验':
            this._send()
            break
          case '扫码发放':
            this._oneKeySend()
            break
          case '导入检测项目':
            this._importItem()
            break
          case '导入检测项目包':
            this._importItemPackage()
            break
          case '复制历史样品检测项目':
            this._copyHisItem()
            break
          case '接收':
            this._sampleReceive()
            break
          // case '打印标签':
          //   this._selectPrinter('print-label')
          //   break
          case '打印标签':
            if (this.selectData.length > 0) {
              this.$refs.selectPrint._open()
            } else {
              this.$Message.warning('请至少选择一条数据')
            }
            break
          case '自定义打印':
            if (this.selectData.length === 0) {
              this.$Message.warning('请至少选择一条数据')
            } else {
              this._cusTomePrint()
            }
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _pluginDownload() {
      this.$refs.downloadPlugin._open()
    },
    _printResult(data) {
      console.log(data)
      if (data) {
        console.log('data.printerVal')
        this.printerVal = data.printerVal
        this.$refs.printNum._open()
        // this._getLabelInfo()
      }
    },
    _printNumResult(data) {
      this.printNum = data
      this._getLabelInfo()
    },
    _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()
    },
    _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 < this.printNum; j++) {
          this._printLabelOk(data[i])
        }
      }
    },
    _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(
        /\$sampleDepth\$/g,
        undefined !== row.sampleDepth ? row.sampleDepth : ''
      )
      result = result.replace(
        /\$receiver\$/g,
        undefined !== row.receiver ? row.receiver : ''
      )
      result = result.replace(
        /\$receiveTime\$/g,
        undefined !== row.receiveTime ? this._formatDate(row.receiveTime) : ''
      )
      result = result.replace(
        /\$entrustCode\$/g,
        undefined !== row.entrustCode ? row.entrustCode : ''
      )
      // 检测项目
      result = result.replace(
        /\$experimentNames\$/g,
        undefined !== row.experimentNames ? row.experimentNames : ''
      )
      // 二维码地址
      result = result.replace(
        /\$qrCode\$/g,
        undefined !== row.qrCode ? row.qrCode : ''
      )
      return result
    },
    _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
    },
    // 扫码发放
    _oneKeySend() {
      if (this.selectIds.length === 0) {
        this.$msgTip('warning', '请至少选择一条数据！')
      } else {
        // 扫码发放判断是否选人
        // eslint-disable-next-line no-lonely-if
        if (this.acceptSelectUserValue === '是') {
          this.$refs.userModal._open('sampleScanSend', '请选择领样人')
        } else {
          // 扫码发放
          this.$refs.refModal._open('扫码发放')
        }
      }
    },
    // 发放
    _submitSend() {
      if (this.selectIds.length === 0) {
        this.$message.warning('请至少选择一条数据！')
      } else {
        // 一键发放判断是否选人
        // eslint-disable-next-line no-lonely-if
        if (this.acceptSelectUserValue === '是') {
        } else {
          const data = {
            ids: this.selectIds.join(',')
          }
          this.$Modal.confirm({
            title: '提示',
            content: '确定要发放这 ' + this.selectIds.length + ' 条数据？',
            onOk: () => {
              this._sendSample(data)
            }
          })
        }
      }
    },
    _sendSample: async function(data) {
      const result = await soilEntrust.sendSample(data)
      if (result) {
        this._resultChange('发放成功')
      }
    },
    _send() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this._sendToAlone()
      }
    },
    _sendToAlone() {
      if (this.selectIds.length === 0) {
        this.$message.warning('请至少选择一条数据！')
      } else {
        const data = {
          ids: this.selectIds.join(',')
        }
        this.$Modal.confirm({
          title: '提示',
          content: '确定要发放这 ' + this.selectIds.length + ' 条数据？',
          onOk: () => {
            this._sendAloneKeep(data)
          }
        })
      }
    },
    _sendAloneKeep: async function(data) {
      const result = await soilEntrust.aloneKeepSample(data)
      if (result) {
        this._resultChange('发放成功')
      }
    },
    _resultChange(msg) {
      this._page()
      this.$Message.success(msg)
      this.selectIds = []
    },

    _exportReceiveRecord() {
      // 导出交接记录
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择数据进行导出')
      } else {
        // eslint-disable-next-line no-undef
        http.open(
          '/food/report/excel/sheet?_u=db样品来源.report.xml&ids=' + ids
        )
      }
    },

    _deleteById(id) {
      // 删除一条记录
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该记录？',
        onOk: () => {}
      })
    },
    _search() {
      this._page()
    },
    // 刷新上级页面
    _searchTop() {
      this._page()
      this.$emit('on-result-change')
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this.getPage = this.$store.state.FoodSample.page
          break
        case 'selectData':
          this.selectData = data
          this.selectIds = []
          for (let i = 0; i < data.length; i++) {
            this.selectIds.push(data[i].id)
          }
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'changeSize':
          this._page()
          break
      }
    },

    // 导入检测项目包
    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectIds)
        })
      }
    },
    // 导入检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectIds, this.selectData[0])
        })
      }
    },
    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectIds)
        })
      }
    },
    // 选择打印机
    _selectPrinter(msg) {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$refs.refModal._open(msg)
      }
    },
    // 选择完打印机之后
    _printerResult(data) {
      // printModal  不能使用动态组件，否则第二次打不开，原因未知
      switch (data.type) {
        // 打印标签--直接打印
        case 'print-label':
          this.$refs.printModal._printOpen(this.selectData, data.printerVal)
          break
      }
    },
    _stdResult(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.standard = data
          break
        case 'query':
          this.formObj.standard = data
          this._getStdList(data)
          break
        case 'focus':
          this._getStdList()
          break
      }
    }
  }
}
</script>
