<template>
  <div class="app-container">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px;">
        <div class="sub-navbar">
          <el-button type="success" @click="batchSend">
            <svg-icon icon-class="send" /> 批量发送
          </el-button>
          <el-button type="primary" @click="batchBohui">
            <svg-icon icon-class="reject" /> 批量驳回
          </el-button>
          <el-button type="primary" @click="batchSign">
            <svg-icon icon-class="sign" /> 批量签名
          </el-button>
          <el-button type="warning" @click="clearSignName">
            <svg-icon icon-class="clear" /> 清空签名
          </el-button>
        </div>
      </sticky>
      <el-form class="el-form" label-position="right" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="报告编号:" prop="baogaobianhao">
              <el-input v-model="listQuery.baogaobianhao" clearable @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="使用单位:" prop="shiyongdanwei">
              <el-input v-model="listQuery.shiyongdanwei" clearable @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <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>
        </el-row>
      </el-form>
    </div>
    <el-table
      ref="list"
      v-adaptive="{bottomOffset: 50}"
      height="0"
      :data="list"
      :default-sort="{prop:'update_time', order:'ascending'}"
      :row-class-name="tableRowClassName"
      border
      fit
      highlight-current-row
      stripe
      size="small"
      width="100%"
      @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="160" sortable="custom" />
      <el-table-column :formatter="formatter.formatterCategory" align="center" label="检验类别" prop="neibuleibie" width="120" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" />
      <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="130" />
      <el-table-column :formatter="formatter.getChineseName" align="center" label="检验人员" prop="jianyanrenyuan" width="100" />
      <el-table-column align="center" label="检验日期" prop="jianyanjieshuriqi" width="100" sortable="custom" />
      <el-table-column align="center" label="检验结论" prop="jianyanjielun" :show-overflow-tooltip="true" width="95" />
      <el-table-column fixed="right" align="center" label="操作" prop="" width="153">
        <template slot-scope="scope">
          <el-button type="success" size="mini" icon="el-icon-view" title="预览 原始记录" circle @click="common.viewYsjl(scope.row.id, 'YSJL')" />
          <el-button type="primary" size="mini" icon="el-icon-view" title="预览 报告" circle @click="common.viewYsjl(scope.row.id, 'JYBG')" />
          <el-button type="info" size="mini" icon="el-icon-message" title="查看驳回意见" circle @click="viewAllRejection(list[scope.$index].id)" />
          <el-button type="warning" size="mini" icon="el-icon-view" title="预览交费凭据" circle @click="previewCredentials(scope.row.sfdId)" />
        </template>
      </el-table-column>
    </el-table>
    <div>
      <pagination v-show="totalCount>0" :total="totalCount" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageRow" style="float: left;" @pagination="getList" />
      <div style="float: right;margin-top:8px;">
        <div style="width: 80px;float:left;margin-left: 50px;">
          重启流程：
        </div>
        <div class="identification" style="background-color:red;" />
        <div style="width: 50px;float:left;margin-left: 20px;">
          驳回：
        </div>
        <div class="identification" style="background-color: orange;" />
        <div style="width: 50px;float:left;margin-left: 20px;">
          复制：
        </div>
        <div class="identification" style="background-color:#690cff;" />
      </div>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="下一环节处理人" @close="closeDialog">
      <el-table ref="flowUserList" :data="flowUserList" border fit highlight-current-row @row-click="onRowClickLink" @selection-change="handleSelectionChangeLink">
        <el-table-column type="selection" width="40" />
        <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="nickname" min-width="40" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="success" @click="confirmSend">
          确认
        </el-button>
      </div>
    </el-dialog>
    <!-- 签名窗口 -->
    <el-dialog :visible.sync="dialogSignVisible" title="签名" width="500px">
      <el-form ref="passForm" :model="passForm" class="small-space" label-position="left" label-width="120px" style="width: 340px; margin-left:50px;">
        <el-form-item label="签名密码" required>
          <el-input v-model="passForm.password" type="password" />
        </el-form-item>
        <el-form-item label="签名日期" required>
          <el-date-picker v-model="passForm.signDate" type="date" value-format="yyyy-MM-dd" placeholder="选择签名日期" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSignVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="qianming">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <!-- 驳回窗口 -->
    <el-dialog :visible.sync="dialogBohuiVisible" title="驳回报告《必须填写意见才可驳回》" width="35%">
      <el-form ref="bohuiForm" :model="bohuiForm" class="small-space" label-position="left" label-width="120px" style="width: 340px; margin-left:50px;">
        <el-form-item label="驳回意见：" required label-width="100px">
          <el-input v-model="bohuiForm.infoNotes" :rows="5" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBohuiVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="bohui">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <!-- 驳回意见 -->
    <el-dialog :visible.sync="dialogBohuiyijianVisible" title="驳回意见" width="50%">
      <el-table :data="infoNotes">
        <el-table-column align="center" label="驳回人" prop="infoSend" />
        <el-table-column align="center" label="驳回意见" prop="infoNotes" />
        <el-table-column align="center" label="驳回时间" prop="createTime" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
import Utils from '../../utils/contact.js'
import qs from 'qs'

export default {
  components: { Sticky, Pagination },
  data() {
    return {
      totalCount: 0,
      list: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        order: 'update_time', // 排序字段
        sort: 'asc', // 排序方式
        hasTrial: true,
        hasChild: true,
        hasFinish: false
      },
      flowUserList: [],
      isQm: true,
      dialogFormVisible: false,
      multipleSelection: [],
      multipleSelectionLink: [],
      dialogQueryVisible: false,
      dialogBohuiVisible: false,
      sbzldm: '',
      sblbdm: '',
      sbpzdm: '',
      modelId: '',
      statusList: [
        {
          value: 1,
          label: '起草报告'
        }, {
          value: 2,
          label: '审核报告'
        }, {
          value: 3,
          label: '审批报告'
        }
      ],
      bohuiForm: {
        infoNotes: '',
        fileName: ''
      },
      userList: [],
      ysjlId: '',
      dialogSignVisible: false,
      passForm: {
        password: '',
        signDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate()
      },
      isBatchSign: false, // 标记是否为批量签名
      // 驳回原因查询数据
      infoNotes: [],
      dialogBohuiyijianVisible: false,
      sbpzs: []
    }
  },
  created() {
    this.getList()
    this.userList = this.$store.getters.allUser
  },
  mounted() {
    const that = this
    this.common.$on('bggl-daiban-list', function() {
      that.handleFilter()
    })
  },
  methods: {
    getList() {
      this.api({
        url: '/ysjl/getList',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.list = data.list
        this.totalCount = data.totalCount
        this.common.switchInspection(this.list)
      })
    },
    sortChange(column) {
      this.listQuery.order = column.prop
      this.listQuery.sort = column.order.replace('ending', '')
      this.getList()
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.dialogQueryVisible = false
      this.getList()
    },
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    onRowClickLink(row) {
      this.$refs.flowUserList.toggleRowSelection(row)
    },
    handleSelectionChangeLink: function(val) {
      this.multipleSelectionLink = val
    },
    batchBohui() {
      // 批量驳回
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要驳回的数据。')
        return false
      }
      this.ysjlId = ''
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[i].flowstatus !== 1) {
          if (i === 0) {
            this.ysjlId = this.multipleSelection[i].id
          } else {
            this.ysjlId = this.ysjlId + ',' + this.multipleSelection[i].id
          }
        } else {
          this.$message('存在未流转报告。')
        }
      }
      if (this.ysjlId !== '') {
        this.dialogBohuiVisible = true
      }
    },
    bohui() {
      this.$confirm('确定要驳回吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs['bohuiForm'].validate(valid => {
          if (valid) {
            this.api({
              url: '/flow/bohui',
              method: 'post',
              params: {
                ids: this.ysjlId,
                infonotes: this.bohuiForm.infoNotes,
                fileName: this.bohuiForm.fileName
              }
            }).then(data => {
              // 根据结果反馈信息
              this.$message({
                message: '驳回成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.dialogBohuiVisible = false
                  this.bohuiForm.infoNotes = ''
                  this.bohuiForm.fileName = ''
                  this.getList()
                }
              })
            })
          }
        })
      })
    },
    batchSend() {
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要发送的数据。')
        return false
      }
      const idStr = this.multipleSelection[0].id
      let existRecordNum = true // 是否存在记录编号
      let sendFlag = true // 发送标记
      let linkname = ''
      let isQianming = false
      let parentIds = '' // 主报告id
      const nblb = this.multipleSelection[0].neibuleibie
      const sbzldm = this.multipleSelection[0].shebeizhongleidaima
      const bglx = this.multipleSelection[0].bglx
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i === 0) {
          linkname = this.multipleSelection[i].flowstatus
          this.ysjlId = this.multipleSelection[i].id
          if (this.multipleSelection[i].bglx === 1) {
            parentIds = this.multipleSelection[i].id
          }
        } else {
          this.ysjlId = this.ysjlId + ',' + this.multipleSelection[i].id
          if (this.multipleSelection[i].bglx === 1) {
            parentIds = parentIds + ',' + this.multipleSelection[i].id
          }
        }
        if (linkname !== this.multipleSelection[i].flowstatus) {
          this.$message('请选择同环节进行发送。')
          return false
        }
        if (bglx !== this.multipleSelection[i].bglx) {
          this.$message('请选择同类型报告进行发送。')
          return false
        }
        if (this.multipleSelection[i].shebeizhongleidaima !== '1000') {
          if (this.multipleSelection[i].neibuleibie.indexOf(nblb) < 0 && nblb.indexOf(this.multipleSelection[i].neibuleibie) < 0) {
            this.$message('请选择同检验类别的报告进行发送。')
            return false
          }
        }
        if (sbzldm !== this.multipleSelection[i].shebeizhongleidaima) {
          this.$message('请选择同设备种类的报告进行发送。')
          return false
        }
        if (this.multipleSelection[i].jilubianhao !== '') {
          existRecordNum = false
        }
        if (this.isQm) {
          switch (this.multipleSelection[i].flowstatus) {
            case 1 :
              if (!this.multipleSelection[i].jianyanrenyuan) {
                this.$message('请检验人员先签名再发送审核!')
                return false
              }
              if (!this.multipleSelection[i].bianzhiren && this.multipleSelection[i].bglx === 1) {
                isQianming = true
              }
              break
            case 2 :
              if (!this.multipleSelection[i].shenheren) {
                isQianming = true
              }
              break
            case 3 :
              if (!this.multipleSelection[i].shenpiren) {
                isQianming = true
              }
              break
          }
        }
      }
      if (existRecordNum) {
        // 发送之前判断子报告是否已经办结
        this.api({
          url: '/ysjl/judgeState',
          method: 'get',
          params: {
            ysjlIds: parentIds,
            bglx: '2,3'
          }
        }).then(data => {
          if (data === 0) {
            sendFlag = false
            this.$message.error('请先办结子报告再发送！')
            return false
          }
        })
      }
      if (sendFlag) {
        if (isQianming) {
          this.dialogSignVisible = true
          this.flowstatus = linkname
          return false
        }
        // 获取下一环节人员之前先确认是否已经签名
        if (this.multipleSelection[0].flowstatus === 2 && (this.multipleSelection[0].shebeizhongleidaima === 'F000' || this.multipleSelection[0].bglx === 2)) {
          this.end(this.ysjlId, this.multipleSelection, false) // 验证是否属于办结操作，是直接办结。
          return false
        } else if (this.multipleSelection[0].flowstatus === 3) {
          this.end(this.ysjlId, this.multipleSelection, true) // 验证是否属于办结操作，是直接办结。
          return false
        }
        this.api({
          url: '/flow/getUser',
          method: 'get',
          params: {
            id: idStr,
            flowstatus: linkname
          }
        }).then(data => {
          this.flowUserList = data
          this.dialogFormVisible = true
        }).catch(() => {
          this.dialogSignVisible = false
          this.$confirm('列表可能长时间未刷新，是否刷新列表?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleFilter()
          }).catch(() => {
            this.dialogSignVisible = false
            this.$message({
              type: 'info',
              message: '已取消刷新'
            })
          })
        })
      }
    },
    confirmSend() {
      if (this.multipleSelectionLink.length !== 1) {
        this.$message('只能选择单人处理下一环节。')
        return false
      }
      let linkname = ''
      for (let i = 0; i < this.multipleSelectionLink.length; i++) {
        if (i === 0) {
          linkname = this.multipleSelectionLink[i].flowstatus
        }
        if (linkname !== this.multipleSelectionLink[i].flowstatus) {
          this.$message('请选择同环节进行发送。')
          return false
        }
      }
      this.multipleSelectionLink[0].ysjlId = this.ysjlId
      const _vue = this
      this.api({
        url: '/flow/send',
        method: 'post',
        data: this.multipleSelectionLink[0]
      }).then(() => {
        this.dialogFormVisible = false
        this.$message({
          message: '发送成功！',
          type: 'success',
          duration: 500,
          onClose: () => {
            _vue.getList()
            Utils.$emit('bggl-yiban-list')
          }
        })
      })
    },
    end(ysjlId, ysjls, generatePDF) {
      this.$confirm('确定办结当前选中报告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.api({
          url: '/flow/end',
          method: 'post',
          params: {
            ids: ysjlId
          }
        }).then(() => {
          this.$message({
            message: '办结成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.delRawRecords(ysjls)
              this.getList()
              Utils.$emit('bggl-yiban-list')
              // 发起生成PDF请求
              if (generatePDF) {
                this.preview({
                  url: '/print/batchGeneratePDF',
                  method: 'post',
                  data: {
                    ids: ysjlId,
                    generateType: 'END'
                  }
                })
                // 发起消红请求
                this.cleanRed(ysjls)
              }
            }
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消办结'
        })
      })
      this.isQm = true
    },
    /**
       * 办结时删除原始资料
       * @param ysjls
       */
    delRawRecords(ysjls) {
      const renwuIds = []
      ysjls.forEach((ysjl) => {
        if (ysjl.bglx === 1 && ysjl.shebeizhongleidaima === '2000' && ysjl.jianyanleibie === 'DJ') {
          renwuIds.push(ysjl.renwuId)
        }
      })
      if (renwuIds.length) {
        this.preview({
          url: '/upload/delRawRecords',
          method: 'get',
          params: {
            renwuIds: renwuIds.join(',')
          }
        })
      }
    },
    cleanRed(ysjls) {
      if (ysjls != null && ysjls.length > 0) {
        this.api({
          url: '/template/getById',
          method: 'get',
          params: {
            id: ysjls[0].modelId
          }
        }).then(data => {
          if (data.cleanState) {
            const cleanData = []
            ysjls.forEach(ysjl => {
              // 排除使用单位标注了测试的报告
              if (ysjl.shiyongdanwei.indexOf('测试') === -1) {
                const data = {}
                data.shiyongdanwei = ysjl.shiyongdanwei
                data.shebeizhonglei = ysjl.shebeizhongleidaima
                // 获取内部类别对应中文名称
                data.jianyanleibie = this.formatter.formatterCategory(null, null, ysjl.neibuleibie)
                data.zhucedaima = ysjl.zhucedaima
                data.shiyongdengjibianhao = ysjl.shiyongdengjibianhao
                data.jianyanriqi = ysjl.jianyanjieshuriqi
                data.xiacijianyanriqi = ysjl.xiacijianyanriqi
                data.jianyanjielun = ysjl.jianyanjielun
                data.baogaobianhao = ysjl.baogaobianhao
                data.quxian = ysjl.quhuamingcheng
                data.jianyanjigou = '济南市特种设备检验研究院'
                data.shi = '济南市'
                cleanData.push(data)
              }
            })
            if (cleanData.length > 0) {
              this.apisjse({
                url: '/baseInfo/chaoqijiekoupi',
                method: 'post',
                headers: { 'content-type': 'application/x-www-form-urlencoded' },
                data: qs.stringify({
                  loginname: 'jntjysjgx',
                  password: '123',
                  jiekous: JSON.stringify(cleanData)
                })
              })
            }
          }
        })
      }
    },
    qianming() {
      this.api({
        url: '/user/validationPwd',
        method: 'post',
        data: {
          id: this.$store.getters.userId,
          signPassword: this.passForm.password
        }
      }).then(() => {
        this.api({
          url: '/flow/qianming',
          method: 'get',
          params: {
            ids: this.ysjlId,
            riqi: this.passForm.signDate,
            flowstatus: this.flowstatus
          }
        }).then(() => {
          this.$message({
            type: 'success',
            message: '签名成功!'
          })
          this.isQm = false
          if (!this.isBatchSign) {
            this.batchSend()
          }
          this.handleFilter()
          this.dialogSignVisible = false
          this.isBatchSign = false
        }).catch(() => {
          this.$confirm('列表可能长时间未刷新，是否刷新列表?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleFilter()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消刷新'
            })
          })
        })
      })
    },
    formatterHuanjie(row) {
      switch (row.flowstatus) {
        case 1:
          return '起草'
        case 2:
          return '审核'
        case 3:
          return '审批'
        default:
          return '未知'
      }
    },
    clearQuery() {
      this.listQuery = {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        order: 'update_time', // 排序字段
        sort: 'asc', // 排序方式
        hasTrial: true,
        hasChild: true,
        hasFinish: false
      }
      this.getList()
    },
    closeDialog() {
      this.isQm = true
    },
    batchSign() {
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要签名的数据。')
        return false
      }
      let idStr = this.multipleSelection[0].id
      const linkname = this.multipleSelection[0].flowstatus
      for (let i = 1; i < this.multipleSelection.length; i++) {
        idStr = idStr + ',' + this.multipleSelection[i].id
        if (linkname !== this.multipleSelection[i].flowstatus) {
          this.$message('请选择同环节签名！')
          return false
        }
      }
      this.ysjlId = idStr
      this.isBatchSign = true
      this.flowstatus = linkname
      this.dialogSignVisible = true
    },
    clearSignName() {
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要清空签名的数据。')
        return false
      }
      let idStr = this.multipleSelection[0].id
      const linkname = this.multipleSelection[0].flowstatus
      for (let i = 1; i < this.multipleSelection.length; i++) {
        idStr = idStr + ',' + this.multipleSelection[i].id
        if (linkname !== this.multipleSelection[i].flowstatus) {
          this.$message('请选择同环节清除签名！')
          return false
        }
      }
      // 清除签名
      this.api({
        url: '/ysjl/clearSignName',
        method: 'get',
        params: {
          ysjlIds: idStr,
          flowStatus: linkname
        }
      }).then(() => {
        this.$message({
          type: 'success',
          message: '清除签名成功!'
        })
        this.handleFilter()
        this.isQm = true
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.retreatState === 1) {
        return 'reject-row'
      } else if (row.retreatState === 2) {
        return 'restart-row'
      } else if (row.copyState === true) {
        return 'copy-row'
      }
      return ''
    },
    /**
       * 根据报告ID查看驳回原因
       * @param ysjlId
       */
    viewAllRejection(ysjlId) {
      this.api({
        url: '/taskinfo/viewAllRejection',
        method: 'get',
        params: {
          ysjlId: ysjlId
        }
      }).then(data => {
        this.infoNotes = data
        if (!this.infoNotes.length) {
          this.$alert('暂无驳回意见！', '驳回意见', {
            confirmButtonText: '关闭'
          })
        } else {
          this.dialogBohuiyijianVisible = true
        }
      })
    },
    previewCredentials(billId) {
      // 组织数据
      this.apibjd({
        url: '/charge/getSfdPrintDataBySfdId',
        method: 'get',
        params: { billId: billId, version: '18' },
        paramsSerializer: function(params) {
          return qs.stringify(params, { indices: false })
        }
      }).then(data => {
        this.preview({
          url: '/print/generatePdfListing',
          method: 'post',
          data: {
            info: data.info,
            paramList: data.paramList,
            viewType: 'SFD'
          }
        }).then(data => {
          data = data.replace(/\\/g, '/')
          console.log(data)
          window.open(data)
        })
      })
    }
  }
}
</script>

<style>
  .el-table .reject-row {
    color: orange;
  }
  .el-table .restart-row {
    color: red;
  }
  .el-table .copy-row {
    color: #690cff;
  }
  .identification{
    width: 30px;
    height:15px;
    display: inline-block;
    border:gray 1px solid;
    border-radius:15px;
    float: left;
  }
  button.el-button.el-button--mini.is-circle{
    margin: 1px;
  }
</style>
