<template>
  <div>
    <Modal v-model="showModal" width="1010" class="modal-footer-none">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <!--内容-->
        <Row>
          <!--查询-->
          <Col span="24">
          <Form id="search-sample-company" v-show="searchOpen" :label-width="80" inline onsubmit="return false">
            <label class="label-sign"></label>
            <Form-item label="试样编号:" class="search-item">
              <Input v-model="formObj.sampleCode" @on-enter="_formSearch" placeholder="请输入样品编号" clearable />
            </Form-item>
            <Form-item label="现场编号:" class="search-item">
              <Input v-model="formObj.siteNo" @on-enter="_formSearch" placeholder="请输入现场编号" clearable />
            </Form-item>
            <Form-item class="search-btn">
              <Button @click="_page" type="primary">
                搜索
              </Button>
            </Form-item>
          </Form>
          </Col>
          <!--操作-->
          <Col span="24">
          <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" class="contHide" show-search-btn="true"></btn-list>
          </Col>
          <!-- 表格 -->
          <Col span="24">
            <PTVXETable ref="pageTable" :table-height="tableHeight" :form-id="formId" :loading="true"
                        :get-page="getPage" :icon-msg="iconMsg"  @on-result-change="_tableResultChange">
              <vxe-table-column
                v-for="item in pageColumns"
                :key="item.key"
                :field="item.key"
                :title="item.title"
                :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)">{{ scope.row[item.key] }}</a>
                </div>
                <div v-else-if="item.status">
                  {{ scope.row[item.key].display }}
                </div>
                <div v-else-if="item.date">
                  {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):'' }}
                </div>
                <span v-else>
                  {{ scope.row[item.key] }}
                </span>
              </template>
            </vxe-table-column>
          </PTVXETable>
          </Col>
        </Row>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>
    <SoilSampleItemManage ref="sampleItemManage" @on-result-change="_page"></SoilSampleItemManage>
  </div>
</template>
<script>
import http from '../../api/http'
import { soilEntrust } from '../../api'
import { getLodop } from '../../plugins/clodop/LodopFuncs'
import SoilSampleItemManage from './SoilSampleItemManageHis'
let LODOP
export default {
  components: { SoilSampleItemManage },
  data() {
    return {
      formId: 'soilSampleManage',
      currentComponent: '',
      btn: [
        {
          type: 'success',
          id: 'ZBC',
          name: '导入检测项目'
        }
      ],
      itemList: [],
      indexList: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '确定', type: 'primary' }
      ],
      iconMsg: [
        {
          type: 'ios-beaker',
          id: '',
          name: '管理检测项目'
        },
        { type: 'md-trash', id: '', name: '删除' }
      ],
      contractId: '', // 委托id
      showModal: false,
      recordHis: false,
      searchOpen: true,
      modalTitle: '管理样品',
      selectIds: [],
      selectData: {},
      getPage: {},
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 100, fixed: 'left' },
        { title: '试样深度', key: 'sampleDepth', width: 100 },
        { title: '现场编号', key: 'siteNo', width: 100 },
        { title: '试验项目', key: 'experimentNames' },
        { title: '土质描述', key: 'sampleDescribe', width: 150 },
        { title: '样品包装类型', key: 'samplePack', width: 120 }
      ],
      sampleId: '',
      dateList: [],
      formObj: {
        name: undefined,
        sampleCode: undefined
      }
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tableModal')
    }
  },
  methods: {
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '确定':
          this._ok()
          break
      }
    },
    _cancel() {
      this.showModal = false
    },
    _ok() {
      this.showModal = false
      this.$refs.footerModal._hideLoading()
      console.log(this.getPage)
    },
    _itemImportBack(data) {
      if (this.selectIds === undefined || this.selectIds.length === 0) {
        return false
      }
      if (data === undefined || data.length === 0) {
        return false
      }
      this._importItemOk({ sampleIds: this.selectIds, drugItemList: data })
    },

    // _importItemOk: async function(data) {
    //   const result = await drugSample.importSampleItemDTO(data)
    //   if (result) {
    //     this.$Message.success('导入成功！')
    //     await this._page()
    //   }
    // },

    _modalResult(data1, data2) {
      switch (this.currentComponent) {
        case 'CopyModal':
          if (data1 === 0) {
            this._copySample(data2)
          } else {
            this._copyAll(data2)
          }
          break
        default:
          this._search()
      }
    },
    _dateChange(data) {
      this.formObj.ctimeBegin = data[0]
      this.formObj.ctimeEnd = data[1]
    },
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '添加':
            this._editModal(false)
            break
          case '复制历史样品':
            this._copyHisSample()
            break
          case '导入样品':
            this._importSample()
            break
          case '导入检测项目':
            this._importItem()
            break
          case '导入检测项目包':
            this._importItemPackage()
            break
          case '打印标签':
            this._printLabel()
            break
          case '复制历史样品检测项目':
            this._copyHisItem()
            break
          case '删除':
            this._deleteSelected()
            break
          case '导出':
            this._exportSample()
            break
          case '添加模拟样品':
            this._editImitateModal(false)
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _exportSample() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条样品')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定导出这' + this.selectIds.length + '条样品',
          onOk: () => {
            http.open(
              '/food/v1/sample/company/export',
              { ids: this.selectIds.join(',') },
              '_blank'
            )
          }
        })
      }
    },
    _copyHisSample() {
      this.$refs.refModal._open(this.contractId)
    },

    _iconClick(res, data, componentName, index) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (res) {
          case '管理检测项目':
            this._itemManage(data.id)
            break
          case '编辑':
            this._editModal(true, data)
            break
          case '复制':
            this._copy(data)
            break
          case '删除':
            console.log(index)
            this._deleteById(data.id)
            break
          case '附件':
            this.$refs.refModal._open(data.id, 'sampleId')
            break
        }
      })
    },
    _itemManage(data) {
      // 管理检测项目
      if (this.recordHis) {
        this.$refs.sampleItemManage._openRecord(data)
      } else {
        this.$refs.sampleItemManage._open(data)
      }
    },
    _tableResultChange(msg, data) {
      const selectIds = []
      switch (msg) {
        case 'selectData':
          for (let i = 0; i < data.length; i++) {
            selectIds.push(data[i].id)
          }
          this.selectIds = selectIds
          this.selectData = data
          break
        case 'allSelect':
          console.log('123465798', data)
          this.allSelect(data)
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    allSelect(data) {
      this.indexList = []
      for (let i = 0; i < data.length; i++) {
        this.indexList.push(data[i].index)
      }
      console.log('索引', this.indexList)
    },
    _open(id) {
      this.formObj = this.$resetFields(this.formObj)
      this.dateList = []
      this.showModal = true
      this.contractId = id // 委托id
      console.log(this.contractId)
      this.$refs.pageTable._hideLoading()
      this._page()
    },
    _openHis(id) {
      this.formObj = this.$resetFields(this.formObj)
      this.dateList = []
      this.showModal = true
      this.contractId = id // 委托id
      console.log(this.contractId)
      this.$refs.pageTable._hideLoading()
      this.recordHis = true
      this._page()
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj.entrustId = this.contractId
      const result = await soilEntrust.samplePage(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          // this.$store.dispatch('FoodSample/deleteByIds', ids).then(() => {
          //   this._resultChange('删除成功!')
          // })
          this._deleteOk(ids)
        }
      })
    },

    // _deleteOk: async function(ids) {
    //   const result = await drugSample.deleteById(ids)
    //   if (result) {
    //     this._resultChange('删除成功')
    //   }
    // },

    _deleteById(id) {
      // 删除一条记录
      this._deleteByIds([id])
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '确定删除 ' + ids.length + ' 条记录？')
      }
    },
    _detailModal(data) {},
    _editModal(edit, data) {
      if (edit) {
        console.log(data)
        this.$refs.sampleManageEdit._open(data)
      } else {
        // 添加
        this.$refs.refModal._open('', this.contractId)
      }
    },
    // 添加编辑模拟样品
    _editImitateModal(edit, data) {
      if (edit) {
        // 模拟样品的编辑
        const tempData = JSON.parse(JSON.stringify(data)) // 深拷贝
        this.$refs.imitateModal._open(tempData, this.contractId)
      } else {
        // 模拟样品的添加
        this.$refs.imitateModal._open('', this.contractId)
      }
    },
    _search() {
      this._page()
    },
    _resultChange(msg) {
      this._page()
      this.$Message.success(msg)
    },
    _copy(data) {
      this.$refs.copyModal._open(data.id, data.type)
    },
    // 复制样品
    _copySample(data) {
      this.$store
        .dispatch('FoodSample/getByCompanyId', data.sampleId)
        .then(() => {
          const result = this.$store.state.FoodSample.companyModel
          if (data.type === 0) {
            // 普通样品
            this.currentComponent = 'FoodSampleCompanyEdit'
            this.$nextTick(function() {
              this.$refs.refModal._openCopySample(result)
            })
          } else if (data.type === 3) {
            // 模拟样品
            this.$refs.imitateModal._openCopySample(result)
          }
        })
    },
    _copyAll(data) {
      this.$store
        .dispatch('FoodSample/getByCompanyId', data.sampleId)
        .then(() => {
          const result = this.$store.state.FoodSample.companyModel
          if (data.type === 0) {
            // 普通样品
            this.currentComponent = 'FoodSampleCompanyEdit'
            this.$nextTick(function() {
              this.$refs.refModal._openCopyAll(result)
            })
          } else if (data.type === 3) {
            // 模拟样品
            this.$refs.imitateModal._openCopyAll(result)
          }
        })
    },
    // 导入样品
    _importSample() {
      const data = {
        importUrl: '/food/v1/sample/company/import_' + this.contractId,
        downloadUrl: '/food/v1/excel/template/FoodSampleCompany',
        title: '导入'
      }
      this.$refs.refModal._open(data)
    },
    // 导入检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.sampleItemModal._open()
        this.$refs.pageTable.checkedData()
      }
    },
    // 导入检测项目包
    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        // this.$refs.refModal._open(this.selectIds, 'sample-rel-package-item')
        this.$refs.itemPackageModal._open(
          this.selectIds,
          'sample-rel-package-item'
        )
      }
    },

    _printLabel() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        for (let m = 0; m < this.selectData.length; m++) {
          const row = this.selectData[m]
          this._printLabelOk(row)
        }
      }
    },

    _printLabelOk(row) {
      LODOP = getLodop()
      if (LODOP === 'undefined' || LODOP === undefined) {
        this._pluginDownload()
        return false
      }
      if (LODOP.GET_PRINTER_COUNT() === 0) {
        this.$Messager.warning('系统未关联打印机,请确认....')
        return false
      }

      LODOP.PRINT_INITA('0mm', '0mm', '70.01mm', '50.01mm', '样品标签打印')
      LODOP.ADD_PRINT_LINE(36, 15, 35, 251, 0, 1)
      LODOP.ADD_PRINT_LINE(74, 15, 73, 251, 0, 1)
      LODOP.ADD_PRINT_LINE(107, 15, 106, 251, 0, 1)
      LODOP.ADD_PRINT_LINE(140, 15, 139, 251, 0, 1)
      LODOP.ADD_PRINT_LINE(175, 15, 174, 251, 0, 1)
      LODOP.ADD_PRINT_LINE(35, 15, 174, 16, 0, 1)
      LODOP.ADD_PRINT_LINE(35, 74, 174, 75, 0, 1)
      LODOP.ADD_PRINT_LINE(35, 251, 174, 252, 0, 1)
      LODOP.ADD_PRINT_TEXT(49, 17, 59, 20, '样品名称')
      LODOP.ADD_PRINT_TEXT(82, 18, 59, 20, '样品编号')
      LODOP.ADD_PRINT_TEXT(116, 17, 59, 20, '样品状态')
      LODOP.ADD_PRINT_TEXT(151, 27, 39, 20, '备注')
      LODOP.ADD_PRINT_TEXT(16, 95, 100, 20, '检测样品标签')
      LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)
      LODOP.ADD_PRINT_TEXT(49, 78, 135, 20, row.name)
      LODOP.ADD_PRINT_TEXT(82, 77, 136, 20, row.sampleCode)
      LODOP.ADD_PRINT_TEXT(117, 76, 176, 20, '□未检 □在检 □已检 □留样')
      if (row.surplus === '取回') {
        LODOP.ADD_PRINT_TEXT(152, 77, 138, 20, '☑"取回 □服务方处理')
      } else if (row.surplus === '服务方处理') {
        LODOP.ADD_PRINT_TEXT(152, 77, 138, 20, '□取回 ☑服务方处理')
      } else {
        LODOP.ADD_PRINT_TEXT(152, 77, 138, 20, '□取回 □服务方处理')
      }

      LODOP.PRINT_DESIGN()
    },

    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    _operationRecord(id) {
      // 操作日志
      this.$refs.recordModal._open(id)
    }
  }
}
</script>
