<template>
  <div>
    <Row>
      <Col span="24">
        <Form id="res-reports-form" :label-width="88" v-show="searchOpen" inline onsubmit="return false">
          <label class="label-sign"></label>
          <Form-item class="search-item" label="报告编号:">
            <Input @on-enter="_formSearch" name="reportCode" placeholder="请输入报告编号" clearable/>
          </Form-item>
          <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-btn">
            <Button @click="_formSearch" type="primary">搜索</Button>
          </Form-item>
        </Form>
      </Col>
      <Col span="24">
        <btn-list :msg="btn" :open="searchOpen" :showSearchBtn="true" @on-result-change="_btnClick" class="contHide">
        </btn-list>
      </Col>
      <!-- 表格 -->
      <Col span="24">
        <PTVXETable
          ref="pageTable"
          :getPage="getPage"
          :iconMsg="iconMsg"
          @on-result-change="_tableResultChange"
          :rows="100">
          <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">
              <div v-if="item.status">
                {{ scope.row[item.key] === undefined ? '': 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>
              <div v-else>{{scope.row[item.key]}}</div>
            </template>
          </vxe-table-column>
        </PTVXETable>
      </Col>
    </Row>
    <keep-alive>
      <!-- eslint-disable-next-line vue/require-component-is -->
      <component ref="refModal" :is="currentComponent" @on-result-change="_componentResult"></component>
    </keep-alive>
  </div>
</template>
<script>
import { soilReport } from '../../../../api'

/**
 * 报告档案的报告台账tab
 */

export default {
  components: {},
  props: {
    reportStatus: null
  },
  data() {
    return {
      notOkCountList: [
        { value: 0, name: '合格' },
        { value: 1, name: '不合格' }
      ],
      // typeList: [
      //   {name: '企业', value: 0},
      //   {name: '政府', value: 1},
      // ],
      currentComponent: '',
      searchOpen: false,
      selectIds: [],
      selectData: [],
      btn: [
        { type: 'error', id: 'ZBC', name: '退回', componentName: 'ReasonBack' }
      ],
      getPage: {},
      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 }
      ],
      iconMsg: [],
      // 操作列
      grantRecord: {
        type: 'ios-navigate',
        id: 'food-report-manage-res-grant-record',
        name: '发放记录',
        componentName: 'GrantRecordView'
      },
      editReport: { type: 'android-image', id: '', name: '预览/编辑报告' },
      viewPDF: { type: 'document', id: '', name: '预览PDF' },
      uploadReport: {
        type: 'ios-upload',
        id: 'food-report-manage-res-report-upload',
        name: '上传',
        componentName: 'UploadByReport'
      },
      itemByReport: {
        type: 'document-text',
        id: '',
        name: '项目台账',
        componentName: 'ItemModalByReport'
      },
      hisVersion: {
        type: 'information-circled',
        id: '',
        name: '历史版本',
        componentName: 'HisRevision'
      },
      fileByReport: {
        type: 'cloud',
        id: '',
        name: '附件',
        componentName: 'ReportFileManage'
      },
      viewFiles: {
        type: 'android-document',
        id: 'food-report-manage-view-files',
        name: '档案查看'
      },
      recordByReport: {
        type: 'ios-clock',
        id: '',
        name: '操作记录',
        componentName: 'FoodReportRecord'
      },

      formObj: {
        reportSn: '',
        sampleName: '',
        sampleNum: '',
        taskSource: '',
        detectType: '',
        standard: '',
        auditor: '',
        issuer: '',
        reportDateBegin: '',
        reportDateEnd: '',
        notOkCount: '',
        contractCtimeBegin: '',
        contractCtimeEnd: '',
        statusList: '',
        signStatusList: '',
        makeDateBegin: '',
        makeDateEnd: '',
        maker: '',
        contractType: ''
      },
      stdList: [],
      statusList: [],
      contractTypeList: [
        { key: '1', value: '政府' },
        { key: '0', value: '企业' }
      ],
      // 盖章状态
      signStatusList: [],
      sealList: [
        { name: '是', value: 3 },
        { name: '失败', value: 2 },
        { name: '否', value: 0 },
        { name: '进行中', value: 1 }
      ],
      reportType: 'FOOD_REPORT_MANAGE',
      selectStatuss: []
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('', 420)
      } else {
        return this.$tableHeight('tabNoSearch')
      }
    }
  },
  created() {},
  mounted() {
    this._page()
  },
  methods: {
    _makeDateChange(data) {
      this.formObj.makeDateBegin = data[0]
      this.formObj.makeDateEnd = data[1]
    },
    // 状态多选
    _statusChange(data) {
      if (data.length !== 0) {
        this.formObj.statusList = data.join(',')
      } else {
        this.formObj.statusList = ''
      }
    },
    _getStatus() {
      this.$store.dispatch('LmsEnum/getByType', 'ReportStatusEnum').then(() => {
        this.statusList = this.$store.state.LmsEnum.model
      })
    },
    _reportDateChange(data) {
      this.formObj.reportDueDateBegin = data[0]
      this.formObj.reportDueDateEnd = data[1]
    },
    _ctimeChange(data) {
      this.formObj.contractCtimeBegin = data[0]
      this.formObj.contractCtimeEnd = data[1]
    },
    _dateChange(data) {
      $('input[name=auditDateBegin]').val(data[0])
      $('input[name=auditDateEnd]').val(data[1])
    },
    _issueDateChange(data) {
      $('input[name=issueDateBegin]').val(data[0])
      $('input[name=issueDateEnd]').val(data[1])
    },
    _stdResult(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.standard = data.stdNum + '【' + data.name + '】'
          break
        case 'query':
          this.formObj.standard = data.name
          this._getStdList(data)
          break
      }
    },
    // 查询执行标准
    _getStdList(data) {
      const obj = { classify: 0, page: 1, row: 20 }
      if (data) {
        obj.name = data.name
      }
      this.$store.dispatch('StandardInfo/pageListByName', obj).then(() => {
        this.stdList = this.$store.state.StandardInfo.page.records
      })
    },
    // 盖完章以后刷新已选择的数据
    _refreshData() {
      if (this.selectIds.length > 0) {
        this._refreshPage()
      } else {
        this._page()
      }
    },
    // 根据ids 请求
    _refreshPage() {
      const obj = {}
      obj.ids = this.selectIds.join(',')
      obj.page = 1
      obj.rows = 1000
      this.$store.dispatch('FoodSampleReport/pageTableReport', obj).then(() => {
        const resRows = this.$store.state.FoodSampleReport.page.records
        this.$refs.pageTable._refreshRows(resRows)
      })
    },
    async _page() {
      const data = this.$serialize('res-reports-form')
      Object.assign(data, this.$refs.pageTable._searchParams())
      const result = await soilReport.pageReportIssueHis(data)
      if (result) {
        this.getPage = result
        this.$refs.pageTable._hideLoading()
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'selectData':
          this.selectData = data
          this.selectIds = []
          for (let i = 0; i < data.length; i++) {
            this.selectIds.push(data[i].id)
          }
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _iconClick(res, data, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (res) {
          case '预览/编辑报告':
            this._viewReport(data.id)
            break
          case '上传':
            this._upload(data.id)
            break
          case '项目台账':
            this.$refs.refModal._open(data.id)
            break
          case '历史版本':
            this.$refs.refModal._open(data.id, this.reportType)
            break
          case '操作记录':
            this._record(data.id)
            break
          case '预览PDF':
            this._viewPDF(data)
            break
          case '发放记录':
            this.$refs.refModal._open(data)
            break
          case '附件':
            this.$refs.refModal._open(data.id, 'reportId')
            break
          case '档案查看':
            this.reportViewFiles(data, {
              location: 'report',
              archivesType: 'reportManage'
            })
            break
        }
      })
    },
    _viewPDF(data) {
      this.$store
        .dispatch('FoodSampleReport/viewReportPDF', data.id)
        .then(() => {
          const res = this.$store.state.FoodSampleReport.model
          if (res) {
            this.$pdfView(res)
          } else {
            this.autoPdf(data)
          }
        })
    },
    _record(id) {
      this.$refs.refModal._open(id)
    },
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '退回':
            this._return()
            break
          case '盖章':
            this._toPDF()
            break
          case '下载':
            if (this.selectIds.length === 0) {
              this.$Message.warning('请至少选择一条数据！')
            } else {
              this.$refs.refModal._open(this.selectIds)
            }
            break
          case '下载报告二维码':
            if (this.selectIds.length === 0) {
              this.$Message.warning('请至少选择一条数据！')
            } else {
              this._downloadCode(this.selectIds)
            }
            break
          case '打印':
            const ids = this.selectIds
            if (ids.length === 0) {
              this.$Message.warning('请至少选择一条样品数据！')
            } else {
              this.$refs.refModal._open(this.selectIds)
            }
            break
          case '导出':
            if (this.getPage.records.length === 0) {
              this.$Message.warning('暂无数据，不可导出')
            } else {
              this._export()
            }
            break
          case '批量填写发放记录':
            if (this.selectData.length === 0) {
              this.$Message.warning('请至少选择一条数据！')
            } else {
              this.$refs.refModal._open(
                this.selectData[0].contractId,
                this.selectIds
              )
            }
            break
          case '更新PDF版报告':
            this._updatePdfReport()
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    // 下载报告二维码
    _downloadCode(selectIds) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定要下载这 ' + selectIds.length + ' 个报告二维码？',
        onOk: () => {
          // eslint-disable-next-line no-undef
          http.open(
            global.baseURL + '/food/v1/sample_report/download_qrcode_batch',
            {
              reportIds: this.selectIds.join(',')
            },
            '_blank'
          )
        }
      })
    },
    // 更新PDF版报告
    _updatePdfReport() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    // 打印word
    _printWord() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条样品数据！')
      } else {
        for (let i = 0; i < ids.length; i++) {
          this.$pageofficePrint({ ids: ids })
        }
      }
    },
    // 盖章
    _toPDF() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    _return() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.refModal._openIssue(this.selectIds)
      }
    },
    _upload(id) {
      this.$refs.refModal._open(id)
    },
    _viewReport(id) {
      this.$store.dispatch('FoodSampleReport/viewReport', id).then(() => {
        const data = this.$store.state.FoodSampleReport.page
        if (data !== undefined) {
          // 查询token,后台使用pageoffice调接口查询数据，需要token,否则提示未登录
          this.$openWindowModeless({
            objectKey: data.objectKey,
            id: id,
            isReport: 1
          })
        }
      })
    },
    // 下载
    _batchDown(Type) {
      if (Type === '2') {
        const ids = this.selectIds
        this.$Modal.confirm({
          title: '提示',
          content: '确定要下载这 ' + ids.length + ' 个报告？',
          onOk: () => {
            // eslint-disable-next-line no-undef
            http.open(
              global.baseURL +
                '/food/v1/sample_report/download_batch_by_sampleIds',
              {
                ids: ids.join(','),
                flag: 1
              },
              '_blank'
            )
          }
        })
      } else {
        // eslint-disable-next-line no-undef
        http.open(
          '/food/v1/sample_report/downloadSignature_batch?ids=' +
            this.selectIds +
            '&flag=1' +
            '&pdfType=' +
            Type
        )
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    /** *********************************************导出*****************************************/
    _export() {
      if (this.selectData.length === 0) {
        // 导出全部数据
        this._exportOk(this.getPage.total)
      } else {
        // 只导出选中的数据
        this._exportOk(this.selectData.length)
      }
    },
    _exportOk(length) {
      this.$Message.destroy()
      this.$Modal.confirm({
        title: '提示',
        content: '确定导出这' + length + '条数据？',
        onOk: () => {
          if (this.selectData.length > 0) {
            this.$exportExcel(
              'resReportTable',
              '报告台账',
              this.pageColumns,
              this.selectData
            )
          } else {
            this.$Message.loading({
              content: '正在处理，请稍后...',
              duration: 0
            })
            this.$store
              .dispatch(
                'FoodSampleReport/pageTableReport',
                this._searchParams()
              )
              .then(() => {
                const result = this.$store.state.FoodSampleReport.page.records
                this.$exportExcel(
                  'resReportTable',
                  '报告台账',
                  this.pageColumns,
                  result
                )
              })
          }
        }
      })
    },
    // 参数
    _searchParams() {
      const data = this.$serializeFormSearch(this.formObj)
      return this.$extend(data, { page: 1, rows: this.$exportRows() })
    },
    /** *********************************************导出*****************************************/
    _componentResult(data) {
      switch (this.currentComponent) {
        case 'SignatureToPDF':
        case 'UpdatePDFReport':
          this._refreshData()
          break
        case 'SelectDownLoadType':
          this._batchDown(data)
          break
        case 'HisRevision':
        case 'ReasonBack':
          this._page()
          break
      }
    }
  }
}
</script>
