<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.operator=='approval'"
            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.operator=='review'"
            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.operator=='check'"
            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.operator=='working'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="certificateWorking(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >作业中</el-button>
          <el-button
            v-if="scope.row.operator=='close'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="closeCertificate(scope.row)"
            v-hasPermi="['system:permit:edit']"
          >关闭作业单</el-button>
          <el-button
            v-if="scope.row.applyStatus=='7'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="dangerousAppraise(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="880px" append-to-body>
      <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>

      </table>

      <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)">{{item.name}}</div>
        </div>
      </div>
      <div class="con_box">
        <div v-for="item in tags" v-if="active == item.name">
          <FlareUp v-if="item.mark == 'flareUp'"
                   :ref="item.mark"
                   :workPermitId = "item.workPermitId"
                   :licenceNum = "item.licenceNum"/>

        </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>

  </div>
</template>

<script>
  import { listPermit, getPermit, delPermit, addPermit, updatePermit, exportPermit } from "@/api/workPermit/permit";
  import { getAllUserName } from "@/api/system/user";
  import { listAll } from "@/api/contractor/contractorInfo";
  import FlareUp from "@/components/NewSaftyWork/FlareUp";
  export default {
    name: "index",
    components:{
      FlareUp
    },
    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"
          }
        },
        tags:[],
        active:"",
        certificateApprovalApplyOpen : false
      };
    },
    created() {
      this.getList();
      this.getAllContractorInfo();
      this.getDicts("certificateStatus").then(response => {
          this.certificateStatus = response.data;
      });
      this.getApproval();
    },
    methods: {
      /** 查询作业许可证列表 */
      getList() {
        this.loading = true;
        listPermit(this.queryParams).then(response => {
          this.permitList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          workPermitId: null,
          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: "0",
          createTime: null,
          updateTime: null,
          remarks: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      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.open = true;
          this.title = "修改作业许可证";
      });
      },
      /** 提交按钮 */
      addCertificate() {
        this.certificateData.mainDangerousMark = JSON.stringify(this.mainDangerousMark);
        this.certificateData.licenceInfo = JSON.stringify(this.licenceInfo);
        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();
          });
        }
      },
      /** 删除按钮操作 */
      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;
        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) {
        this.active = item;
      },
      cancelCertificateApply(){
        this.tags = [];
        this.active = "";
        this.certificateApprovalApplyOpen = false;
      },
      submitCertificateApply(){
        let that = this;
        let flag = true;
        this.tags.forEach(item =>{
          if(that.$refs[item.mark][0].addSpecialWorkPermit()){
            flag = false;
          }
        });
        //更新作业单状态
        if(flag){
          updatePermit({workPermitId:this.tags[0].workPermitId,applyStatus:"2"});
          this.certificateApprovalApplyOpen = false;
        }
      }

    }
  }
</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>
