<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="申请部门" prop="applyDept">
        <el-input
          v-model="queryParams.applyDept"
          placeholder="请输入申请部门"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="applyWorkStartTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.applyWorkStartTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="applyWorkEndTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.applyWorkEndTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请单状态" prop="applyStatus">
        <el-select v-model="queryParams.applyStatus" placeholder="请选择申请单状态" clearable size="small">
          <el-option
            v-for="dict in certificateStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:permit:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="permitList">
      <el-table-column label="申请部门" align="center" prop="applyDept" />
      <el-table-column label="申请人" align="center" prop="linkMan" :formatter="applyNameFormate"/>
      <el-table-column label="联系电话" align="center" prop="linkPhone" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备编号" align="center" prop="deviceNum" />
      <el-table-column label="开始时间" align="center" prop="applyWorkStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyWorkStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="applyWorkEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyWorkEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请单状态" align="center" prop="applyStatus" :formatter="applyStatusFormate"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="certificateDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button
            v-if="scope.row.applyStatus =='0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:permit:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.applyStatus=='0' && scope.row.linkMan == $store.state.user.userId"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="certificateApprovalApply(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >作业证申请</el-button>
          <el-button
            v-if="scope.row.applyStatus=='1' && -1 != scope.row.approvals.findIndex(item => item === $store.state.user.userId)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="certificateApproval(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >作业证审核</el-button>
          <el-button
            v-if="scope.row.applyStatus=='2' && JSON.parse(scope.row.produceComfirm).monitorId == $store.state.user.userId"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="certificateCheck(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >事前检查</el-button>
          <el-button
            v-if="scope.row.applyStatus=='3' && scope.row.linkMan ==  $store.state.user.userId"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="closeCertificate(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >关闭作业单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改作业许可证对话框 -->
    <el-dialog :title="title" :rules="rules" :visible.sync="open" width="900px" append-to-body @close="cancel">
      <table>
        <tr>
          <td rowspan="4" colspan="2">作业许可申请人</td>
          <td colspan="2">申请部门/单位</td>
          <td colspan="2"><input v-model="certificateData.applyDept" class="editInput"/></td>
          <td colspan="2">申请人及联系方式</td>
          <td colspan="2"><input v-model="certificateData.linkManName" disabled class="editInput" style="width: 47%"/>|<input v-model="certificateData.linkPhone" class="editInput" style="width: 50%"/></td>
        </tr>
        <tr>
          <td colspan="2">作业区域范围</td>
          <td colspan="2"><input v-model="certificateData.workBound" class="editInput"/></td>
          <td colspan="2">设备名称及编号</td>
          <td colspan="2"><input v-model="certificateData.deviceName" class="editInput" style="width: 47%"/>|<input v-model="certificateData.deviceNum" class="editInput" style="width: 50%"/></td>
        </tr>
        <tr>
          <td colspan="2">申请作业时间</td>
          <td colspan="6">
            <el-row>
              <el-col :span="11">
                <el-date-picker clearable size="small"
                                v-model="certificateData.applyWorkStartTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择开始时间"
                                style="width: 100%">
                </el-date-picker>
              </el-col>
              <el-col :span="2" style="margin-top: 5px">
                至
              </el-col>
              <el-col :span="11">
                <el-date-picker clearable size="small"
                                v-model="certificateData.applyWorkEndTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择结束时间"
                                style="width: 100%">
                </el-date-picker>
              </el-col>
            </el-row>
          </td>
        </tr>
        <tr>
          <td colspan="2">作业内容</td>
          <td colspan="6"><input v-model="certificateData.workContent" class="editInput"/></td>
        </tr>
        <tr>
          <td colspan="2">所有相关方讨论</td>
          <td>工作安全分析</td>
          <td style="writing-mode: vertical-rl;">危害识别</td>
          <td colspan="6" style="text-align: left">
            <div><input type="checkbox" v-model="mainDangerousMark.burn">灼伤（低温/高温/化学品灼伤,电弧烧伤,火灾，易燃气/液体，蒸汽，电焊、动火、射线等）</div>
            <div><input type="checkbox" v-model="mainDangerousMark.electricShock">电击（触电，电压，不适当的接地，电气热作业，地下/暗线等）。</div>
            <div><input type="checkbox" v-model="mainDangerousMark.objectStrike">物体打击（爆炸，压力，能量释放，移动/坠落的物体，不正确的存放,设备）</div>
            <div><input type="checkbox" v-model="mainDangerousMark.stifle">窒息/中毒（惰性气体，有毒气体，易挥发的液体溶剂等）</div>
            <div><input type="checkbox" v-model="mainDangerousMark.drop">坠落（高处作业，没有防护的开口，没有固定的梯子，脚手架搭设，无防护的平台等）</div>
            <div><input type="checkbox" v-model="mainDangerousMark.vehicleInjury">车辆伤害（速度过快,疲劳驾驶,车辆故障,缺乏防御性驾驶,能见度差,不寻常的路状，分心等）</div>
            <div><input type="checkbox" v-model="mainDangerousMark.other">其它危害。</div>
            <div>注：如存在以上任一情况，请填写安全措施。</div>
          </td>
        </tr>
        <tr>
          <td rowspan="4" colspan="2">批准人填写</td>
          <td rowspan="4" colspan="2">许可证</td>
          <td colspan="6" style="text-align: left">是否需要进一步的JSA: <input type="checkbox" v-model="licenceInfo.jsa.yes"/>否<input type="checkbox" v-model="licenceInfo.jsa.no"/>是  JSA[<input class="editInput" v-model="licenceInfo.jsa.num" style="width: 250px" placeholder="填写JSA编号"/>]</td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: left"><input type="checkbox" v-model="licenceInfo.specialLicence"/>0无需特殊工作许可</td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: left">
            <div><input type="checkbox" v-model="licenceInfo.lockListing.isChecked"/>1-1锁定挂牌记录表 [<input class="editInput" v-model="licenceInfo.lockListing.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.blindPlate.isChecked"/>1-2盲板抽堵作业许可 [<input class="editInput" v-model="licenceInfo.blindPlate.num" style="width: 250px" placeholder="填写编号"/>]</div>
          </td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: left;">
            <div><input type="checkbox" v-model="licenceInfo.flareUp.isChecked"/>2动火作业许可证 [<input class="editInput" v-model="licenceInfo.flareUp.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.heightWork.isChecked"/>3高处作业许可证 [<input class="editInput" v-model="licenceInfo.heightWork.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.breakGround.isChecked"/>4动土作业许可证 [<input class="editInput" v-model="licenceInfo.breakGround.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.hoisting.isChecked"/>5吊装作业许可证 [<input class="editInput" v-model="licenceInfo.hoisting.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.limitSpace.isChecked"/>6受限空间作业许可证 [<input class="editInput" v-model="licenceInfo.limitSpace.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.electricityUse.isChecked"/>7临时用电许可证 [<input class="editInput" v-model="licenceInfo.electricityUse.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" v-model="licenceInfo.ray.isChecked"/>8射线探伤许可证 [<input class="editInput" v-model="licenceInfo.ray.num" style="width: 250px" placeholder="填写编号"/>]</div>
          </td>
        </tr>
        <tr>
          <td colspan="2">相关方填写</td>
          <td colspan="4">
            <div style="text-align: left">
              承包商:
              <textarea v-model="relationSign.contractor" style="height: 96px"></textarea>
            </div>

          </td>
          <td colspan="4">
            <div style="text-align: left">
              负责人：
              <textarea v-model="relationSign.personCharge" style="height: 96px"></textarea>
            </div>
          </td>
        </tr>
      </table>
      <el-row style="margin-top: 10px">
        <el-col :span="5">
          <div style="font-size: 18px;margin-top: 5px">
            <span style="color: red;font-weight: bold;margin-right: 3px">*</span>
            生产组当班班长：
          </div>
        </el-col>
        <el-col :span="8">
          <el-select v-model="produceComfirm.leaderDeptId" filterable placeholder="请选择生产组当班班长部门" @change="switchDept()">
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="11">
          <el-select v-model="produceComfirm.monitorId" filterable placeholder="请选择生产组当班班长">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCertificate">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 作业单申请 -->
    <el-dialog title="作业单申请" :visible.sync="certificateApprovalApplyOpen" append-to-body :close-on-click-modal="false" @close="cancelCertificateApply">
      <div class="tags_box">
        <div v-for="item in tags" class="tags">
          <div :class="{isActive:item.name==active}" @click="handelToogel(item.name,'1')">{{item.name}}</div>
        </div>
      </div>
      <div class="con_box">
        <div v-for="item in tags" v-show="active == item.name">
          <FlareUp v-if="item.mark == 'flareUp'"
                   :ref="item.mark"
                   :workPermitId = "item.workPermitId"
                   :licenceNum = "item.licenceNum"
                   applyStatus = "0"/>
          <BlindPlate v-if="item.mark == 'blindPlate'"
                   :ref="item.mark"
                   :workPermitId = "item.workPermitId"
                   :licenceNum = "item.licenceNum"
                   applyStatus = "0"/>

        </div>
      </div>
      <div style="text-align: right;margin-top: 10px">
        <el-button type="primary" @click="submitCertificateApply">确定</el-button>
        <el-button @click="cancelCertificateApply">取消</el-button>
      </div>
    </el-dialog>

    <!-- 作业单审核 -->
    <el-dialog title="作业单审核" :visible.sync="certificateApprovalOpen" append-to-body :close-on-click-modal="false">
      <div class="tags_box">
        <div v-for="item in specialWorkPermits" class="tags">
          <div :class="{isActive:item.specialWorkType==approvalActive}" @click="handelToogel(item.specialWorkType,'2')">{{ getTagName(item.specialWorkType) }}</div>
        </div>
      </div>
      <div class="con_box">
        <div v-for="item in specialWorkPermits" v-show="approvalActive == item.specialWorkType">
          <FlareUp v-if="item.specialWorkType == 'flareUp'"
                   :ref="item.specialWorkType"
                   :workPermitId = "item.workPermitId"
                   :licenceNum = "item.licenceNum"
                   applyStatus="1"/>
          <BlindPlate v-if="item.specialWorkType == 'blindPlate'"
                      :ref="item.specialWorkType"
                      :workPermitId = "item.workPermitId"
                      :licenceNum = "item.licenceNum"
                      applyStatus="1"/>
        </div>
      </div>
    </el-dialog>

    <!-- 事前检查 -->
    <el-dialog title="事前检查" :visible.sync="checkOpen" width="900px" append-to-body @close="checkCancel">
      <table>
        <tr>
          <td rowspan="4" colspan="2">作业许可申请人</td>
          <td colspan="2">申请部门/单位</td>
          <td colspan="2"><input disabled v-model="certificateData.applyDept" class="editInput"/></td>
          <td colspan="2">申请人及联系方式</td>
          <td colspan="2"><input v-model="certificateData.linkMan" disabled class="editInput" style="width: 47%"/>|<input disabled v-model="certificateData.linkPhone" class="editInput" style="width: 50%"/></td>
        </tr>
        <tr>
          <td colspan="2">作业区域范围</td>
          <td colspan="2"><input disabled v-model="certificateData.workBound" class="editInput"/></td>
          <td colspan="2">设备名称及编号</td>
          <td colspan="2"><input disabled v-model="certificateData.deviceName" class="editInput" style="width: 47%"/>|<input disabled v-model="certificateData.deviceNum" class="editInput" style="width: 50%"/></td>
        </tr>
        <tr>
          <td colspan="2">申请作业时间</td>
          <td colspan="6">
            {{ certificateData.applyWorkStartTime == null ? "-" :certificateData.applyWorkStartTime.split(" ")[0].split("-")[1]}}月{{certificateData.applyWorkStartTime == null ? "-" :certificateData.applyWorkStartTime.split(" ")[0].split("-")[2]}}日{{certificateData.applyWorkStartTime == null ? "-" :certificateData.applyWorkStartTime.split(" ")[1].split(":")[0]}}时{{certificateData.applyWorkStartTime == null ? "-" :certificateData.applyWorkStartTime.split(" ")[1].split(":")[1]}}分至{{certificateData.applyWorkEndTime == null ? "-" :certificateData.applyWorkEndTime.split(" ")[0].split("-")[1]}}月{{certificateData.applyWorkEndTime == null ? "-" :certificateData.applyWorkEndTime.split(" ")[0].split("-")[2]}}日{{certificateData.applyWorkEndTime == null ? "-" :certificateData.applyWorkEndTime.split(" ")[1].split(":")[0]}}时{{certificateData.applyWorkEndTime == null ? "-" :certificateData.applyWorkEndTime.split(" ")[1].split(":")[1]}}分
          </td>
        </tr>
        <tr>
          <td colspan="2">作业内容</td>
          <td colspan="6"><input disabled v-model="certificateData.workContent" class="editInput"/></td>
        </tr>
        <tr>
          <td colspan="2">所有相关方讨论</td>
          <td>工作安全分析</td>
          <td style="writing-mode: vertical-rl;">危害识别</td>
          <td colspan="6" style="text-align: left">
            <div><input type="checkbox" disabled v-model="mainDangerousMark.burn">灼伤（低温/高温/化学品灼伤,电弧烧伤,火灾，易燃气/液体，蒸汽，电焊、动火、射线等）</div>
            <div><input type="checkbox" disabled v-model="mainDangerousMark.electricShock">电击（触电，电压，不适当的接地，电气热作业，地下/暗线等）。</div>
            <div><input type="checkbox" disabled v-model="mainDangerousMark.objectStrike">物体打击（爆炸，压力，能量释放，移动/坠落的物体，不正确的存放,设备）</div>
            <div><input type="checkbox" disabled v-model="mainDangerousMark.stifle">窒息/中毒（惰性气体，有毒气体，易挥发的液体溶剂等）</div>
            <div><input type="checkbox" disabled v-model="mainDangerousMark.drop">坠落（高处作业，没有防护的开口，没有固定的梯子，脚手架搭设，无防护的平台等）</div>
            <div><input type="checkbox" disabled v-model="mainDangerousMark.vehicleInjury">车辆伤害（速度过快,疲劳驾驶,车辆故障,缺乏防御性驾驶,能见度差,不寻常的路状，分心等）</div>
            <div><input type="checkbox" disabled v-model="mainDangerousMark.other">其它危害。</div>
            <div>注：如存在以上任一情况，请填写安全措施。</div>
          </td>
        </tr>
        <tr>
          <td rowspan="4" colspan="2">批准人填写</td>
          <td rowspan="4" colspan="2">许可证</td>
          <td colspan="6" style="text-align: left">是否需要进一步的JSA: <input disabled type="checkbox" v-model="licenceInfo.jsa.yes"/>否<input type="checkbox" disabled v-model="licenceInfo.jsa.no"/>是  JSA[<input class="editInput" disabled v-model="licenceInfo.jsa.num" style="width: 250px" placeholder="填写JSA编号"/>]</td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: left"><input disabled type="checkbox" v-model="licenceInfo.specialLicence"/>0无需特殊工作许可</td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: left">
            <div><input type="checkbox" disabled v-model="licenceInfo.lockListing.isChecked"/>1-1锁定挂牌记录表 [<input class="editInput" disabled v-model="licenceInfo.lockListing.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.blindPlate.isChecked"/>1-2盲板抽堵作业许可 [<input class="editInput" disabled v-model="licenceInfo.blindPlate.num" style="width: 250px" placeholder="填写编号"/>]</div>
          </td>
        </tr>
        <tr>
          <td colspan="6" style="text-align: left;">
            <div><input type="checkbox" disabled v-model="licenceInfo.flareUp.isChecked"/>2动火作业许可证 [<input class="editInput" disabled v-model="licenceInfo.flareUp.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.heightWork.isChecked"/>3高处作业许可证 [<input class="editInput" disabled v-model="licenceInfo.heightWork.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.breakGround.isChecked"/>4动土作业许可证 [<input class="editInput" disabled v-model="licenceInfo.breakGround.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.hoisting.isChecked"/>5吊装作业许可证 [<input class="editInput" disabled v-model="licenceInfo.hoisting.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.limitSpace.isChecked"/>6受限空间作业许可证 [<input class="editInput" disabled v-model="licenceInfo.limitSpace.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.electricityUse.isChecked"/>7临时用电许可证 [<input class="editInput" disabled v-model="licenceInfo.electricityUse.num" style="width: 250px" placeholder="填写编号"/>]</div>
            <div><input type="checkbox" disabled v-model="licenceInfo.ray.isChecked"/>8射线探伤许可证 [<input class="editInput" disabled v-model="licenceInfo.ray.num" style="width: 250px" placeholder="填写编号"/>]</div>
          </td>
        </tr>
        <tr>
          <td colspan="2">相关方填写</td>
          <td colspan="4">
            <div style="text-align: left">
              承包商:
              <textarea disabled v-model="relationSign.contractor" style="height: 96px"></textarea>
            </div>

          </td>
          <td colspan="4">
            <div style="text-align: left">
              负责人：
              <textarea disabled v-model="relationSign.personCharge" style="height: 96px"></textarea>
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="2">生产班组确认</td>
          <td colspan="8">
            <el-row>
              <el-col :span="8" style="text-align: left">本人已知晓此工作许可证的内容</el-col>
              <el-col :span="8" style="text-align: right">确认签字（当班班长）：</el-col>
              <el-col :span="8"><NewEsign :resultImg.sync ="produceComfirm.monitorName" :width="918" :height="100"/></el-col>
            </el-row>
            <el-row>
              <el-col :span="24" style="text-align: right">日期/时间：<input style="width: 228px" v-model="produceComfirm.date" class="editInput"/></el-col>
            </el-row>
          </td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="checkSubmit">确 定</el-button>
        <el-button @click="checkCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 作业单关闭 -->
    <el-dialog title="作业单关闭" :visible.sync="certificateCompleteOpen" width="900px" append-to-body @close="completeCancel">
      <div>关闭意见：</div>
      <Editor v-model="workDeal.suggestion" :min-height="192" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="completeSubmit">确 定</el-button>
        <el-button @click="completeCancel">取 消</el-button>
      </div>
    </el-dialog>

    <NewWorkPermitDetail :certificateDetailOpen.sync="certificateDetailOpen"
                         :certificateData="certificateDataDetail"/>

  </div>
</template>

<script>
  import { listPermit, selectTWorkPermitListByLoginUser, getPermit, delPermit, addPermit, updatePermit, exportPermit } from "@/api/workPermit/permit";
  import { getSpecialWorkPermitByWorkPermitId,addBatchSpecialPermit } from "@/api/workPermit/specialPermit";
  import { listUser,getAllUserName } from "@/api/system/user";
  import { listAll } from "@/api/contractor/contractorInfo";
  import FlareUp from "@/components/NewSaftyWork/FlareUp";
  import BlindPlate from "@/components/NewSaftyWork/BlindPlate";
  import { listSign } from "@/api/workPermit/workPermitSign";
  import { listDept } from "@/api/system/dept";
  import NewEsign from "@/components/SaftyWork/NewEsign";
  import Editor from '@/components/Editor';
  import NewWorkPermitDetail from '@/components/DangerousMark/NewWorkPermitDetail';
  export default {
    name: "index",
    components:{
      FlareUp,
      BlindPlate,
      NewEsign,
      Editor,
      NewWorkPermitDetail
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 作业许可证表格数据
        permitList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
           pageNum: 1,
            pageSize: 10,
            applyDept: null,
            linkMan: null,
            linkPhone: null,
            workBound: null,
            deviceName: null,
            deviceNum: null,
            applyWorkStartTime: null,
            applyWorkEndTime: null,
            workContent: null,
            contractor: null,
            ratifier: null,
            mainDangerousMark: null,
            dangerousMarkDetial: null,
            licenceInfo: null,
            relationSign: null,
            produceComfirm: null,
            workDeal: null,
            applyStatus: null,
            remarks: null
        },
       // 表单参数
        form: {},
        // 表单校验
        rules: {
        applyDept: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
          linkPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
          workBound: [
          { required: true, message: "工作范围不能为空", trigger: "blur" }
        ],
          applyWorkStartTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
          applyWorkEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
          workContent: [
          { required: true, message: "工作内容不能为空", trigger: "blur" }
        ],
      },
        certificateStatus:[],
        approvalList:[],
        //承包商信息
        allContractorInfo:[],
        //新增作业许可单
        certificateData : {},
        mainDangerousMark :{
          burn : false,
            electricShock : false,
            objectStrike : false,
            stifle : false,
            drop : false,
            vehicleInjury : false,
            other : false
        },
        licenceInfo : {
          lockListing: {
            num: "",
              isChecked: false
          },
          blindPlate: {
            num: "",
              isChecked: false,
              status: "0"
          },
          breakGround: {
            num: "",
              isChecked: false,
              status: "0"
          },
          limitSpace: {
            num: "",
              isChecked: false,
              status: "0"
          },
          jsa: {
            no: false,
              yes: false,
              num: ""
          },
          specialLicence: false,
            flareUp: {
            num: "",
              isChecked: false,
              status: "0"
          },
          hoisting: {
            num: "",
              isChecked: false,
              status: "0"
          },
          ray: {
            num: "",
              isChecked: false,
              status: "0"
          },
          electricityUse: {
            num: "",
              isChecked: false,
              status: "0"
          },
          heightWork: {
            num: "",
              isChecked: false,
              status: "0"
          }
        },
        relationSign:{
          contractor:"",
          personCharge:""
        },
        produceComfirm:{
          leaderDeptId:"",
          monitorId:"",
          monitorName:"",
          date:""
        },
        workDeal:{
          suggestion:""
        },
        leaderDeptId:"",
        tags:[],
        active:"",
        certificateApprovalApplyOpen : false,
        certificateApprovalOpen:false,
        specialWorkPermits:[],
        approvalActive:"",
        deptList:[],
        userList:[],
        checkOpen:false,
        certificateCompleteOpen:false,
        workPermitId:"",
        certificateDetailOpen:false,
        certificateDataDetail:{}
      };
  },
  created() {
    this.getList();
    this.getAllContractorInfo();
    this.getDicts("t_new_permitWork_status").then(response => {
        this.certificateStatus = response.data;
    });
    this.getApproval();
    this.getDeptList();
  },
  methods: {
    /** 查询作业许可证列表 */
    getList() {
      this.loading = true;
      selectTWorkPermitListByLoginUser(this.queryParams).then(response => {
        this.permitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.certificateData = {};
      this.mainDangerousMark = {
        burn : false,
          electricShock : false,
          objectStrike : false,
          stifle : false,
          drop : false,
          vehicleInjury : false,
          other : false
      };
      this.licenceInfo = {
        lockListing: {
          num: "",
            isChecked: false
        },
        blindPlate: {
          num: "",
            isChecked: false,
            status: "0"
        },
        breakGround: {
          num: "",
            isChecked: false,
            status: "0"
        },
        limitSpace: {
          num: "",
            isChecked: false,
            status: "0"
        },
        jsa: {
          no: false,
            yes: false,
            num: ""
        },
        specialLicence: false,
          flareUp: {
          num: "",
            isChecked: false,
            status: "0"
        },
        hoisting: {
          num: "",
            isChecked: false,
            status: "0"
        },
        ray: {
          num: "",
            isChecked: false,
            status: "0"
        },
        electricityUse: {
          num: "",
            isChecked: false,
            status: "0"
        },
        heightWork: {
          num: "",
            isChecked: false,
            status: "0"
        }
      };
      this.relationSign = {
        contractor:"",
          personCharge:""
      };
      this.produceComfirm = {
        leaderDeptId:"",
          monitorId:"",
          monitorName:"",
          date:""
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.workPermitId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加作业许可证";
        this.certificateData.linkManName = this.$store.state.user.name;
        this.certificateData.linkMan = this.$store.state.user.userId;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const workPermitId = row.workPermitId || this.ids
        getPermit(workPermitId).then(response => {
            this.certificateData = response.data;
            this.certificateData.linkManName = this.applyNameFormate(this.certificateData);
            this.mainDangerousMark = JSON.parse(this.certificateData.mainDangerousMark);
            this.licenceInfo = JSON.parse(this.certificateData.licenceInfo);
            this.relationSign = JSON.parse(this.certificateData.relationSign);
            this.produceComfirm = JSON.parse(this.certificateData.produceComfirm);
            this.open = true;
            this.title = "修改作业许可证";
        });
      },
      /** 提交按钮 */
      addCertificate() {
        if(this.validateAddCertificate()){
          return;
        }
        this.certificateData.mainDangerousMark = JSON.stringify(this.mainDangerousMark);
        this.certificateData.licenceInfo = JSON.stringify(this.licenceInfo);
        this.certificateData.relationSign = JSON.stringify(this.relationSign);
        this.certificateData.produceComfirm = JSON.stringify(this.produceComfirm);
        if(this.certificateData.workPermitId != null){
          updatePermit(this.certificateData).then(response => {
            this.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }else{
          addPermit(this.certificateData).then(response => {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      },
      validateAddCertificate(){
        //许可证校验
        let flag = true;
        for(let key in this.licenceInfo){
          if(this.licenceInfo[key].isChecked){
            if(null == this.licenceInfo[key].num || '' == this.licenceInfo[key].num){
              this.msgError("许可证编号未填写");
              return flag;
            }
            flag = false;
          }
        }
        if(flag){
          this.msgError("许可证未选择！")
          return flag;
        }
        if(null == this.produceComfirm.monitorId || '' == this.produceComfirm.monitorId){
          this.msgError("生产组当班班长未选择！");
          return true;
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const workPermitIds = row.workPermitId || this.ids;
        this.$confirm('是否确认删除作业许可证编号为"' + workPermitIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPermit(workPermitIds);
        }).then(() => {
          this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有作业许可证数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
        return exportPermit(queryParams);
      }).then(response => {
          this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
      },
      //获取审核人
      getApproval(){
        getAllUserName().then(res =>{
            this.approvalList = res.data;
        })
      },
      applyNameFormate(row){
        var user = this.approvalList.find(item => item.userId == row.linkMan);
        if(user && user.userName){
          return user.userName;
        }
        return "";
      },
      applyStatusFormate(row){
        var value = this.certificateStatus.find(item => item.dictValue == row.applyStatus);
        if(value && value.dictLabel){
          return value.dictLabel;
        }
        return "";
      },
      //获取所有承包商
      getAllContractorInfo(){
        listAll().then(res =>{
            this.allContractorInfo = res.data;
        })
      },
      //作业单申请
      certificateApprovalApply(row){
        this.certificateApprovalApplyOpen = true;
        this.tags = [];
        const workPermitId = row.workPermitId;
        getPermit(workPermitId).then(res => {
          let licence = JSON.parse(res.data.licenceInfo);
          for(let key in licence){
            if(licence[key].isChecked){
              this.tags.push({workPermitId:workPermitId,licenceNum:licence[key].num,name:this.getTagName(key),mark:key})
            }
          }
          this.active = this.tags[0].name;
        })
      },
      //获取tag名称
      getTagName(key){
        switch(key){
          case "blindPlate":
            return "盲板抽堵作业许可";
          case "flareUp":
            return "动火作业许可证";
          case "heightWork":
            return "高处作业许可证";
          case "breakGround":
            return "动土作业许可证";
          case "hoisting":
            return "吊装作业许可证";
          case "limitSpace":
            return "受限空间作业许可证";
          case "electricityUse":
            return "临时用电许可证";
          case "ray":
            return "射线探伤许可证";
          default:
            return "";
        }
      },
      //tag切换
      handelToogel(item,type) {
        if(type == '1'){
          this.active = item;
        }
        if(type == '2'){
          this.approvalActive = item;
        }
      },
      cancelCertificateApply(){
        this.tags = [];
        this.active = "";
        this.certificateApprovalApplyOpen = false;
      },
      submitCertificateApply(){
        let param= {};
        param.tWorkPermit = {workPermitId:this.tags[0].workPermitId,applyStatus:"1"};
        param.specialWorkPermits = [];
        for(let i = 0;i<this.tags.length;i++){
          if(this.$refs[this.tags[i].mark][0].validateData()){
            return;
          }
          param.specialWorkPermits.push(this.$refs[this.tags[i].mark][0].addSpecialWorkPermit())
        };
        addBatchSpecialPermit(param).then(res =>{
          this.certificateApprovalApplyOpen = false;
          this.getList();
        })
      },
      //作业单审核
      certificateApproval(row){
        this.certificateApprovalOpen = true;
        this.specialWorkPermits = [];
        getSpecialWorkPermitByWorkPermitId({workPermitId:row.workPermitId}).then(res =>{
          let specialWorkPermits = res.data.specialWorkPermits;
          for(let key in specialWorkPermits ){
            if(-1 != specialWorkPermits[key].signs.findIndex(item => item.staffId === this.$store.state.user.userId)){
              this.specialWorkPermits.push(specialWorkPermits[key]);
              this.$nextTick(() => {
                this.$refs[specialWorkPermits[key].specialWorkType][0][specialWorkPermits[key].specialWorkType] = JSON.parse(specialWorkPermits[key].specialWorkData);
                this.$refs[specialWorkPermits[key].specialWorkType][0].specialWorkPermitId = specialWorkPermits[key].specialWorkPermitId;
                this.$refs[specialWorkPermits[key].specialWorkType][0].specialWorkPermitSigns = specialWorkPermits[key].signs;
              })
            }
          }
          this.approvalActive = this.specialWorkPermits[0].specialWorkType;
        })
      },
      cancelCertificateApproval(){
        this.certificateApprovalOpen = false;
      },
      //作业前检查
      certificateCheck(row){
        this.checkOpen=true;
        this.workPermitTitle = "事前检查";
        let workPermitId = row.workPermitId;
        getPermit(workPermitId).then(response => {
          this.certificateData = response.data;
          this.certificateData.linkMan = this.applyNameFormate( this.certificateData);
          this.mainDangerousMark = JSON.parse(this.certificateData.mainDangerousMark);
          this.licenceInfo = JSON.parse(this.certificateData.licenceInfo);
          this.relationSign = JSON.parse(this.certificateData.relationSign);
        })
      },
      /** 查询部门列表 */
      getDeptList() {
        listDept().then(response => {
            this.deptList = response.data;
        });
      },
      //部门切换
      switchDept(){
        this.produceComfirm.monitorId = "";
        listUser({ pageNum: 1,pageSize: 99999,deptId:this.produceComfirm.leaderDeptId}).then(response => {
            this.userList = response.rows;
        });
      },
      checkCancel(){
        this.checkOpen=false;
        this.reset();
      },
      checkSubmit(){
        if(this.produceComfirm.monitorName == null || this.produceComfirm.monitorName == ''){
          this.msgError("请签名！");
          return;
        }
        let produceComfirm = JSON.stringify(this.produceComfirm);
        updatePermit({workPermitId:this.certificateData.workPermitId,produceComfirm:produceComfirm,applyStatus:"3"}).then(response => {
          this.msgSuccess("签名成功");
          this.checkOpen = false;
          this.getList();
        });
      },
      //关闭作业单
      closeCertificate(row){
        this.workPermitId = row.workPermitId;
        this.certificateCompleteOpen = true;
      },
      completeSubmit(){
        updatePermit({workPermitId:this.workPermitId,workDeal:JSON.stringify(this.workDeal),applyStatus:"4"}).then(response => {
          this.msgSuccess("作业单关闭！");
          this.certificateCompleteOpen = false;
          this.getList();
        });
      },
      completeCancel(){
        this.certificateCompleteOpen = false;
      },
      certificateDetail(row){
        const workPermitId = row.workPermitId;
        getPermit(workPermitId).then(res => {
          this.certificateDataDetail = res.data;
          this.certificateDataDetail.linkMan = this.applyNameFormate(this.certificateDataDetail);
          this.certificateDetailOpen = true;
        })
      }
  }
  }
</script>

<style scoped lang="scss">
  table{
    border-collapse: collapse;
    table-layout: fixed;
    text-align: center;
    width: 100%;
  }
  table td, table th{
    border: 1px solid;
    height: 30px;
  }

  .editInput{
    border: none;
    width: 100%;
    height: 100%;
    text-align: center;
  }

  .editInput:focus{
    outline: none;
  }

  .editLine{
    border-bottom: 1px solid;
    border-top: none;
    border-left: none;
    border-right: none;
    text-align: center;
  }

  .editLine:focus{
    outline: none;
  }


  textarea{
    height: 100%;
    width: 100%;
    border: none;
    resize:none;
  }

  textarea:focus{
    outline: none;
  }


  .tags_box {
    height: 10%;
    display: flex;
    .tags {
      div {
        padding: 10px 20px;
        cursor: pointer;
        border: #cccccc 1px solid;
        #margin-right: 20px;
        #border-radius: 5px;
      }
      .isActive {
        background-color: #409EFF;
        color: white;
      }
    }
  }

  .con_box {
    height: 500px;;
    border: #cccccc 1px solid;
    padding: 10px;
    overflow-y: scroll;
    overflow-x: hidden;
    &::-webkit-scrollbar {
      width:5px;
    }
    &::-webkit-scrollbar-track {
      -webkit-box-shadow:inset006pxrgba(0,0,0,0.3);
      border-radius:10px;
    }
    &::-webkit-scrollbar-thumb {
      border-radius:5px;
      background:rgba(0,0,0,0.1);
      -webkit-box-shadow:inset006pxrgba(0,0,0,0.5);
    }
  }

</style>
