<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 v-if="hasPerm('ysjl:un-done-jybg:reject')" type="primary" @click="batchBohui">
            <svg-icon icon-class="reject" /> 批量驳回
          </el-button>
          <el-button type="success" @click="batchSign">
            <svg-icon icon-class="sign" /> 批量签名
          </el-button>
          <el-button type="warning" @click="clearSignName">
            <svg-icon icon-class="clear" /> 清空签名
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="delReport">
            退回到记录
          </el-button>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.baogaobianhao" 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: 350px" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.bglx" placeholder="报告类型" style="width: 160px">
            <el-option
              v-for="item in bglxOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select><br>
          <span class="radio-group-label">当前环节：</span>
          <el-radio-group v-model="listQuery.flowstatus" @change="handleFilter">
            <el-radio :label="undefined">
              全部
            </el-radio>
            <el-radio :label="1">
              起草
            </el-radio>
            <el-radio :label="2">
              审核
            </el-radio>
            <el-radio :label="3">
              审批
            </el-radio>
          </el-radio-group>
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-search" @click="highQuery">
            高级查询
          </el-button>
          <el-button type="info" size="small" icon="el-icon-close" @click="clearQuery">
            清空条件
          </el-button>
        </el-form-item>
      </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 fixed="left" align="center" label="报告编号" prop="baogaobianhao" width="160" sortable="custom" />
      <el-table-column :formatter="formatter.formatterCategory" align="center" label="检验类别" prop="jianyanleibie" width="80" />
      <template v-if="$store.getters.departmentId === 69 || $store.getters.departmentId === 86">
        <el-table-column v-if="$store.getters.departmentId === 69" align="center" label="使用单位" prop="shiyongdanwei" width="200" />
        <el-table-column v-if="$store.getters.departmentId === 86" align="center" label="安装单位" prop="shigongdanwei" width="200" />
        <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="130" />
        <el-table-column align="center" label="制造单位" prop="zhizaodanwei" width="200" />
      </template>
      <template v-else-if="$store.getters.departmentId === 74">
        <el-table-column align="center" label="制造单位" prop="zhizaodanwei" width="200" />
        <el-table-column align="center" label="设备代码" prop="shebeidaima" width="200" />
        <el-table-column align="center" label="锅炉型号" prop="guigexinghao" width="200" />
        <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="130" />
      </template>
      <template v-else>
        <el-table-column align="center" label="使用登记证号" prop="shiyongdengjibianhao" width="150" sortable="custom" />
        <el-table-column align="center" label="注册代码" prop="zhucedaima" width="170" sortable="custom" />
        <el-table-column align="center" label="使用单位" prop="shiyongdanwei" width="200" />
        <el-table-column align="center" label="产品名称/设备名称" prop="shebeimingcheng" width="130" />
        <el-table-column align="center" label="制造单位" prop="zhizaodanwei" width="200" />
        <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="130" />
        <el-table-column align="center" label="单位内编号" prop="danweineibubianhao" width="130" sortable="custom" />
      </template>
      <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 v-if="$store.getters.departmentId !== 74" align="center" label="下次检验日期" prop="xiacijianyanriqi" width="120" sortable="custom" />
      <el-table-column align="center" label="检验结论" prop="jianyanjielun" :show-overflow-tooltip="true" width="95" />
      <el-table-column :formatter="formatterRiqi" align="center" label="最后修改日期" prop="updateTime" width="100" />
      <el-table-column :formatter="formatterHuanjie" fixed="right" align="center" label="环节" prop="flowstatus" width="50" />
      <el-table-column fixed="right" align="center" label="报告类型" prop="inspectionItems" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.bglx===1">
            主报告
          </el-tag>
          <el-tag v-if="scope.row.bglx===2" type="success">
            {{ scope.row.inspectionItems }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" prop="" width="200">
        <template slot-scope="scope">
          <el-button v-show="scope.row.flowstatus === 1 && !(scope.row.jilubianhao)" size="mini" type="success" icon="el-icon-edit" title="编辑" circle @click="editYsjl(scope.$index)" />
          <el-button
            v-show="(scope.row.shebeizhongleidaima === '2000' && scope.row.jianyanleibie !== 'ZJ') || scope.row.shebeizhongleidaima === '7000'"
            type="info"
            size="mini"
            circle
            icon="el-icon-view"
            :title="'预览' + (scope.row.shebeizhongleidaima === '2000' ? '原始资料' : '附件')"
            @click="common.viewRawRecords(scope.row.renwuId)"
          />
          <el-button v-if="scope.row.shebeizhongleidaima === '2000' && scope.row.jianyanleibie === 'ZJ'" v-show="scope.row.jilubianhao" type="success" size="mini" icon="el-icon-view" title="预览记录" circle @click="showZJPreviewJudge(scope.row)" />
          <el-button v-else v-show="scope.row.jilubianhao" 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 size="mini" type="info" icon="el-icon-message" title="查看驳回意见" circle @click="viewAllRejection(scope.row.renwuId)" />
          <el-button v-show="scope.row.shebeizhongleidaima === '2000' && scope.row.jianyanleibie === 'ZJ'" type="info" size="mini" circle icon="el-icon-info" title="查看相关鉴证" @click="showVerification(scope.row.renwuId,false)" />
          <!-- 锅炉制造 并且 当前报告的检验人员中包含当前用户 才显示该按钮 -->
          <el-button v-if="scope.row.shebeizhongleidaima === '1000' && scope.row.jianyanleibie === 'ZJ' && scope.row.jianyanrenyuan.split(',').indexOf(String($store.getters.userId)) !== -1" type="info" size="mini" circle title="收费信息" @click="showSfInfo(scope.row)">
            <svg-icon icon-class="finance" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <pagination v-show="total>0" :total="total" :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 :formatter="formatter.getChineseName" align="center" label="处理人" prop="userId" 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="dialogQueryVisible" title="高级查询" width="60%">
      <el-container>
        <el-form :inline="true">
          <el-form-item label="检验类别:" style="width: 240px;">
            <el-select v-model="listQuery.neibuleibie" placeholder="请选择检验类别" style="width: 165px" clearable>
              <el-option v-for="item in jylbList" v-show="item.parentId" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备种类:" style="width: 240px;">
            <el-select v-model="listQuery.shebeizhongleidaima" placeholder="请选择设备种类" style="width: 165px" clearable>
              <el-option v-for="item in sbzlList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="当前环节:" style="width: 240px;">
            <el-select v-model="listQuery.flowstatus" placeholder="请选择当前环节" style="width: 165px" clearable>
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="检验人员:" style="width: 240px;">
            <el-select v-model="listQuery.jianyanrenyuan" placeholder="请选择检验人员" style="width: 165px" filterable clearable>
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核人员:" style="width: 240px;">
            <el-select v-model="listQuery.shenheren" placeholder="请选择审核人员" style="width: 165px" filterable clearable>
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="审批人员:" style="width: 240px;">
            <el-select v-model="listQuery.shenpiren" placeholder="请选择审批人员" style="width: 165px" filterable clearable>
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="检验日期:" style="width: 240px;">
            <el-date-picker v-model="listQuery.jianyanriqi" type="date" value-format="yyyy-MM-dd" placeholder="选择检验日期" style="width: 165px" />
          </el-form-item>
          <el-form-item label="审核日期:" style="width: 240px;">
            <el-date-picker v-model="listQuery.shenheriqi" type="date" value-format="yyyy-MM-dd" placeholder="选择审核日期" style="width: 165px" />
          </el-form-item>
          <el-form-item label="审批日期:" style="width: 240px;">
            <el-date-picker v-model="listQuery.shenpiriqi" type="date" value-format="yyyy-MM-dd" placeholder="选择审批日期" style="width: 165px" />
          </el-form-item>
          <el-form-item label="设备/产品名称:" style="width: 290px;">
            <el-input v-model="listQuery.shebeimingcheng" placeholder="请输入设备/产品名称" clearable style="width: 185px" />
          </el-form-item>
          <el-form-item label="内部编号:" style="width: 240px;">
            <el-input v-model="listQuery.danweineibubianhao" placeholder="请输入内部编号" clearable style="width: 165px" />
          </el-form-item>
          <el-form-item label="下次检验日期:" style="width: 280px;">
            <el-date-picker v-model="listQuery.xiacijianyanriqi" type="date" value-format="yyyy-MM-dd" placeholder="请输入日期" style="width: 165px" />
          </el-form-item>
          <el-form-item label="制造单位:" style="width: 400px;">
            <el-input v-model="listQuery.zhizaodanwei" placeholder="请输入制造单位" clearable style="width: 300px" />
          </el-form-item>
          <el-form-item label="产品/出厂编号:" style="width: 290px;">
            <el-input v-model="listQuery.chanpinbianhao" placeholder="请输入产品编号" clearable style="width: 185px" />
          </el-form-item>
          <el-form-item label="使用登记证编号:" style="width: 320px;">
            <el-input v-model="listQuery.shiyongdengjibianhao" placeholder="请输入使用登记证编号" clearable style="width: 200px" />
          </el-form-item>
        </el-form>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQueryVisible = false">
          取 消
        </el-button>
        <el-button type="success" @click="handleFilter">
          查 询
        </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 v-if="this.$store.getters.departmentId !== 74" 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">
        <el-form-item label="驳回意见：" required>
          <el-input v-model="bohuiForm.infoNotes" :rows="5" type="textarea" />
        </el-form-item>
        <el-form-item label="驳回环节：" required>
          <el-select v-model="bohuiForm.flowstatus" placeholder="请选择">
            <el-option v-if="flowstatus === 2 || flowstatus === 3" label="起草环节" value="1" />
            <el-option v-if="flowstatus === 3" label="审核环节" value="2" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="上传驳回附件：">
          <span style="color: #dd6161">多张图片可合成一份pdf文件进行上传</span>
          <el-upload
            action=""
            class="upload-demo"
            accept="application/pdf,image/png,image/jpeg"
            :http-request="handleUploadReject"
            :on-preview="handlePreview"
            :on-remove="onRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :show-file-list="true"
            :file-list="fileList"
          >
            <el-button size="small" icon="el-icon-upload2">
              点击上传
            </el-button>
          </el-upload>
        </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" :modal-append-to-body="false" title="驳回意见" width="50%">
      <el-table :data="infoNotes">
        <el-table-column :formatter="formatter.getChineseName" align="center" label="驳回人" prop="infoSend" />
        <el-table-column align="center" label="驳回意见" prop="infoNotes" />
        <el-table-column align="center" label="驳回时间" prop="createTime" />
        <!--        <el-table-column align="center" label="驳回附件" width="120">
          <template slot-scope="{row}">
            <el-button type="primary" size="small" circle icon="el-icon-view" title="预览" @click="common.viewReject(row.id, row.fileName)" />
          </template>
        </el-table-column>-->
      </el-table>
    </el-dialog>

    <!--选择预览记录文件（制造监检压力容器）-->
    <el-dialog :visible.sync="dialogZJPreviewVisible" :modal-append-to-body="appendToBody" title="选择预览记录文件" width="20%">
      <el-form>
        <el-button type="primary" plain size="small" icon="el-icon-search" @click="common.viewYsjl(ysjlId, 'YSJL')">
          原始记录
        </el-button>
        <el-button type="primary" plain size="small" icon="el-icon-search" @click="common.viewYsjl(ysjlId, 'OTHER')">
          {{ ifDataSheet ? '数据表' : '批量证明' }}
        </el-button>
      </el-form>
    </el-dialog>

    <!--查看相关鉴证-->
    <el-dialog title="查看相关鉴证" :modal-append-to-body="false" :visible.sync="dialogEnclosureVisible">
      <enclosure :relation-id.sync="currentRenwuId" :if-liaison.sync="ifLiaison" :view-button.sync="viewButton" />
    </el-dialog>
    <!--查看收费信息-->
    <el-dialog title="查看收费信息" :visible.sync="dialogFormVisibleSfInfo">
      <el-form>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="合同金额" prop="zaojia">
              <el-input v-model="sfInfo.zaojia" type="text" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="比例" prop="bili">
              <el-input v-model="sfInfo.bili" type="text" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检验费用" prop="jianyanheding">
              <el-input v-model="sfInfo.jianyanheding" type="text" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <br>
    </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'
import Enclosure from '@/views/common/Enclosure'
import { rebutFn } from '@/api/common'
export default {
  name: 'TODOReport',
  components: { Sticky, Pagination, Enclosure },
  data() {
    return {
      total: 0,
      list: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        order: 'update_time', // 排序字段
        sort: 'asc', // 排序方式
        hasChild: true,
        hasFinish: false
      },
      listWithDrawQuery: {
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
        order: 'update_time', // 排序字段
        sort: 'ascending', // 排序方式
        createBy: this.$store.getters.userId
      },
      flowUserList: [],
      isQm: true,
      dialogFormVisible: false,
      multipleSelection: [],
      multipleSelectionLink: [],
      dialogQueryVisible: false,
      dialogBohuiVisible: false,
      dialogEnclosureVisible: false,
      viewButton: true,
      ifLiaison: false,
      sbzlList: [],
      sblbList: [],
      sbpzList: [],
      modelList: [],
      sbzldm: '',
      sblbdm: '',
      sbpzdm: '',
      modelId: '',
      currentRenwuId: 0,
      jylbList: [],
      flowstatus: '',
      statusList: [
        {
          value: 1,
          label: '起草报告'
        }, {
          value: 2,
          label: '审核报告'
        }, {
          value: 3,
          label: '审批报告'
        }
      ],
      bohuiForm: {
        infoNotes: '',
        flowstatus: ''
      },
      userList: [],
      ysjlId: '',
      dialogSignVisible: false,
      passForm: {
        password: '',
        signDate: this.formatter.dateFormat('YYYY-MM-dd')
      },
      isBatchSign: false, // 标记是否为批量签名
      listCopy: [],
      dialogFormCopyNewReportVisible: false,
      listQueryCopy: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        searchYsjl: {}
      },
      totalCopy: 0,
      copyNum: 1, // 复制份数
      manufacturParam: {},
      bzrQianming: false,
      // 驳回原因查询数据
      infoNotes: [],
      dialogBohuiyijianVisible: false,
      dialogDrawCanvasVisible: false,
      dialogZJPreviewVisible: false,
      appendToBody: false,
      ifDataSheet: true,
      ifDataSheet5: false,
      bglxOptions: [{
        value: '1',
        label: '主报告'
      }, {
        value: '2',
        label: '无损报告'
      }],
      fileList: [],
      dialogFormVisibleSfInfo: false,
      sfInfo: {},
      AllFlowUser: [{
        label: '起草环节',
        key: 1
      }, {
        label: '审核环节',
        key: 2
      }
      ]
    }
  },
  created() {
    this.getList()
    this.getSbzlList()
    this.jylbList = this.$store.getters.allCategory
    this.userList = this.$store.getters.allUser
  },
  mounted() {
    const that = this
    this.common.$on('bggl-daiban-list', function() {
      that.handleFilter()
    })
  },
  methods: {
    handlePreview(file) {
      window.open(file.url)
    },

    onRemove(file) {
      const array = file.url.split('/')
      if (array.length > 0) {
        const fd = new FormData()
        fd.append('fileName', array[array.length - 1])
        this.preview({
          method: 'delete',
          url: '/upload/deleteReject',
          data: fd
        }).then(() => {
          this.fileList.splice(this.fileList.indexOf(file), 1)
          this.$message.success('删除成功！')
        })
      }
    },
    handleExceed() {
      this.$notify.warning('请删除已上传附件后重新上传！')
    },
    handleUploadReject(back) {
      const fd = new FormData()
      fd.append('file', back.file)
      this.preview({
        method: 'post',
        url: '/upload/uploadReject',
        data: fd
      }).then(data => {
        if (data) {
          this.bohuiForm.fileName = data
          this.fileList.push({ name: data, url: process.env.VUE_APP_BASE_API + 'reject/' + data })
          this.$message.success('上传成功！')
        }
      })
    },
    getList() {
      this.api({
        url: '/ysjl/getListUnDoneJybg',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        for (let i = 0; i < data.list.length; i++) {
          if (data.list[i].bglx === 1) {
            data.list[i].bglxLabel = '主报告'
          } else if (data.list[i].bglx === 2) {
            data.list[i].bglxLabel = '无损报告'
          }
        }
        this.list = data.list
        this.total = data.total
        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
    },
    getSbzlList() {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: undefined,
          level: '1'
        }
      }).then(data => {
        this.sbzlList = data
      })
    },
    delReport() {
      // 批量删除
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要删除的数据。')
        return false
      }
      let linkname = ''
      let revertRenwuByYsjlIds = ''
      const ids = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i === 0 && this.multipleSelection[i].flowstatus === 1) {
          linkname = this.multipleSelection[i].flowstatus
        }
        if (linkname !== this.multipleSelection[i].flowstatus) {
          this.$message('只允许起草环节删除报告。')
          return false
        }
        if (this.multipleSelection[i].shebeileibiedaima === '2100' && this.multipleSelection[i].jianyanleibie === 'DJ') {
          revertRenwuByYsjlIds = this.multipleSelection[i].id + ',' + revertRenwuByYsjlIds
        }
        ids.push(this.multipleSelection[i].id)
      }
      this.$confirm('确定删除当前选中报告?', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        this.api({
          url: '/ysjl/delReport',
          method: 'delete',
          params: {
            ids: ids
          },
          paramsSerializer: function(params) {
            return require('qs').stringify(params, { indices: false })
          }
        }).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.getList()
              // 刷新原始记录待办，原始记录已办列表，任务列表
              Utils.$emit('task-list')
              Utils.$emit('ysjl-list')
              Utils.$emit('ysjl-yb-list')
              Utils.$emit('bggl-yiban-list')
              Utils.$emit('manufacture-list')
              Utils.$emit('manufacture-done-list')
            }
          })
        })
      })
    },
    batchBohui() {
      // 批量驳回
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要驳回的数据。')
        return false
      }
      this.ysjlId = []
      const arr = []

      this.flowstatus = this.multipleSelection[0].flowstatus
      if (this.flowstatus === 1) {
        this.$message('存在未流转报告。')
        return false
      }
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[i].flowstatus !== this.flowstatus) {
          this.$message('选择的驳回数据环节请保持一致')
        }
        arr.push(this.multipleSelection[0].id)
      }
      this.ysjlId = arr
      if (this.ysjlId.length) {
        this.dialogBohuiVisible = true
      }
    },
    bohui() {
      this.$confirm('确定要驳回吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(this.ysjlId)
        this.$refs['bohuiForm'].validate(valid => {
          if (valid) {
            rebutFn({
              ysjlIds: this.ysjlId,
              infonotes: this.bohuiForm.infoNotes,
              flowstatus: this.bohuiForm.flowstatus
            }).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 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
      this.ysjlId = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        this.ysjlId.push(this.multipleSelection[i].id)
        if (i === 0) {
          linkname = this.multipleSelection[i].flowstatus
          if (this.multipleSelection[i].bglx === 1) {
            parentIds = this.multipleSelection[i].id
          }
        } else {
          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) {
            this.$message.error('请先办结子报告再发送！')
          } else {
            this.batchSendTo(isQianming, linkname, idStr)
          }
        })
      } else {
        this.batchSendTo(isQianming, linkname, idStr)
      }
    },
    batchSendTo(isQianming, flowstatus, idStr) {
      if (isQianming) {
        this.dialogSignVisible = true
        this.flowstatus = flowstatus
        return false
      }
      const departmentId = this.multipleSelection[0].departmentId
      const bglx = this.multipleSelection[0].bglx
      // 获取下一环节人员之前先确认是否已经签名
      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/getNextLinkUsers',
        method: 'get',
        params: {
          bglx: bglx,
          flowstatus: flowstatus + 1,
          departmentId: departmentId
        }
      }).then(data => {
        this.flowUserList = data
        this.dialogFormVisible = true
      }).catch(() => {
        this.dialogSignVisible = false
      })
    },
    confirmSend() {
      if (this.multipleSelectionLink.length !== 1) {
        this.$message('只能选择单人处理下一环节。')
        return false
      }
      const flowstatus = this.multipleSelection[0].flowstatus
      for (let i = 1; i < this.multipleSelection.length; i++) {
        if (flowstatus !== this.multipleSelection[i].flowstatus) {
          this.$message('请选择同环节进行发送。')
          return false
        }
      }
      const _vue = this
      const link = this.multipleSelectionLink[0]
      this.api({
        url: '/flow/send',
        method: 'post',
        data: {
          ysjlIds: this.ysjlId,
          userId: link.userId,
          currentLink: flowstatus,
          nextValue: flowstatus + 1
        }
      }).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
          },
          paramsSerializer: function(params) {
            return qs.stringify(params, { indices: false })
          }
        }).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
    },
    /**
       * 批量办结压力管道报告
       */
    batchEnd() {
      if (this.$refs.list.selection.length < 1) {
        this.$message.warning('请至少选择一份报告进行办结！')
        return false
      }
      if (this.$refs.list.selection.filter(report => report.jianyanleibie !== 'DJ' || report.shebeizhongleidaima !== '8000').length) {
        this.$message.warning('该批量办结只允许批量办结压力管道定检报告！')
        return false
      }
      this.$confirm('确定办结当前选中报告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.$refs.list.selection.map(report => report.id).join(',')
        this.api({
          url: '/flow/end',
          method: 'post',
          params: {
            ids: ids
          }
        }).then(() => {
          this.$message.success('批量办结报告成功！')
          this.common.viewYsjlNoOpen(ids, 'JYBG')
          this.getList()
          Utils.$emit('bggl-yiban-list')
        })
      })
    },
    /**
       * 办结时删除原始资料
       * @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.sign()
      })
    },
    sign() {
      this.api({
        url: '/flow/qianming',
        method: 'get',
        params: {
          ids: this.ysjlId,
          riqi: this.passForm.signDate,
          flowstatus: this.flowstatus
        },
        paramsSerializer: function(params) {
          return require('qs').stringify(params, { indices: false })
        }
      }).then(() => {
        this.$message({
          type: 'success',
          message: '签名成功!'
        })
        this.isQm = false
        if (this.isBatchSign) {
          this.handleFilter()
        } else {
          this.batchSend()
        }
        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 '未知'
      }
    },
    editYsjl($index) {
      const ysjl = this.list[$index]
      if (ysjl.shebeizhongleidaima === '8000') {
        this.api({
          url: '/template/getById',
          method: 'get',
          params: {
            id: ysjl.modelId
          }
        }).then(data => {
          const queryParam = {
            id: ysjl.id,
            jyxm: this.list[$index].jianyanxiangmu,
            departmentId: this.$store.getters.departmentId,
            jianyanrenyuan: ysjl.jianyanrenyuan,
            state: 'update',
            renwuId: ysjl.renwuId,
            modelId: ysjl.modelId,
            jylb: ysjl.jianyanleibie,
            neibuleibie: ysjl.neibuleibie,
            sbzldm: ysjl.shebeizhongleidaima,
            sblbdm: ysjl.shebeileibiedaima,
            sbpzdm: ysjl.shebeipinzhongdaima,
            sfdId: ysjl.sfdId
          }
          if (ysjl.bglx === 1) {
            this.$router.push({ path: data.tempPath + '/' + ysjl.id, query: queryParam })
          } else {
            this.$router.push({ path: data.tempPath, query: queryParam })
          }
        })
      } else {
        let nblb = ''
        if (ysjl.neibuleibie === 'DQ' || ysjl.neibuleibie === 'SCDQ' || ysjl.neibuleibie === 'QM') {
          nblb = 'dj/'
        } else if (ysjl.neibuleibie === 'JD') {
          nblb = 'jj/'
        } else {
          nblb = ysjl.neibuleibie.toLowerCase() + '/'
        }
        if (this.list[$index].bglx === 1) {
          if (ysjl.shebeizhongleidaima === '2000') {
            this.$router.push({ path: '/bggl/' + ysjl.shebeizhongleidaima + '/' + nblb + this.list[$index].jianyanxiangmu + '/' + ysjl.id, query: { id: ysjl.id, jyxm: this.list[$index].jianyanxiangmu, departmentId: this.$store.getters.departmentId, ysjl: ysjl, state: 'update' }})
          } else {
            this.$router.push({ path: '/bggl/' + ysjl.shebeizhongleidaima + '/' + nblb + 'edit/' + ysjl.id + '/update', query: { ysjl: ysjl }})
          }
        } else {
          if (ysjl.shebeizhongleidaima === '2000') {
            nblb = ''
          }
          this.$router.push({ path: '/bggl/' + ysjl.shebeizhongleidaima + '/' + nblb + this.list[$index].jianyanxiangmu, query: { id: ysjl.id, jyxm: this.list[$index].jianyanxiangmu, departmentId: this.$store.getters.departmentId }})
        }
      }
    },
    highQuery() {
      this.dialogQueryVisible = true
    },
    clearQuery() {
      this.listQuery = {
        order: 'update_time', // 排序字段
        sort: 'asc', // 排序方式
        hasChild: true,
        hasFinish: false
      }
      this.getList()
    },
    clearCopyQuery() {
      this.$set(this.listQueryCopy, 'searchYsjl', {
        bglx: 1
      })

      this.handleFilterCopy()
    },
    closeDialog() {
      this.isQm = true
    },
    batchSign() {
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要签名的数据。')
        return false
      }
      this.ysjlId = []
      const flowstatus = this.multipleSelection[0].flowstatus
      for (let i = 0; i < this.multipleSelection.length; i++) {
        this.ysjlId.push(this.multipleSelection[i].id)
        if (flowstatus !== this.multipleSelection[i].flowstatus) {
          this.$message('请选择同环节签名！')
          return false
        }
      }
      this.isBatchSign = true
      this.flowstatus = flowstatus
      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
      })
    },
    getSblbList(val) {
      this.sblbdm = ''
      this.sbpzList = []
      this.sbpzdm = ''
      this.modelList = []
      this.modelId = ''
      this.getSbList(val, undefined, 2)
    },
    getSbpzList(val) {
      this.modelList = []
      this.modelId = ''
      this.sbpzdm = ''
      this.getSbList(this.sbzldm, val, 3)
    },
    getModelList(val) {
      let tempJylb = '制造监检'
      let category = 'JYBG'
      if (val === '7310') {
        tempJylb = '定期检验'
        category = 'YSJL'
      }
      this.api({
        url: '/template/getTemplateBySbpz',
        method: 'post',
        data: {
          sbpz: val,
          jianyanleibie: tempJylb,
          category: category
        }
      }).then(data => {
        this.modelList = data
        this.modelId = data[0].value
      })
    },
    getSbList(sbzl, sblb, level) {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: sbzl,
          sblb: sblb,
          level: level
        }
      }).then(data => {
        switch (level) {
          case 2:
            this.sblbList = data
            return ''
          case 3:
            this.sbpzList = data
            return ''
          default:
            this.sbzlList = data
            return ''
        }
      })
    },
    getListCopy() {
      this.listQueryCopy.searchYsjl.bglx = '1'
      this.api({
        url: '/ysjl/gainNewReportList',
        method: 'get',
        params: this.listQueryCopy
      }).then(data => {
        this.listCopy = data.list
        this.totalCopy = data.total
      })
    },
    handleFilterCopy() {
      // 查询事件
      this.listQueryCopy.pageNum = 1
      this.getListCopy()
    },
    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 ''
    },
    formatterRiqi(row) {
      if (row.updateTime) {
        return row.updateTime.substring(0, 10)
      }
    },
    /**
       * 根据报告ID查看驳回原因
       * @param renwuId
       */
    viewAllRejection(renwuId) {
      this.api({
        url: '/taskinfo/viewRejection',
        method: 'get',
        params: {
          renwuId: renwuId
        }
      }).then(data => {
        this.infoNotes = data
        if (!this.infoNotes.length) {
          this.$alert('暂无驳回意见！', '驳回意见', {
            confirmButtonText: '关闭'
          })
        } else {
          this.dialogBohuiyijianVisible = true
        }
      })
    },
    /**
       *  预览驳回图片文件
       * @param viewType
       */
    rejectPicture(viewType) {
      this.preview({
        url: '/print/generateRejectPicture',
        method: 'post',
        data: {
          ysjlId: this.ysjlId,
          viewType: viewType
        }
      }).then(data => {
        data = data.replace(/\\/g, '/')
        window.open(data)
        this.dialogBohuiyijianVisible = false
      })
    },
    showDrawCanvas(ysjl) {
      if (ysjl.flowstatus === 1) {
        this.$message('存在未流转报告。')
      } else {
        this.ysjlId = ysjl.id
        this.dialogDrawCanvasVisible = true
      }
    },
    drawCanvas(viewType) {
      this.preview({
        url: '/upload/judgeDrawingFileExist',
        method: 'post',
        params: {
          ysjlId: this.ysjlId,
          viewType: viewType
        }
      }).then(data => {
        if (data) {
          this.$confirm('是否删除原绘制文件重新绘制?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.toCanvas(viewType)
          })
        } else {
          this.toCanvas(viewType)
        }
      })
    },
    toCanvas(viewType) {
      this.preview({
        url: '/print/getDrawCanvasImgUrl',
        method: 'post',
        data: {
          ysjlId: this.ysjlId,
          viewType: viewType,
          generateType: false
        }
      }).then(data => {
        this.appendToBody = false
        this.dialogDrawCanvasVisible = false
        const path = data.path.replace(/\\/g, '/')
        this.$router.push({ path: '/preview/canvas-list/' + encodeURIComponent(path) + '/' + data.width + '/' + data.height })
      })
    },
    showZJPreviewJudge(ysjl) {
      this.ifDataSheet = ysjl.shebeileibiedaima !== '2300'
      this.ifDataSheet5 = ysjl.shengchanxingshi === '5'
      this.ysjlId = ysjl.id
      this.appendToBody = false
      this.dialogZJPreviewVisible = true
    },
    showVerification(renwuId, viewButton) {
      this.currentRenwuId = renwuId
      this.viewButton = viewButton
      this.dialogEnclosureVisible = true
    },
    showSfInfo(row) {
      this.ysjlService.getParam(row.id, '1000').then(data => {
        this.sfInfo = {
          zaojia: data.zaojia,
          bili: data.bili,
          jianyanheding: row.jianyanheding
        }
        this.dialogFormVisibleSfInfo = true
      })
    }
  }
}
</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>
