<template>
  <!-- 表格 -->
  <div class="box-a">
    <div class="leftbox">
      <div class="bs-title">*注：每个人员辨识条数必须大于0才能开始汇总</div>
      <div style="height: calc(100vh - 200px);">
        <!-- 左侧列表 -->
        <el-table ref="mulRef" stripe :data="tableData1" style="width: 100%;height: 100%;" v-loading="tableloading"
          element-loading-text="数据加载中..." @selection-change="handleSelectionChange" :height="tableHeight" border>
          <el-table-column label="姓名" property="userName">
          </el-table-column>
          <el-table-column property="num" label="辨识数">
            <template #default="scope">
              <span v-if="scope.row.num" :class="scope.row.num == 0 ? 'redfont' : ''">{{ scope.row.num
                }}</span>
              <span style="color: rgb(245, 34, 34) !important;" v-else>{{ scope.row.num }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="tableData1.some(item => item.num > 0)">
            <template #default="{ row }">
              <!-- <span class="operates" v-if="row.num == Number(0)" @click="handlexg(row)">原因</span> -->
              <!-- <span v-if="row.num > 0">已辨识</span> -->
              <span class="operates" v-if="row.num > 0" @click="handlexg(row)">查看</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="tabBox2 mr10 ml10">
      <div style="display: flex;justify-content: space-between;flex-wrap: wrap;">
        <div class="fil-bbox">
          <span class="font">风险单元：<span class="labs">{{ fromData.entity.entityName }}</span></span>
          <!-- <span class="font">辨识总数：<span class="labs">{{ fromData.count + fromData.delCount
                }}</span></span> -->
          <span class="font">部门辨识总人数：<span class="labs">{{ fromData.peopleCount }}</span></span>
          <span class="font">部门辨识总条数：<span class="labs">{{ fromData.count }}</span></span>
          <span class="font">已删除辨识总条数：<span class="labs">{{ fromData.delCount }}</span></span>
        </div>
        <div>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定辨识结束?"
            @confirm="changbs">
            <template #reference>
              <el-button type="primary" v-if="fromData.entity.stage == '10'" :disabled="!isShowbs">
                <span>辨识结束</span>
              </el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" @click="handelreset">
            <span>重置</span>
          </el-button>
          <el-button type="primary" @click="Close">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            <span>返回</span>
          </el-button>
        </div>
      </div>
      <div style="height: calc(100% - 290px);">
        <!-- 右侧固有风险识别与评估列表 -->
        <el-table :data="tableData2" style="width: 100%;" height="620" stripe border v-loading="tableloading"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" align="center" width="50" />
          <el-table-column label="固有风险识别与评估" align="center">
            <el-table-column label="辨识单元" prop="sitetypeInherent" align="center" />
            <el-table-column label="风险单元" prop="activityfacility" align="center" />
            <el-table-column label="风险描述" prop="descriptionInherent" align="center" />
            <el-table-column label="可能产生的后果" prop="consequenseInherent" align="center">
              <template #="{ row }">
                <span v-for="it in row.consequenseInherent.split(',')" :key="it" style="margin: 0 2px;display: flex;">
                  <dict-tag :options="D_BZ_KNFXHGLX" :value="it" :tag="false" style="display: flex;" />
                </span>
              </template>
            </el-table-column>
            <el-table-column label="风险严重程度" prop="sscoreInherent" align="center">
              <template #="{ row }">
                <el-tag v-if="row.sscoreInherent == 1" class="tab-box tab-box-blue">{{ '1' }}</el-tag>
                <el-tag v-else-if="row.sscoreInherent == 2" class="tab-box tab-box-yellow">{{ '2'
                  }}</el-tag>
                <el-tag v-else-if="row.sscoreInherent == 3" class="tab-box" type="warning">{{ '3'
                  }}</el-tag>
                <el-tag v-else-if="row.sscoreInherent == 4" class="tab-box tab-box-red">{{ '4' }}</el-tag>
                <el-tag v-else-if="row.sscoreInherent == 5" class="tab-box tab-box-red">{{ '5' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="风险等级" prop="risklevelInherent" align="center">
              <template #="{ row }">
                <el-tag v-if="row.risklevelInherent == 1" class="tab-box tab-box-blue">低风险(蓝区)</el-tag>
                <el-tag v-else-if="row.risklevelInherent == 2" class="tab-box tab-box-yellow">一般风险(黄区)</el-tag>
                <el-tag v-else-if="row.risklevelInherent == 3" class="tab-box" type="warning">较大风险(橙区)</el-tag>
                <el-tag v-else-if="row.risklevelInherent == 4" class="tab-box tab-box-red">重大风险(红区)</el-tag>
                <el-tag v-else-if="row.risklevelInherent == 5" class="tab-box tab-box-red">特别重大风险(深红区)</el-tag>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="现状风险识别与评估" align="center">
            <el-table-column label="现有控制措施" prop="existingMeasures" align="center" />
            <el-table-column label="可能存在的风险隐患" prop="description" align="center">
              <!-- <template #="{ row }">
                  <span v-for="it in row.description.split(',')" :key="it" style="margin: 0 2px;display: flex;">
                    <dict-tag :options="D_BZ_KNFXHGLX" :value="it" :tag="false" style="display: flex;" />
                  </span>
                </template> -->
            </el-table-column>
            <el-table-column label="L" prop="lscore" align="center" />
            <el-table-column label="S" prop="sscore" align="center" />
            <el-table-column label="R" prop="RScore" align="center" />
            <el-table-column label="现有风险等级" prop="risklevelCurrent" align="center">
              <template #="{ row }">
                <el-tag v-if="row.risklevelCurrent == 1" class="tab-box tab-box-blue">低风险(蓝区)</el-tag>
                <el-tag v-else-if="row.risklevelCurrent == 2" class="tab-box tab-box-yellow">一般风险(黄区)</el-tag>
                <el-tag v-else-if="row.risklevelCurrent == 3" class="tab-box" type="warning">较大风险(橙区)</el-tag>
                <el-tag v-else-if="row.risklevelCurrent == 4" class="tab-box tab-box-red">重大风险(红区)</el-tag>
                <el-tag v-else-if="row.risklevelCurrent == 5" class="tab-box tab-box-red">特别重大风险(深红区)</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="辨识人" prop="identifyActualUserName" align="center" />
          </el-table-column>
          <el-table-column label="操作" width='250' fixed="right">
            <template #default="{ row }">
              <!-- <span class="operesee" @click="handlepj(row, 'pj')"><el-icon>
                    <Compass />
                  </el-icon>评价
                </span> -->
              <!-- <span class="operedit" @click="handlepj(row, 'sy')"
                      v-if="props.initPage.role == 'KZ' && row.status == '02'"><el-icon>
                        <EditPen />
                      </el-icon>审验
                    </span> -->
              <!-- <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                  @confirm="deldetebm(row)" v-if="['21'].includes(zbbmzt) && row.isHadBtnAuth">
                  <template #reference>
                    <span class="operdel" size="small"><el-icon>
                        <Delete />
                      </el-icon>删除</span>
                  </template>
        </el-popconfirm> -->
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="deldetebm(row)">
                <template #reference>
                  <span class="operdel" size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <!-- <span class="operesee" @click="handlepj(row, 'xq')"><el-icon>
                    <Compass />
                  </el-icon>详情</span> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye" :style="{ top: tableHeight }">
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listQuery.pageIndex" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
            layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
        </div>
      </div>
    </div>
  </div>
  <!--请假原因弹窗 -->
  <el-dialog v-model="addyyShow"
    :title="showbtn ? '如果【' + titlename + '】因为特殊原因不能参加风险辨识，请填写相应原因' : '【' + titlename + '】不能参加风险辨识的原因'"
    :close-on-click-modal="false" width="50%" :show-close="false">
    <div>
      <el-form class="mosty-from-wrap" ref="elform" label-width="130px" :model="proms" :inline="true" :rules="rules"
        :disabled="!showbtn">
        <el-form-item prop="reason" style="width: 100%">
          <el-input v-model="proms.reason" type="textarea" :rows="10" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="savebmyj(elform)" :loading="loading" v-if="showbtn">确定</el-button>
        <el-button @click="addyyShow = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="xgfzrShow" :title="'提示'" :close-on-click-modal="false" width="20%" :show-close="false">
    <div>
      <span>部门{{ Name }}信息不正确，是否确认修改？</span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="xgfzrxx(Name)">确定</el-button>
        <el-button @click="xgfzrShow = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <div v-if="showhzpage" class="dialog-box">
    <Hzindex @close="changeclose" :idlist="idlist" :state="fromData.entity.status"
      :identifyEntityId="identifyEntityId" />
  </div>
  <div v-if="showhbsxq" class="dialog-box">
    <Bsxqinfo @close="changeclose" :idlist="idlist" :type="'bm'" :saveBtnShow="savebtn"
      :identifyEntityId="identifyEntityId" />
  </div>
  <!-- 选择人员 -->
  <ChooseUser v-model="chooseUserVisible" :zzlx="zzlx" :deptId="orgcode" :Single="singleShow" :leaderid="leaderid"
    @choosedUsers="getSonValue">
  </ChooseUser>
</template>
<script setup>
// 引入
import { defineProps, reactive, onMounted, getCurrentInstance, defineEmits, ref } from 'vue'
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import Hzindex from './hzindex.vue';
import Bsxqinfo from './bsxqinfo.vue';
import { ElMessageBox, ElMessage } from "element-plus"
const emits = defineEmits(["close"]);
const { proxy } = getCurrentInstance();
const { D_BZ_FXLX, D_BZ_FXDJS, D_BZ_KNFXHGLX } = proxy.$dict("D_BZ_FXLX", "D_BZ_FXDJS", "D_BZ_KNFXHGLX");
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  title: String,
  planid: {
    type: String,
    default: null
  },
});
const listpage = ref({
  pageCurrent: 1,
  pageSize: 10,
  planId: props.planid
})
const savebtn = ref(false)
const tableHeight = ref()
const showhzpage = ref(false)
const showhbsxq = ref(false)
const elform = ref();
const loading = ref(false);
const isFaill = ref(true);
const showbtn = ref(false);
const xgfzrShow = ref(false);
const chooseUserVisible = ref(false);
const leaderid = ref("");
const Name = ref("");
const singleShow = ref(true); //单选多选
const listQuery = ref({
  planid: props.planid
});
const fromData = ref({
  entity: { entityName: '' }
})
const proms = ref({
})
const idlist = ref({
  planid: props.planid,
})
const total = ref(0);
const identifyEntityId = ref(null);
const titlename = ref('');
const orgcode = ref(null);
const zzlx = ref(null);
const tableData2 = ref([])
const tableData1 = ref([])
const tableloading = ref(false)
const tableloadings = ref(false)
const addyyShow = ref(false)
const rules = reactive({
  reason: [{ required: true, message: "请输入请假原因", trigger: "blur" }],
});

onMounted(() => {
  tabHeightFn();
  reast()
})
//刷新页面
function reast () {
  getTabList();
  getpepo();

}
//获取表单数据
function getTabList () {
  getApi({ planid: props.planid }, '/mosty-jcgl/dangerPlanlist/getBmhzInfo').then((res) => {
    if (res) {
      fromData.value = res;
      proms.value.refId = res.entity.id
      identifyEntityId.value = res.entity.id
      orgcode.value = res.entity.entityCode

    }
    if (orgcode.value) {
      gettabList()
    }
  }).catch(() => {
    emits("close");
  });
}
// 是否部门人员都有辨识数
const isShowbs = ref(true)
const userId = ref(null)
//获取 	部门汇总-人员列表
function getpepo () {
  tableloading.value = true
  getApi({ planid: props.planid }, '/mosty-jcgl/dangerPlanlist/getBmhzRyList').then((res) => {
    if (res) {
      tableData1.value = res
      let i = 0
      while (i < tableData1.value.length && isShowbs.value) {
        if (tableData1.value[i].num === 0) isShowbs.value = false
        i++
      }
    }
  })
  tableloading.value = false
}
//   辨识评价 - 查询各个单位的辨识情况
function gettabList () {
  tableData2.value = []
  let params = {
    ...listpage.value,
    identifyAssignedDeptId: orgcode.value || ''
  }
  if (userId.value) {
    params.identifyAssignedUserId = userId.value
  }
  getApi(params, '/mosty-jcgl/tbDangerIdentifyResult/selectPage').then(async (res) => {
    total.value = res.total
    const results = []
    // for (const item of res?.records) {
    //   try {
    //     let params = {
    //       // identifyOrgId: listpage.value.depcode,
    //       bmbsid: item.id,
    //     }
    //     const authRes = await getApi(params, '/mosty-jcgl/tbDangerIdentifyEvaluateMember/checkEvaluatePermission')
    //     results.push({
    //       ...item,
    //       isHadBtnAuth: authRes || false
    //     })
    //   } catch (error) {
    //     results.push({
    //       ...item,
    //       isHadBtnAuth: false
    //     })
    //   }
    // }
    res.records.forEach((item) => {
      tableData2.value.push({
        id: item.id,
        objid: item.objid,
        isHadBtnAuth: item.isHadBtnAuth,
        identifyActualUserName: item.identifyActualUserName,
        sitetypeInherent: item.dangerBaseInherent.sitetype,
        activityfacility: item.dangerBaseInherent.activityfacility,
        descriptionInherent: item.dangerBaseInherent.description,
        consequenseInherent: item.dangerBaseInherent.consequense,
        sscoreInherent: item.dangerBaseInherent.sscore,
        risklevelInherent: item.dangerBaseInherent.risklevel,
        lscore: item.dangerBaseCurrent.lscore,
        sscore: item.dangerBaseCurrent.sscore,
        RScore: item.dangerBaseCurrent.lscore * item.dangerBaseInherent.sscore,
        existingMeasures: item.dangerBaseCurrent.existingMeasures,
        description: item.dangerBaseCurrent.description,
        risklevelCurrent: item.dangerBaseCurrent.risklevel,
      })
    })
  })
}
// function gettabList () {
//   tableloadings.value = true;
//   getApi(listQuery.value, '/mosty-jcgl/dangerPlanlist/getBmbsPage').then((res) => {
//     if (res) {
//       tableData.value = res.records;
//       total.value = res.total


//     }
//   })
//   tableloadings.value = false;

// }
//原因
const handlexg = (row) => {
  userId.value = row.userId
  gettabList()
  // proms.value.userId = row.userId
  // if (fromData.value.entity.stage != '10') {
  //   proms.value.reason = row.reason;
  //   showbtn.value = false;
  // } else {
  //   proms.value.reason = row.reason ? row.reason : ''
  //   showbtn.value = true;
  // }
  // titlename.value = row.userName
  // addyyShow.value = true
};
// 重置左侧列表
const handelreset = () => {
  userId.value = null
  gettabList()
}
//点击辨识结束
function changbs () {
  postApi({}, `/mosty-jcgl/dangerPlanlist/updateStage/${proms.value.refId}`).then(res => {
    proxy.$message.success("辨识结束");
    reast()
  })
}
//修改负责人
function xgfzrxx (val) {
  singleShow.value = true;
  chooseUserVisible.value = true;
  if (val == '负责人') {
    zzlx.value = '01';
  } else {
    zzlx.value = '02';
  }

}
const getSonValue = (val) => {
  let data = {
    deptid: orgcode.value,
    username: val[0].userName,
    userid: val[0].id,
  }
  if (zzlx.value == '01') {
    postApi(data, '/mosty-jcgl/securitychild/updateFzrByDeptid').then(res => {
      proxy.$message.success("负责人修改成功");

    })
  } else {
    postApi(data, '/mosty-jcgl/securitychild/updateFgldByDeptid').then(res => {
      proxy.$message.success("修改成功");
    })
  }
  xgfzrShow.value = false
  reast()
}
//返回
function Close () {
  emits("close");
}
//汇总删除
function deldete (row) {
  postApi({ identifyEntityId: identifyEntityId.value, bmbsid: row.id }, '/mosty-jcgl/dangerPlanlist/hzDel').then((res) => {
    proxy.$message.success("删除成功");
    reast()
  })
}
//修改
function handlehz (row) {
  idlist.value.dangerid = row.dangerid;
  idlist.value.bmbsid = row.id
  savebtn.value = true
  showhbsxq.value = true
}
//详情
function handlehxq (row) {
  idlist.value.dangerid = row.dangerid;
  idlist.value.bmbsid = row.id
  savebtn.value = false
  if (row.identifyUserCount > 1) {
    showhzpage.value = true
  } else {
    showhbsxq.value = true
  }
}
//关闭汇总
function changeclose (val) {
  showhzpage.value = false
  showhbsxq.value = false
  isFaill.value = true
  reast()
}
// 方法
const tabHeightFn = () => {
  tableHeight.value =
    window.innerHeight - 100 - 57 - 60 + 'px'
}
//提交审核
function handlesh () {
  for (let i = 0; i < tableData.value.length; i++) {
    const item = tableData.value[i]
    if (item.status == '0' && item.identifyUserCount > 1) {
      proxy.$message.warning("还有汇总未完成");
      isFaill.value = false
      break
    }
  }
  if (isFaill.value) {
    postApi({}, `/mosty-jcgl/dangerPlanlist/updateStage/${proms.value.refId}`).then(res => {
      proxy.$message.success("提交成功");
      reast()
    })
  }

}
//修改
function xgchange (val) {
  Name.value = val
  xgfzrShow.value = true;
}
//提交原因
const savebmyj = async (formEl) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      postApi(proms.value, '/mosty-jcgl/dangerPlanlist/addException').then((res) => {
        proxy.$message.success("提交成功");
        addyyShow.value = false;
        getpepo();
      })
      loading.value = false;
    } else {
      loading.value = false;
      proxy.$message.warning('请输入原因！！！')
    }
  });
};

//删除
function deldetebm (row) {
  // 	部门汇总-部门辨识数据删除
  deleteApi({}, `/mosty-jcgl/tbDangerIdentifyResult/${row.id}`).then(res => {
    if (res) {
      ElMessage.success("删除成功");
      // getpageDate()
      gettabList()
    }

  })
}
//分页
const handleSizeChange = (currentSize) => {
  listpage.value.pageSize = currentSize;
  gettabList();
};
const handleCurrentChange = (currentPage) => {
  listpage.value.pageSize = currentSize;
  gettabList();
};
</script>

<style lang="scss" scoped>
.titleBox {
  border: none;
  height: 152px;
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 2;
}

.box-a {
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
}

.stebox {
  width: 90%;
  display: flex;
  justify-content: center;
  position: relative;
  align-items: center;
  margin: o auto;
}

.left {
  width: 70%;
}

.el-select {
  width: 150px;
}

.btnBox {
  right: 15px;
  top: 9px;
  width: 10%;
  text-align: right;
  padding-right: 10px;
}

.bs-title {
  color: red;
  margin: 10px;
}

.leftbox {
  width: 30%;
  // margin-right: 40px;
}

.tabBox2 {
  width: 70%;
}

.fil-bbox {
  display: flex;

  .font {
    color: #000;
    font-size: 16px;
    font-weight: 600;
    margin: 10px;

    .labs {
      color: #999494;
    }
  }
}

.operates {
  cursor: pointer;

  color: #067a97 !important;
  text-align: center;
  padding: 2px 4px;
}

.operated {
  cursor: pointer;
  color: #fff !important;
  display: inline-block;
  width: 40px;
  height: 23px;
  margin: 0 5px;
  background-color: #f11515;
  border-radius: 5px;
}

.redfont {
  color: rgb(245, 34, 34) !important;
}
</style>
