<template>
  <div class="app-container">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px;">
        <div class="sub-navbar">
          <el-dropdown style="margin-right: 10px" @command="handleCommand">
            <el-button type="primary">
              起草报检单<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item, index) in jylbList" :key="index" :command="item">
                {{ item.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="success" icon="el-icon-printer" @click="batchPrintHzd">
            打印回执单
          </el-button>
          <el-button type="warning" icon="el-icon-circle-close" @click="errorBjd">
            异常收回
          </el-button>
          <el-button type="danger" icon="el-icon-circle-close" @click="invalidBjd">
            作废
          </el-button>
          <el-button type="info" icon="el-icon-delete" @click="delBjd">
            删除
          </el-button>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.serialNumber" placeholder="报检单号/流水号" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.shebeizhongleidaima" placeholder="请选择设备种类" clearable>
            <el-option v-for="item in sbzlList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input v-model="listQuery.shiyongdanwei" placeholder="使用单位名称" clearable style="width: 300px" @keyup.enter.native="handleFilter" />
          <el-date-picker v-model="listQuery.shouliriqi" type="date" value-format="yyyy-MM-dd" placeholder="选择报检日期" style="width: 180px" />
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <br>
          <span class="radio-group-label">报检状态：</span>
          <el-radio-group v-model="listQuery.bjState" @change="handleFilter">
            <el-radio :label="undefined">
              全部
            </el-radio>
            <el-radio :label="0">
              新建/预审
            </el-radio>
            <el-radio :label="1">
              待审核
            </el-radio>
            <el-radio :label="2">
              已审核
            </el-radio>
            <el-radio :label="5">
              异常收回
            </el-radio>
            <el-radio :label="6">
              异常退回
            </el-radio>
          </el-radio-group>
          <br>
          <span class="radio-group-label">受理科室：</span>
          <el-radio-group v-model="listQuery.shoulikeshi" @change="handleFilter">
            <el-radio :label="this.$store.getters.departmentId">
              本科室
            </el-radio>
            <el-radio :label="undefined">
              全部
            </el-radio>
          </el-radio-group>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span class="radio-group-label">受理人员：</span>
          <el-radio-group v-model="listQuery.shouliren" @change="handleFilter">
            <el-radio :label="$store.getters.userId">
              只看自己
            </el-radio>
            <el-radio :label="undefined">
              全部
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="bjdList"
      v-adaptive="{bottomOffset: 50}"
      height="0"
      :data="list"
      element-loading-text="拼命加载中"
      border
      fit
      highlight-current-row
      stripe
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" />
      <el-table-column align="center" label="序号" width="60">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="报检单号/流水号" prop="serialNumber" min-width="80" />
      <el-table-column align="center" label="设备种类" prop="shebeizhonglei" min-width="50" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" min-width="150" />
      <el-table-column align="center" label="报检日期" prop="shouliriqi" min-width="60" />
      <el-table-column align="center" label="报检状态" prop="bjState" min-width="50">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.bjState===0" type="success">
            新建/预审
          </el-tag>
          <el-tag v-else-if="scope.row.bjState===1" type="primary">
            待审核
          </el-tag>
          <el-tag v-else-if="scope.row.bjState===2" type="info">
            已审核
          </el-tag>
          <el-tag v-else-if="scope.row.bjState===3" type="warning">
            不予受理
          </el-tag>
          <el-tag v-else-if="scope.row.bjState===4" type="warning">
            补正通知
          </el-tag>
          <el-tag v-else-if="scope.row.bjState===5" type="danger">
            异常收回
          </el-tag>
          <el-tag v-else-if="scope.row.bjState===6" type="danger">
            异常退回
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备台数" prop="totalNum" min-width="50" />
      <el-table-column :formatter="formatter.getChineseName" align="center" label="受理人员" prop="shouliren" min-width="50" />
      <el-table-column align="center" label="操作" min-width="60" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="small" circle icon="el-icon-edit" title="编辑" @click="editBjd(scope.$index)" />
          <el-button v-show="scope.row.bjState === 2 || scope.row.bjState === 5 || scope.row.bjState === 6" type="success" size="small" circle icon="el-icon-view" title="预览回执单" @click="viewHzd(scope.row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageRow" style="float: left" @pagination="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 qs from 'qs'

export default {
  name: 'ProjectDtList',
  components: { Sticky, Pagination },
  data() {
    return {
      total: 0,
      list: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        orderBy: 'id desc',
        zfState: false,
        shoulikeshi: this.$store.getters.departmentId,
        shouliren: this.$store.getters.userId,
        bjState: undefined,
        dataSource: 0
      },
      sbzlList: [],
      ids: '',
      multipleSelection: [],
      params: {
        bjdIds: this.ids
      },
      printbutton: '',
      jylbList: [{ label: '定期检验', path: '/bjd/bjd-dj-create/定期检验' },
        { label: '监督检验', path: '/bjd/bjd-jj-create/监督检验' }]
    }
  },
  created() {
    this.getList()
    this.getSbzlList()
  },
  mounted() {
    const that = this
    this.common.$on('bjd-list', function() {
      that.handleFilter()
    })
  },
  methods: {
    getList() {
      this.apibjd({
        url: '/bjd/list',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.list = data.list
        this.total = data.total
      })
    },
    getSbzlList() {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: undefined,
          level: '1'
        }
      }).then(data => {
        this.sbzlList = data
      })
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleCommand(item) {
      this.$router.push({ path: item.path })
    },
    // 表格单击选中行
    onRowClick(row) {
      this.$refs.bjdList.toggleRowSelection(row)
      this.printbutton = ''
    },
    // 获取选中行的bdjId
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    handleDialogSelectionChange(val) {
      this.selection = val
    },
    // 作废报检单
    invalidBjd: function() {
      this.ids = ''
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选中需要删除的数据！'
        })
        return false
      } else {
        this.$prompt('请输入作废原因', '共' + this.multipleSelection.length + '条报检项目将作废，是否继续?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '作废原因不能为空'
        }).then(({ value }) => {
          for (let i = 0; i < this.multipleSelection.length; i++) {
            this.apibjd({
              url: '/bjd/updBjdToZf',
              method: 'get',
              params: { reason: value, bjdId: this.multipleSelection[i].id },
              paramsSerializer: function(params) {
                return qs.stringify(params, { indices: false })
              }
            }).then((data) => {
              this.$notify.success('操作成功！')
              this.getList()
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消作废'
          })
        })
      }
    },

    // 删除报检单---只有未审核的报检单才能删除
    delBjd: function() {
      this.ids = ''
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选中需要删除的数据！'
        })
        return false
      } else {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].bjState === 2) {
            this.$message({
              type: 'error',
              message: '选择的数据中有办结的项目，请重新选择！'
            })
            return false
          } else if (this.multipleSelection[i].bjState === 5 || this.multipleSelection[i].bjState === 6) {
            this.$message({
              type: 'error',
              message: '异常收回跟异常退回的数据，请通过作废按钮进行处理！'
            })
            return false
          } else if (this.multipleSelection[i].dataSource !== '0') {
            this.$message({
              type: 'warning',
              message: '微信报检/企业报检数据请执行作废操作！'
            })
            return false
          }
        }
        this.$confirm('共' + this.multipleSelection.length + '条报检项目将删除，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.apibjd({
            url: '/bjd',
            method: 'delete',
            params: {
              bjdIds: this.multipleSelection.map(rw => {
                return rw.id
              }).join(',')
            }
          }).then(data => {
            this.$message({
              message: data + '条项目删除成功',
              type: 'success'
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    editBjd($index) {
      const bjd = this.list[$index]
      let type = '/update'
      if (bjd.bjState === 2) {
        type = '/finish'
      }
      if (bjd.jianyanleibie === 'DJ') {
        this.$router.push({ path: '/bjd/bjd-dj-input/' + bjd.id + '/' + bjd.shebeizhongleidaima + '/' + bjd.shebeizhonglei + type })
      } else if (bjd.jianyanleibie === 'JJ') {
        this.$router.push({ path: '/bjd/bjd-jj-input/' + bjd.id + '/' + bjd.shebeizhongleidaima + '/' + bjd.shebeizhonglei + type })
      }
    },
    // 打印回执单
    batchPrintHzd() {
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请选择至少一条数据进行打印！', type: 'error' })
        return false
      }
      const arr = this.$refs.bjdList.selection.map((bjd) => {
        return bjd.id
      })
      console.log(arr)
      this.preview({
        url: '/print/batchGeneratePdfHzd',
        method: 'get',
        params: {
          bjdIds: arr
        },
        paramsSerializer: function(params) {
          return qs.stringify(params, { indices: false })
        }
      }).then((data) => {
        this.preview({
          url: '/print/createXmlOther',
          method: 'post',
          params: {
            ids: arr,
            type: 'HZD'
          },
          paramsSerializer: function(params) {
            return qs.stringify(params, { indices: false })
          }
        }).then((data) => {
          this.printbutton = 'ReportPrintApp://' + data
        })
      })
    },
    // 打印回执单
    printHzd() {
      if (this.multipleSelection.length > 1) {
        this.$message({ message: '只能打印一份报检单', type: 'error' })
        return
      }
      this.apibjd({
        url: '/bjd/printHzd',
        method: 'get',
        params: {
          bjdIds: this.multipleSelection[0].id
        }
      }).then(data => {
        this.preview({
          url: '/print/generatePdfListing',
          method: 'post',
          data: {
            info: data.bjd,
            paramList: data.renwu,
            viewType: 'HZD'
          }
        }).then(data => {
          data = data.replace(/\\/g, '/')
          // router.push({ path: '/preview/1/1/urlPath?src=' + store.getters.prodName + '/static/web/viewer.html?file=' + encodeURIComponent(data) + '&v=' + Math.random() })
          window.open(data)
        })
      })
    },
    viewHzd(bjdid) {
      this.preview({
        url: '/print/generatePdfHzd',
        method: 'get',
        params: {
          bjdId: bjdid
        }
      }).then((data) => {
        data = data.replace(/\\/g, '/')
        if (data) {
          this.$router.push({
            path:
              '/preview/hzd?src=' +
              this.$store.getters.prodName +
              '/static/web/viewer.html?file=' +
              encodeURIComponent(data)
          })
        } else {
          this.$message({
            message: 'PDF预览错误！',
            type: 'error',
            duration: 3 * 1000
          })
        }
      })
    },
    errorBjd() {
      // 异常收回
      this.$confirm('报检项目将进行异常收回，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length !== 1) {
          this.$message({ message: '只允许单台报检单收回', type: 'error' })
          return false
        }
        if (this.multipleSelection[0].bjState !== 2) {
          this.$message({ message: '非审核通过数据不允许异常收回！', type: 'error' })
          return false
        }
        // 业务
        this.apibjd({
          url: '/bjd/updBjdToYcsh',
          method: 'get',
          params: { bjdId: this.multipleSelection[0].id }
        }).then(data => {
          this.$message.success('异常收回成功！！请修改后重新审核通过！')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消收回'
        })
      })
    }
  }
}
</script>
