<template>
  <div>
    <Row>
      <!--查询-->
      <Col span="24">
      <Form
        v-show="searchOpen"
        id="consult-sample-form"
        inline
        onsubmit="return false"
        :label-width="90"
        class="search-form"
      >
        <label class="label-sign" />
        <Form-item class="search-item" label="样本编号:">
          <Input name="sampleCode" placeholder="请输入样本编号" clearable @on-enter="_formSearch" />
        </Form-item>
        <Form-item class="search-item" label="牌号:">
          <Input name="name" placeholder="请输入牌号" clearable @on-enter="_formSearch" />
        </Form-item>
        <Form-item class="search-item" label="生产日期:">
          <Date-picker
            ref="pcTime"
            type="datetimerange"
            placeholder="生产日期"
            style="width: 100%;"
            :editable="false"
            transfer
            @on-change="_histDateChange"
          />
          <input type="hidden" name="pcTimeBegin">
          <input type="hidden" name="pcTimeEnd">
        </Form-item>
        <!--<Form-item class="search-item" label="报检单位:">-->
        <!--<Input name="declarationInspection" placeholder="请输入报检单位" clearable @on-enter="_formSearch" />-->
        <!--</Form-item>-->

        <Form-item class="search-item" label="样品接收人:">
          <Input name="receiver" placeholder="请输入样品接收人" clearable @on-enter="_formSearch" />
        </Form-item>
        <Form-item class="search-item" label="样品接收时间:">
          <Date-picker
            ref="receiveTime"
            type="datetimerange"
            placeholder="样品接收时间"
            style="width: 100%;"
            :editable="false"
            transfer
            @on-change="_receiveTimeChange"
          />
          <input type="hidden" name="receiveTimeBegin">
          <input type="hidden" name="receiveTimeEnd">
        </Form-item>
        <Form-item class="search-btn">
          <Button type="primary" @click="_formSearch">
            搜索
          </Button>
        </Form-item>
      </Form>
      </Col>
      <!--按钮-->
      <Col span="24">
      <btn-list :msg="btn" :open="searchOpen" show-search-btn="true" @on-result-change="_btnClick" />
      </Col>
      <!--table-->
      <Col span="24">
      <element-table
        id="testBasisTable"
        ref="pageTable"
        :page-columns="pageColumns"
        :table-height="tableHeight"
        :get-page="getPage"
        :opt-col-width="140"
        :icon-msg="iconMsg"
        show-check-box
        @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"
          :width="item.width"
          :min-width="200"
          :fixed="item.fixed?item.fixed:undefined"
        >
          <template slot-scope="scope">
            <div v-if="item.dateTime">
              {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM:ss'):'' }}
            </div>
            <div v-else>
              {{ scope.row[item.key] }}
            </div>
          </template>
        </el-table-column>
      </element-table>
      </Col>
    </Row>
    <!--添加编辑-->
    <fileManage ref="fileManageModal" @on-result-change="_fileResult" />
    <!--操作日志-->
    <sampleRecord ref="recordModal" />
    <!--检测项目-->
    <sampleItemList ref="testItemModal" @on-result-change="_formSearch" />
  </div>
</template>
<script>
import { drugSample } from '../../api'
import global from '../../api/config'
import fileManage from '../base-manage/fileManage'
import sampleRecord from '../record/sampleRecord'
import sampleItemList from './SampleItemList'
export default {
  components: { fileManage, sampleItemList, sampleRecord },
  data() {
    return {
      searchOpen: true,
      formObj: {
        code: '',
        name: ''
      },
      selectIds: [],
      btn: [
        // { type: 'success', id: '', name: '添加' },
        // { type: 'error', id: '', name: '删除' },
        // { type: 'primary', id: '', name: '导入' },
        // { type: 'primary', id: '', name: '导出' }
      ],
      pageColumns: [
        {
          title: '样本编号',
          key: 'sampleCode',
          width: 200,
          fixed: 'left',
          align: 'center'
        },
        { title: '牌号', key: 'name', width: 200, align: 'center' },
        {
          title: '样品接收时间',
          key: 'receiveTime',
          align: 'center',
          datetime: true
        },
        {
          title: '样品接收人',
          key: 'receiver',
          align: 'center'
        },
        { title: '价类', key: 'category', width: 150, align: 'center' },
        {
          title: '生产日期',
          key: 'pcTime',
          align: 'center',
          datetime: true
        }
      ],
      getPage: {},
      iconMsg: [
        { type: 'pt-a-download-outline', id: '', name: '下载' },
        { type: 'pt-a-cloud', id: '', name: '附件' },
        { type: 'pt-a-chemistry', id: '', name: '查看检测项目' },
        { type: 'pt-a-clock', id: '', name: '操作日志' }
      ]
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('search')
      } else {
        return this.$tableHeight('noSearch')
      }
    }
  },
  mounted() {
    this._page()
  },
  methods: {
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      const data = this.$serialize('consult-sample-form')
      Object.assign(data, this.$refs.pageTable._searchParams())
      const result = await drugSample.pageReportConsult(data)
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _searchParams(formId) {
      return this.$refs.pageTable._searchParams(formId)
    },
    _btnClick(msg, data) {
      switch (msg) {
        case '添加':
          this.$refs.editModal._open()
          break
        case '删除':
          this._deleteByIds()
          break
        case '导出':
          if (this.getPage.records.length === 0) {
            this.$Message.warning('暂无数据，不可导出！')
          } else {
            this._export()
          }
          break
        case 'search':
          this.searchOpen = !this.searchOpen
          break
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
        case 'selectIds':
          this.selectIds = data
          break
      }
    },
    _iconClick(res, data) {
      switch (res) {
        case '删除':
          this._deleteById(data.id)
          break
        case '下载':
          this._downloadByIds(data.id)
          break
        case '附件':
          this._uploadByIds(data.id)
          break
        case '查看检测项目':
          this._testItem(data.id)
          break
        case '操作日志':
          this._record(data.id)
          break
      }
    },
    // 操作日志
    _record(id) {
      this.$refs.recordModal._open(id)
    },
    // 检测项目
    _testItem(id) {
      this.$refs.testItemModal._open(id)
    },
    _uploadByIds(id) {
      const tempData = {
        id: id,
        uploadFileUrl: '/v1/sample_annex/upload/',
        downloadFileUrl: '/v1/sample_annex/download/'
      }
      this.$refs.fileManageModal._open(tempData, 'sampleId')
    },

    // 文件返回的数据
    _fileResult(msg, data) {
      switch (msg) {
        case 'file-page':
          this.$refs.fileManageModal._openFile(data)
          break
        case 'delete-page':
          this.$refs.fileManageModal._delPage('', data)
          break
        case 'success':
          this.$Message.success('删除成功！')
          this.$refs.fileManageModal._page()
          break
        default:
          this.$refs.fileManageModal._page()
      }
    },
    _downloadByIds(id) {
      if (undefined === id) {
        this.$Message.warning('请至少选择一条数据!')
      } else {
        this._download(id, `确定要下载吗?`)
      }
    },

    _download(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定要下载报告?',
        onOk: () => {
          window.open(
            global.baseURL + '/v1/sample_report/download/' + ids,
            '_blank'
          )
        }
      })
    },

    // 删除
    _deleteById(id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该数据？',
        onOk: () => {
          this._deleteOk(id)
        }
      })
    },
    _deleteByIds() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定删除 ' + ids.length + ' 条记录？',
          onOk: () => {
            this._deleteOk(ids)
          }
        })
      }
    },
    _deleteOk: async function(id) {
      const result = await drugSample.deleteById(id)
      if (result) {
        this.$Message.success('删除成功')
        this._page()
      }
    },
    _editModal: async function(id) {
      const result = await drugSample.getById(id)
      if (result) {
        this.$refs.editModal._open(result)
      }
    },
    _export: async function() {
      const result = await drugSample.page(this._searchParamsTemp())
      // 导出全部数据
      if (!result) {
        return
      }
      this.$Modal.confirm({
        title: '提示',
        content: '确定导出全部数据（最多导出5000条）？',
        onOk: () => {
          this.$exportExcel(
            'testBasisTable',
            '检测依据',
            this.pageColumns,
            result.records
          )
        }
      })
    },

    _histDateChange(data) {
      $('input[name="pcTimeBegin"]').val(data[0])
      $('input[name="pcTimeEnd"]').val(data[1])
    },
    _receiveTimeChange(data) {
      $('input[name="receiveTimeBegin"]').val(data[0])
      $('input[name="receiveTimeEnd"]').val(data[1])
    },

    // 参数
    _searchParamsTemp: function() {
      const data = this.$serializeForm(this.formObj)
      return this.$extend(data, { page: 1, rows: 5000 })
    }
  }
}
</script>
