<template>
  <div>
    <Row>
      <Form
        v-show="searchOpen"
        id="lab-sample-form"
        :label-width="70"
        inline
        onsubmit="return false"
        class="search-form"
      >
        <label class="label-sign" />
        <Form-item class="search-item" label="委托方:">
          <Input name="client" placeholder="请输入委托方" clearable @on-enter="_formSearch" />
        </Form-item>
        <Form-item class="search-item" label="委托编号:">
          <Input name="entrustCode" placeholder="请输入委托编号" clearable @on-enter="_formSearch" />
        </Form-item>
        <Form-item class="search-btn">
          <Button type="primary" @click="_formSearch">
            搜索
          </Button>
        </Form-item>
      </Form>
      <Col span="24">
      <btn-list :msg="btn" :open="searchOpen" show-search-btn="true" @on-result-change="_btnClick" />
      </Col>
      <Col span="24">
      <PTVXETable
        ref="pageTable"
        :page-columns="pageColumns"
        :table-height="tableHeight"
        :get-page="getPage"
        :icon-msg="iconMsg"
        show-check-box
        select-data
        @on-result-change="_tableResultChange"
      >
        <vxe-table-column
          v-for="item in pageColumns"
          :key="item.key"
          :field="item.key"
          :title="item.title"
          :width="item.width"
          :min-width="200"
          :fixed="item.fixed?item.fixed:undefined"
          sortable
        >
          <template slot-scope="scope" @click.stop="_handleIndex(scope)">
            <span v-if="item.date">
              {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):'' }}
            </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>
        </vxe-table-column>
      </PTVXETable>
      </Col>
    </Row>
    <fileManage ref="FileManage" @on-result-change="_fileResult" />
    <Reason ref="reasonModal" @on-result-change="_reasonResult" />
    <SoilGroupExpReportMake ref="soilGroupExpReportMakeModal" @on-result-change="_page" />
    <OperationModal ref="operationModal" />
  </div>
</template>

<script>
// eslint-disable-next-line import/named
import { soilSample, soilStatistics } from '../../../../api'
import global from '../../../../api/config'
import Reason from '../../../../components/base/Reason'
import OperationModal from '../../../../components/operation/Operation'
import SoilGroupExpReportMake from '../../report-check/SoilGroupExpReportCheck'
export default {
  name: 'PreparationManage',
  components: { Reason, OperationModal, SoilGroupExpReportMake },
  data() {
    return {
      name: '',
      pageColumns: [
        {
          title: '委托商',
          key: 'client',
          width: 200,
          fixed: 'left'
        },
        { title: '委托编号', key: 'entrustCode', width: 100 },
        { title: '项目名称', key: 'projectName', width: 120 },
        { title: '检测科室', key: 'groupName', width: 120 },
        { title: '委托日期', key: 'entrustDate', width: 100, date: true },
        { title: '钻孔位置', key: 'boreholeLocation', width: 130 },
        { title: '钻孔名称', key: 'boreholeName', width: 100 },
        { title: '水深', key: 'waterDepth', width: 100 },
        { title: '制表人', key: 'tabulater', width: 110 },
        { title: '制表日期', key: 'tabulateDate', width: 110, date: true }
      ],
      btn: [
        // { id: '', type: 'primary', name: '提交' },
        // { id: '', type: 'primary', name: '退回' }
      ],
      getPage: {},
      searchOpen: false,
      currentIndex: '',
      selectIds: [],
      selectData: [],
      iconMsg: [
        // { id: '', type: 'md-image', name: '预览报告' },
        { id: '', type: 'md-image', name: '项目报告' },
        { id: '', type: 'ios-cloud', name: '附件' },
        { id: '', type: 'ios-clock', 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 soilStatistics.pageExpReportCheck(data)
      if (result) {
        this.getPage = result
        this.$refs.pageTable._hideLoading()
      }
    },
    _clearPage() {
      $('#lab-sample-form')
        .find('input')
        .each(function() {
          $(this).val('')
        })
      // this.$refs.sampleTime.handleClear()
    },
    _btnClick(msg, data) {
      switch (msg) {
        case '提交':
          this._submitReportIssue()
          break
        case '下载':
          this._downloadByIds()
          break
        case '退回':
          this._goBack()
          break
        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('提交成功!')
      }
    },
    _goBack() {
      // 退回
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条委托！')
      } else {
        this.$refs.reasonModal._open('退回原因')
      }
    },
    _reasonResult(data) {
      if (undefined !== data && data !== '') {
        this._reportCheckBack(data)
      }
    },
    _reportCheckBack: async function(data) {
      const result = await soilSample.reportIssueBack({
        ids: this.selectIds,
        remark: data
      })

      if (result) {
        this.$Message.success('退回成功！')
        await this._page()
      }
    },
    _submitReportCheck() {
      const data = this.selectData
      if (data.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
        return false
      }
      this._submitByIds(
        this.selectIds,
        `确定要提交 ${this.selectIds.length} 条数据吗?`
      )
    },
    _submitReportIssue() {
      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 soilSample.reportIssueSubmit(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 '操作日志':
          this._record(data.id)
          break
        case '项目报告':
          this._expReport(data)
          break
      }
    },
    _viewReport(data) {
      this._getObjectKey(data)
    },
    _record(id) {
      this.$refs.operationModal._open(id)
    },

    _expReport(data) {
      this.$refs.soilGroupExpReportMakeModal._open(data)
    },
    _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>
