<template>
  <div class="app-container">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px;">
        <div class="sub-navbar">
          <el-button v-show="hasPerm('print:SFD')" type="success" icon="el-icon-printer" @click="printSfd">
            收费通知单
          </el-button>
          <el-button type="primary" icon="el-icon-printer" @click="batchToPrint('YSJL')">
            原始记录
          </el-button>
          <el-button type="primary" icon="el-icon-printer" @click="batchToPrint('JYBG')">
            检验报告
          </el-button>
          <el-button type="primary" icon="el-icon-printer" @click="batchToPrint('HGZ')">
            合格证
          </el-button>
          <el-button type="primary" @click="openGrant()">
            <svg-icon icon-class="form" />
            报告发放
          </el-button>
          <el-dropdown @command="printOnline">
            <el-button type="success" icon="el-icon-view">
              预览打印<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="YSJL">
                原始记录
              </el-dropdown-item>
              <el-dropdown-item command="JYBG">
                检验报告
              </el-dropdown-item>
              <el-dropdown-item command="HGZ">
                合格证
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button v-if="hasRole('ADMIN')" type="primary" @click="sign">
            签章
          </el-button>
          <el-button v-if="hasRole('ADMIN')" type="primary" @click="removeSign">
            移除签章
          </el-button>
        </div>
      </sticky>
      <el-form ref="testrefprint">
        <el-form-item>
          <el-input v-model="listQuery.serialNumber" placeholder="（全部）报检单编号" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.zhucedaima" placeholder="注册代码" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.shiyongdanwei" placeholder="使用单位" clearable style="width: 250px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.weibaodanwei" placeholder="维保单位" clearable style="width: 250px" @keyup.enter.native="handleFilter" />
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="info" size="small" icon="el-icon-close" @click="clearQuery">
            清空
          </el-button>
          <br>
          <el-input v-model="listQuery.baogaobianhao" placeholder="报告编号" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.shiyongdengjibianhao" placeholder="请输入使用登记证编号" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.chanpinbianhao" placeholder="请输入产品编号" clearable style="width: 185px" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.jianyanleibie" placeholder="请选择检验类别" style="width: 165px" filterable clearable @change="handleFilter">
            <el-option v-for="item in jylbList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
          <el-date-picker v-model="listQuery.xiacijianyanriqi" type="date" value-format="yyyy-MM-dd" placeholder="请选择下次检验日期" style="width:145px" />
          <span class="radio-group-label">打印状态：</span>
          <el-radio-group v-model="listQuery.printState" @change="handleFilter">
            <el-radio :label="0">
              未打印
            </el-radio>
            <el-radio :label="1">
              已打印
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="list"
      v-adaptive="{bottomOffset: 50}"
      height="0"
      :data="list"
      border
      fit
      highlight-current-row
      stripe
      width="100%"
      size="small"
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column fixed="left" align="center" label="序号" width="50">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="报告编号" prop="baogaobianhao" width="120" sortable="custom" />
      <el-table-column align="center" label="检验类别" prop="jianyanleibie" width="90" />
      <el-table-column align="center" label="使用登记证号" prop="shiyongdengjibianhao" width="140" sortable="custom" />
      <el-table-column align="center" label="注册代码" prop="zhucedaima" width="160" sortable="custom" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" width="240" />
      <el-table-column align="center" label="维保单位" prop="weibaodanwei" width="240" />
      <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="140" />
      <el-table-column align="center" label="单位内编号" prop="danweineibubianhao" width="140" sortable="custom" />
      <el-table-column align="center" label="检验人员" prop="jianyanrenyuan" width="120" />
      <el-table-column align="center" label="检验日期" prop="jianyankaishiriqi" width="110" sortable="custom" />
      <el-table-column align="center" label="下次检验日期" prop="xiacijianyanriqi" width="130" sortable="custom" />
      <el-table-column align="center" label="检验结论" prop="jianyanjielun" width="80" />
      <el-table-column align="center" label="交费状态" prop="jfState" width="90" fixed="right">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.jfState" type="success">
            已交费
          </el-tag>
          <el-tag v-else type="danger">
            未交费
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" prop="" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-view" title="预览" circle @click="viewBaogao(scope.row.id, scope.row.reportVersion)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageRow" @pagination="getList" />
    <sign-info v-if="fafangVisible" :fafanglisttable="multipleSelection" @closeFafang="fafangVisible = false" @refulshList="getList" />
    <!-- 高级查询窗口 -->
    <iframe :src="printbutton" frameborder="0" scrolling="no" height="0px" aria-disabled="true" />
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
import SignInfo from '../sign_info'
import qs from 'qs'

export default {
  name: 'PrintReportDtWdy',
  components: { Sticky, Pagination, SignInfo },
  data() {
    return {
      total: 0,
      list: [],
      fafangListTable: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        orderBy: 'id desc', // 排序字段
        shebeizhongleidaima: '3000',
        printState: 0
      },
      flowUserList: [],
      dialogFormVisible: false,
      multipleSelection: [],
      multipleSelectionLink: [],
      jylbList: [{
        code: '定期检验',
        name: '定期检验'
      }, {
        code: '监督检验',
        name: '监督检验'
      }],
      userList: [],
      printbutton: '',
      fafangVisible: false,
      lingqu: {
        lingquren: '',
        lingqurenDianhua: '',
        fafangfangshi: '自取',
        dataSource: '16'
      },
      lingquImage: '',
      options: [{
        value: '自取',
        label: '自取'
      }, {
        value: '邮寄',
        label: '邮寄'
      }],
      rules: {
        lingquren: [{ required: true, message: '领取人不能为空', trigger: 'blur', validator: this.validator }],
        lingqurenDianhua: [{ required: true, message: '领取人电话不能为空', trigger: 'blur', validator: this.validator }]
      }
    }
  },
  created() {
    this.getList()
    this.userList = this.$store.getters.allUser
  },
  mounted() {
  },
  methods: {
    async validator(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    getList() {
      this.api({
        url: '/ysjl/getListPrint',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.list = data.list
        this.total = data.total
      })
    },
    sortChange(column) {
      this.listQuery.orderBy = column.prop + ' ' + column.order.replace('ending', '')
      this.getList()
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDialogSelectionChange(val) {
      this.selection = val
    },
    printOnline(type, updateDyState) {
      if (this.multipleSelection.length !== 1) {
        this.$message('请选择单条进行打印。')
        return false
      }
      if (type === 'HGZ') {
        this.generatePdfHgz()
        return
      }
      const id = this.multipleSelection[0].id

      this.preview({
        url: '/print/generatePdf',
        method: 'post',
        data: {
          ysjlId: id,
          viewType: type,
          generateType: false
        }
      }).then(data => {
        data = data.replace(/\\/g, '/')
        window.open(data)
        this.api({ // 记录打印详细，不做打印状态改变。
          url: '/ysjl/batchRecordPrintState',
          method: 'get',
          params: {
            id: id,
            type: type
          }
        })
      })
    },
    generatePdfHgz() {
      if (this.multipleSelection.length !== 1) {
        this.$message('请选择单条进行打印。')
        return false
      }
      const id = this.$refs.list.selection[0].id
      this.preview({
        url: '/print/generatePdfHgz',
        method: 'get',
        params: {
          ysjlId: id,
          viewType: 'HGZ'
        }
      }).then(data => {
        data = data.replace(/\\/g, '/')
        window.open(data)
        this.api({ // 记录打印详细，不做打印状态改变。
          url: '/ysjl/batchRecordPrintState',
          method: 'get',
          params: {
            id: id,
            type: 'HGZ'
          }
        })
      })
    },
    batchToPrint(type) {
      if (this.multipleSelection.length === 0) {
        this.$message('请选择单条或者多条设备进行打印。')
        return false
      }
      let ids = ''
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (type === 'HGZ' && this.multipleSelection[i].jianyanjielun === '不合格') {
          this.$message('请选择合格的报告进行打印。')
          return false
        }
        // if (!this.multipleSelection[i].jfState) {
        //   this.$message.error('存在未收费的报告，请联系收费核实后再进行打印。')
        //   return false
        // }
      }
      if (type === 'YSJL') {
        ids = this.$refs.list.selection.map(rep => {
          return rep.ysjlId
        }).join(',')
      } else {
        ids = this.$refs.list.selection.map(rep => {
          return rep.id
        }).join(',')
      }
      this.apiOld({
        url: '/flow/getPrintClientXml18',
        method: 'get',
        params: {
          ids: ids,
          type: type,
          username: `${this.$store.getters.username}`
        }
      }).then(data => {
        const pathdata = data.result
        this.printbutton = 'ReportPrintApp://' + pathdata
        this.apiOld({ // 记录打印详细，不做打印状态改变。
          url: '/taskInfo/batchRecordPrintState',
          method: 'get',
          params: {
            ids: ids,
            type: type,
            username: `${this.$store.getters.username}`
          }
        })
      })
    },
    clearQuery() {
      this.$set(this, 'listQuery', {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        orderBy: 'id desc', // 排序字段
        shebeizhongleidaima: '3000',
        printState: 0
      })
      this.getList()
    },
    printSfd() {
      if (this.multipleSelection.length > 1) {
        this.$message({
          type: 'info',
          message: '只能打印一份收费通知单！'
        })
        return false
      }
      if (this.multipleSelection[0].sfdId === null) {
        this.$message({
          type: 'warning',
          message: '该台设备没有收费通知单！！'
        })
        return false
      }
      if (this.multipleSelection[0].shebeizhongleidaima !== '1000') {
        this.$message({
          type: 'info',
          message: '只能锅炉打印收费通知单！'
        })
        return false
      }
      // 组织数据
      this.apibjd({
        url: '/sfd/getSfdPrintData',
        method: 'get',
        params: {
          ysjlId: this.multipleSelection[0].id
        }
      }).then(data => {
        this.preview({
          url: '/print/generatePdfListing',
          method: 'post',
          data: {
            info: data.info,
            paramList: data.paramList,
            viewType: 'SFD'
          }
        }).then(data => {
          data = data.replace(/\\/g, '/')
          window.open(data)
        })
      })
    },
    viewBaogao(id, viewType, generateType = false) {
      const data = `${process.env.VUE_APP_OLD_API}` + 'report/docKuroPreView/' + id + '/JYBG'.replace(/\\/g, '/')
      this.$router.push({ path: '/preview/' + id + '/JYBG/urlPath?src=' + this.$store.getters.prodName + '/static/web/viewer.html?file=' + encodeURIComponent(data) + '&v=' + Math.random() })
    },
    tableRowJielun({ row, rowIndex }) {
      if (row.jianyanjielun === '不合格' || row.jianyanjielun === '复检不合格') {
        return 'jielun-row'
      }
      return ''
    },
    openGrant() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请先选择需要发放的报告！'
        })
        return false
      }
      this.fafangVisible = true
    },
    sign() {
      this.preview({
        url: '/sign/byReportIds',
        method: 'post',
        params: {
          reportIds: this.$refs.list.selection.map(row => row.id)
        },
        paramsSerializer: function(params) {
          return qs.stringify(params, { indices: false })
        }
      }).then(data => {
        if (data) {
          this.$message.success('签章成功！')
        } else {
          this.$message.error('签章失败！')
        }
      })
    },
    removeSign() {
      this.apiOld({
        url: '/report/createReportByCheckIds',
        method: 'get',
        params: {
          ids: this.$refs.list.selection.map(row => row.id).join(',')
        }
      }).then(_ => {
        this.preview({
          url: '/sign/resetSignStatus16',
          method: 'post',
          params: {
            reportIds: this.$refs.list.selection.map(row => row.id)
          },
          paramsSerializer: function(params) {
            return qs.stringify(params, { indices: false })
          }
        }).then(data => {
          if (data) {
            this.$message.success('移除签章完成！')
          } else {
            this.$message.error('移除签章失败！')
          }
        })
      })
    }
  }
}
</script>

<style scoped>
  .app-container {
    padding-bottom: 0px;
  }
  /** 检验结论不合格 */
  .el-table .jielun-row {
    color: #ff0913;
  }
</style>
