<template>
  <div>
    <Row>
      <Form
        id="lab-sample-form-his"
        v-show="searchOpen"
        :label-width="70"
        inline
        onsubmit="return false"
        class="search-form"
      >
        <label class="label-sign" />
        <Form-item class="search-item" label="委托方:">
          <Input @on-enter="_formSearch" name="client" placeholder="请输入委托方" clearable />
        </Form-item>
        <Form-item class="search-item" label="委托编号:">
          <Input @on-enter="_formSearch" name="entrustCode" placeholder="请输入委托编号" clearable />
        </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 @click="_formSearch" type="primary">
            搜索
          </Button>
        </Form-item>
      </Form>
      <Col span="24">
      <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" style="height: 30px;" show-search-btn="true" />
      </Col>
<!--      <Button type="primary" @click="_submitReportCheck">-->
<!--        提交-->
<!--      </Button>-->
      <Col span="24">
        <PTVXETable
          ref="pageTable"
          :tableHeight="tableHeight"
          :getPage="getPage"
          :iconMsg="iconMsg"
          @on-result-change="_tableResultChange"  select-data>
          <vxe-table-column
            v-for="item in pageColumns"
            :key="item.key"
            :field="item.key"
            :title="item.title"
            :min-width="100"
            :width="item.width"
            :fixed="item.fixed?item.fixed:undefined"
            sortable
          >
            <template slot-scope="scope">
              <a @click.stop="_detailModal(scope.row.id,scope.row.type)"
                 v-if="item.detail">{{scope.row[item.key]}}</a>
              <div v-else-if="item.type">{{scope.row[item.key]?'政府':'企业'}}</div>
              <div v-else-if="item.date">{{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'): ''}}
              </div>
              <div v-else-if="item.key==='havePhoto'">{{scope.row[item.key]===1?'是':
                scope.row[item.key]===0?'否':''}}
              </div>
              <div v-else-if="item.status">
                <span v-if="scope.row[item.key].display === '报告审核退回'||'报告签发退回' ===scope.row[item.key].display " style="color: red;">{{ scope.row[item.key] === undefined ? '': scope.row[item.key].display }}</span>
                <span v-else>{{ scope.row[item.key] === undefined ? '': scope.row[item.key].display }}</span>
              </div>
              <div v-else-if="item.judge">
                {{Number(scope.row[item.key]) === 0? '否':'是'}}
              </div>
              <div v-else>{{scope.row[item.key]}}</div>
            </template>
          </vxe-table-column>
        </PTVXETable>
      </Col>
    </Row>
    <fileManage ref="FileManage" @on-result-change="_fileResult" />
    <OperationModal ref="operationModal" />
  </div>
</template>

<script>
// eslint-disable-next-line import/named
import {
  soilEntrust,
  soilReport,
  soilSample,
  soilStatistics
} from '../../../../api'
import global from '../../../../api/config'
import OperationModal from '../../../../components/operation/Operation'
export default {
  name: 'PreparationManage',
  components: { OperationModal },
  data() {
    return {
      name: '',
      pageColumns: [
        {
          title: '委托商',
          key: 'client',
          width: 100,
          fixed: 'left'
        },
        { title: '委托编号', key: 'entrustCode', width: 100 },
        { title: '报告编号', key: 'reportCode', width: 100 },
        { title: '进度', key: 'progress', width: 110, status: true },
        { title: '状态', key: 'status', width: 100, status: true },
        { title: '委托日期', key: 'entrustDate', width: 100, date: true },
        { title: '钻孔位置', key: 'boreholeLocation', width: 100 },
        { title: '钻孔名称', key: 'boreholeName', width: 100 },
        { title: '水深', key: 'waterDepth', width: 100 },
        { title: '制表人', key: 'tabulater', width: 110 },
        { title: '制表日期', key: 'tabulateDate', width: 110, date: true }
      ],
      btn: [
        // { id: 'env-report-make-submit', type: 'primary', name: '提交' },
        // { id: '', type: 'primary', name: '生成' },
      ],
      getPage: {},
      searchOpen: false,
      currentIndex: '',
      selectIds: [],
      selectData: [],
      iconMsg: [
        { id: 'issue-report-his', type: 'md-image', name: '预览报告' },
        // { id: '', type: 'ios-cloud', name: '项目报告' },
        { id: 'issue-upload-his', type: 'ios-cloud', name: '附件' },
        { id: 'issue-record-his', type: 'ios-clock', name: '操作日志' },
        { id: 'issue-delete-his', type: 'md-trash', 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-his')
      Object.assign(data, this.$refs.pageTable._searchParams())
      const result = await soilReport.pageReportIssueHis(data)
      if (result) {
        this.getPage = result
        this.$refs.pageTable._hideLoading()
      }
    },
    _clearPage() {
      $('#lab-sample-form-his')
        .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 soilStatistics.submitReportCheck(ids)
      if (result) {
        this._resultChange('提交成功!')
      }
    },
    _submitReportCheck() {
      const data = this.selectData
      if (data.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
        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 soilStatistics.submitEntrustReportCheck(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_report/' + ids,
            '_blank'
          )
        }
      })
    },
    _iconClick(name, data) {
      switch (name) {
        case '提交':
          this._receiveByIds(data.id)
          break
        case '附件':
          this._uploadByIds(data.id)
          break
        case '预览报告':
          this._viewReport(data)
          break
        case '预览PDF':
          this._viewPDF(data)
          break
        case '操作日志':
          this._record(data.id)
          break
        case '删除':
          this._deleteByIds([data.id])
          break
      }
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          this._delete(ids)
        }
      })
    },
    _delete: async function(ids) {
      const result = await soilEntrust.deleteById(ids)
      if (result) {
        this._formSearch()
        this.$Message.success('删除成功！')
      }
    },
    // 没有生成pdf先生成在预览
    _viewPDF(data) {
      console.log(data)
      if (data.pdfObjectKey) {
        this.$pdfView(data.pdfObjectKey)
      } else {
        console.log(123456)
        // window.open(
        //   'http://api.pertest.patzn.com/food/v1/sample_report/generate_pdf_auto?id=' +
        //     data.id
        // )
        // this.autoPdf(data)
        // window.open(
        //   global.baseURL +
        //     '/food/v1/sample_report/generate_pdf_auto?id=' +
        //     data.id
        // )
      }
    },
    _viewReport(data) {
      this._getObjectKey(data)
    },
    _record(id) {
      this.$refs.operationModal._open(id)
    },
    _getObjectKey: async function(data) {
      const result = await soilSample.getReport(data.id)
      if (result) {
        this.$openWindowModeless({
          objectKey: result.objectKey,
          id: data.id,
          isReport: 4,
          idType: 11
        })
      }
    },

    _uploadByIds(id) {
      this.$refs.FileManage._open(id, 'entrustId')
    },
    // 文件返回的数据
    _fileResult(msg, data) {
      switch (msg) {
        case 'file-page':
          this.$refs.FileManage._openFile(data)
          break
        case 'delete-page':
          this.$refs.FileManage._delEntrustPage('', data)
          break
        case 'success':
          this.$Message.success('删除成功！')
          this.$refs.FileManage._pageEntrust()
          break
        default:
          this.$refs.FileManage._pageEntrust()
      }
    },
    _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
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          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>
