<template>
  <div>
    <Row>
      <Form
        v-show="searchOpen"
        id="lab-sample-form"
        inline
        onsubmit="return false"
        :label-width="70"
        class="search-form"
      >
        <label class="label-sign" />
        <Form-item class="search-item" label="样本编号:">
          <Input name="sampleNum" 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="sampleTime"
            type="datetimerange"
            placeholder="报检时间"
            style="width: 100%;"
            :editable="false"
            transfer
            @on-change="_labSampleTime"
          />
          <input type="hidden" name="inspectionDateBegin">
          <input type="hidden" name="inspectionDateEnd">
        </Form-item>
        <Form-item class="search-btn">
          <Button type="primary" @click="_formSearch">
            搜索
          </Button>
        </Form-item>
      </Form>
      <Col />
      <Button type="primary" @click="_submitReportMake">
        提交
      </Button>
      <Button type="primary" @click="_createReport">
        生成
      </Button>
      <Button @click="_downloadByIds">下载</Button>
      </Col>
      <Col />
      <element-table
        ref="pageTable"
        :page-columns="pageColumns"
        :table-height="tableHeight"
        :get-page="getPage"
        show-check-box
        select-data
        @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"
          :align="item.align"
          :width="item.width"
          :min-width="200"
          :fixed="item.fixed?item.fixed:undefined"
        >
          <template slot-scope="scope" @click.stop="_handleIndex(scope)">
            <span v-if="item.datetime">
              {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM:ss'):'' }}
            </span>
            <div v-else-if="item.status">
              {{ scope.row[item.key] === undefined ? '': scope.row[item.key].display }}
            </div>
            <span v-else>
              {{ scope.row[item.key] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          slot="col"
          label="操作"
          align="center"
          :width="120"
          fixed="right"
        >
          <template slot-scope="scope">
            <icon-list
              :msg="iconMsg"
              :row-data="scope.row"
              :row-index="scope.$index"
              @on-result-change="_iconClick"
            />
          </template>
        </el-table-column>
      </element-table>
      </Col>
    </Row>

    <createReport ref="createReportModal" />

    <fileManage ref="fileManageModal" @on-result-change="_fileResult" />
  </div>
</template>

<script>
import { drugSample } from '../../../api'
import createReport from '../createReport'
import fileManage from '../../base-manage/fileManage'
import global from '../../../api/config'
export default {
  name: 'PreparationManage',
  components: { createReport, fileManage },
  data() {
    return {
      name: '',
      pageColumns: [
        {
          title: '样本编号',
          key: 'sampleCode',
          width: 200,
          fixed: 'left',
          align: 'center'
        },
        { title: '物料名称', key: 'name', width: 200, align: 'center' },
        {
          title: '状态',
          key: 'progress',
          width: 200,
          status: true,
          align: 'center'
        },
        { title: '报告是否生成', key: 'reported', width: 200, align: 'center' },
        {
          title: '送样人接收时间',
          key: 'sendTime',
          align: 'center',
          datetime: true
        },
        { title: '检测类型', key: 'category', width: 200, align: 'center' },
        { title: '物品编号', key: 'code', width: 200, align: 'center' },
        {
          title: '请检时间',
          key: 'pcTime',
          align: 'center',
          datetime: true
        },
        { title: '送样人', key: 'sender', align: 'center' }
      ],
      btn: [
        { id: 'env-report-make-submit', type: 'primary', name: '提交' },
        { id: '', type: 'primary', name: '生成' },
        { id: '', type: 'primary', name: '下载' }
      ],
      getPage: {},
      searchOpen: false,
      currentIndex: '',
      selectIds: [],
      selectData: [],
      iconMsg: [
        { id: '', type: 'pt-a-download-outline', name: '提交' },
        { id: '', type: 'pt-a-cloud', name: '附件' }
        // { id: '', type: 'md-egg', name: '操作日志' }
      ]
    }
  },
  computed: {
    tableHeight() {
      if (this.searchOpen) {
        return this.$tableHeight('tabSearch')
      } else {
        return this.$tableHeight('tabNoSearch')
      }
    }
  },
  methods: {
    async _page() {
      const data = this.$serialize('lab-sample-form')
      Object.assign(data, this.$refs.pageTable._searchParams())
      const result = await drugSample.pageReportMake(data)
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _clearPage() {
      $('#lab-sample-form')
        .find('input')
        .each(function() {
          $(this).val('')
        })
      this.$refs.sampleTime.handleClear()
    },
    _btnClick(msg, data) {
      switch (msg) {
        case '扫码接收':
          this._scanReceive()
          break
        case '手动接收':
          this._sampleReceive()
          break
        case 'search':
          this.searchOpen = !this.searchOpen
          break
      }
    },
    _scanReceive() {
      this.$refs.receiveModal._open()
    },
    _sampleReceive() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
      } else {
        this._receiveByIds(ids, `确认要接收 ${ids.length} 条数据吗?`)
      }
    },
    _receiveByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || `确定要处理该条数据吗?`,
        onOk: () => {
          this._receiveIds(ids)
        }
      })
    },
    async _receiveIds(ids) {
      const result = await drugSample.submitReportMake(ids)
      if (result) {
        this._resultChange('提交成功!')
      }
    },
    _submitReportMake() {
      const data = this.selectData
      if (data.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
        return false
      }
      for (let i = 0; i < data.length; i++) {
        if (data[i].reported === '否') {
          this.$Message.warning(
            '样品编号为' + data[i].sampleCode + '的样品报告暂未生成不能提交'
          )
          return false
        }
      }

      this._submitByIds(
        this.selectIds,
        `确定要提交 ${this.selectIds.length} 条数据吗?`
      )
    },

    _submitByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || `确定要提交该条数据吗?`,
        onOk: () => {
          this._submit(ids)
        }
      })
    },

    // 接口异步
    _submit: async function(ids) {
      if (ids.length === 0) return false
      const result = await drugSample.submitReportMake(ids)
      if (result) {
        this.$Message.success('提交成功!')
        this._formSearch()
      }
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this._formSearch()
    },

    _createReport() {
      console.log(this.currentComponent)
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
      } else {
        this.$refs.createReportModal._open(this.selectData)
      }
    },

    _downloadByIds() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
      } else {
        this._download(
          this.selectIds,
          `确定要下载 ${this.selectIds.length} 条数据吗?`
        )
      }
    },

    _download(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定要下载报告?',
        onOk: () => {
          window.open(
            global.baseURL + '/v1/sample_report/download/' + ids,
            '_blank'
          )
        }
      })
    },
    _iconClick(name, data) {
      switch (name) {
        case '提交':
          this._receiveByIds(data.id)
          break
        case '附件':
          this._uploadByIds(data.id)
          break
      }
    },
    _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()
      }
    },
    _handleIndex(data) {
      this.currentIndex = data.$index
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'selectIds':
          this.selectIds = data
          break
        case 'selectData':
          this.selectData = data
          this.selectIds = []
          for (let i = 0; i < this.selectData.length; i++) {
            this.selectIds.push(this.selectData[i].id)
          }
          break
        default:
          this._page()
      }
    },
    _labSampleTime(data) {
      $('input[name="inspectionDateBegin"]').val(data[0])
      $('input[name="inspectionDateEnd"]').val(data[1])
      console.log(data)
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    }
  }
}
</script>

<style scoped>
</style>
