<template>
  <div>
    <div class="card-top">
      <BaseTag :items="countlist" @getItem="changetable" @getSubItem="handleSubItem" />
    </div>
    <!-- 表格 -->
    <div>
      <div style="display: flex;justify-content: space-between;">
        <!-- 左侧部门列表 -->
        <div style="margin-left: 10px;width: 19%;height:calc(100vh - 350px);display: flex;flex-direction: column;">
          <div
            style="font-size:20px;font-weight: 600;color:black;padding: 10px;background-color: #d1f1e9;text-align: center;">
            辨识部门
          </div>
          <div style="flex: 1;overflow: auto;">
            <MOSTY.Table highlightCurrentRow :table-columns="tableColumn" :tableData="tableData1"
              :tableloading="tableloading" :isSelect="false" :isSort="false" style="width: 100%;height: 100%;"
              actionsW="100" @rowClick="rowClick">
              <template #num="{ row }">
                <span>{{ row.identifyAppraiseCount }}/{{ row.identifyResultCount }}</span>
              </template>
              <template #actions="{ row }">
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要驳回?"
                  @confirm="handelreject(row)">
                  <template #reference>
                    <el-button type="primary" class='mr10' :disabled="!isAqbm || !proms?.identifyEntityId"
                      v-if="['AQY', 'KZ'].includes(props.initPage.role) && ['21', '20'].includes(listpage.stage)">
                      <span>驳回</span>
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </MOSTY.Table>
          </div>
        </div>
        <div style="width: 80%;margin-left: 10px;margin-right:10px">
          <div style="height: calc(100vh - 350px)">
            <MOSTY.PageTree :pageTitle="'风险评价列表'" class="card-center" :isShowLeftTree="false">
              <template #serach>
                <el-divider />
                <MOSTY.Search :searchArr="searchArr" @submit="onSearch" @reset="OnchangeReset" />
                <el-divider />
                <div class="addbtn" style="margin-bottom: 10px;">
                  <el-button type="primary" @click="batchDelete">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    <span>批量删除</span>
                  </el-button>
                  <el-button type="primary" @click="handlehz">
                    <el-icon>
                      <CirclePlus />
                    </el-icon>
                    <span>提交审核</span>
                  </el-button>
                  <el-button type="primary" @click="Close">
                    <el-icon>
                      <ArrowLeft />
                    </el-icon>
                    <span>返回</span>
                  </el-button>
                </div>
              </template>
              <template #table>
                <section>
                  <el-table :data="tableData2" style="width: 100%;" height="330" stripe border v-loading="tableloading"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
                    <el-table-column label="序号" type="index" align="center" width="50" />
                    <el-table-column label="评价状态" prop="appraiseStatus" align="center">
                      <template #="{ row }">
                        <dict-tag :options="D_BZ_SF" :value="row.appraiseStatus" />
                      </template>
                    </el-table-column>
                    <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" width="150" align="left">
                        <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="descriptionInherent" align="center" />
                      <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" width="150" align="left">
                        <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="identifyAssignedUserName" align="center" />
                    </el-table-column>
                    <el-table-column label="操作" width='250' fixed="right">
                      <template #default="{ row }">
                        <span v-if="['21'].includes(zbbmzt) && row.isHadBtnAuth" class="operesee"
                          @click="handlepj(row, 'pj')"><el-icon>
                            <Compass />
                          </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>
                        <span class="operesee" @click="handlepj(row, 'xq')"><el-icon>
                            <Compass />
                          </el-icon>详情</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </section>
                <div class="fenye" :style="{ top: tableHeight }">
                  <el-pagination class="pagination" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" :current-page="listpage.pageCurrent"
                    :page-sizes="[2, 5, 10, 20]" :page-size="listpage.pageSize"
                    layout="total, prev, pager, next, sizes, jumper" :total="listpage.total"></el-pagination>
                </div>
              </template>
            </MOSTY.PageTree>
          </div>
        </div>
      </div>
    </div>
    <!-- 辨识-评价小组 -->
    <!-- <addPjxzTc ref="addPjxzTcRef" @ok="savebmyj" :planid="props.planid" /> -->
    <!-- 选择人员 -->
    <ChooseUser v-model="chooseUserVisible" :deptId="deptId" :data="userids" :Single="singleShow" :leaderid="leaderid"
      @choosedUsers="getSonValue">
    </ChooseUser>
    <!-- 选择参与部门: -->
    <ChooseDept v-if="showJkssbm" :formInfo="fromObj" :showDdld="showJkssbm" :searchType="'03'" @closezzjg="closeJhss"
      @listdata="getSonValue" :zzlx="zzlx" />
    <!-- 评价 -->
    <el-dialog custom-class="dialog_close" :height="'900'" v-model="showpjpage" v-if="showpjpage" :title="'风险评价'"
      :width="'65%'">
      <pJindex @close="changepjclose" @pjcg="handelpjcg" :planid="planid" :tjtype='tjtype'
        :deptcode='listpage.identifyAssignedDeptId' :idlist="idlist" />
    </el-dialog>
    <userModel v-model:ids="auditForm.userId" tcTitle="选择审核人" :Single="true" v-model:cName="auditForm.founderName"
      width="300" ref="userModelRef" @change="userModelChange" />
  </div>
</template>
<script setup>
// 引入
import { defineProps, watch, onMounted, getCurrentInstance, defineEmits, reactive, ref, computed } from 'vue'
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import ChooseDept from "@/components/MyComponents/ChooseDept/Depart.vue";
import * as MOSTY from "@/components/MyComponents/index";
import BaseTag from "@/views/dataReportWork/org/components/baseTag_fxpj.vue";
import pJindex from './pjindexNew.vue';
import { dateFormat } from "@/utils/tools.js"
import { ElMessage } from "element-plus";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import addPjxzTc from './component/addPjxzTc.vue';
import { filterqx } from "@/utils/auth.js";// isSgs,isgs,isxgs,isaqbm,isldbz
import { getSysDictByCode } from "@/api/sysDict";
import userModel from './component/userModel.vue';
const emits = defineEmits(["close"]);
const { proxy } = getCurrentInstance();
const { D_BZ_KNFXHGLX, D_BZ_SF } = proxy.$dict("D_BZ_KNFXHGLX", "D_BZ_SF");
/***是否安全部门 */
const isAqbm = filterqx('isaqbm') == '1'
const tableHeight = ref()
const showpjpage = ref(false)
const props = defineProps({
  btnshow: {
    default: true,
    type: Boolean
  },
  initPage: Object,
  title: String,
  planid: {
    type: String,
    default: null
  },
  orgCodeIds: {
    type: String,
    default: null
  },
  rowstatus: {
    type: String,
    default: null
  }
});
const userModelRef = ref(null)
const deptId = ref(null)
const tjtype = ref('pj')
const userids = ref([]);
const deptlist = ref([])
const ids = ref(null)
const shsm = ref(null)
/** 左边部门状态 */
const zbbmzt = ref(1)//左边部门状态
const total = ref(0)
const status = ref(2)
const zzlx = ref(null);
const showJkssbm = ref(false);//选择部门
const proms = ref({
})
const countlist = reactive([
  { nameTitle: "评价小组", nameLabel: ["组长", "组员"], dm: 'bmbsfgl', count: [0, 0], dm: 'pjxz', type: '0', icon: `aqss/icon_07.png` },
  { nameTitle: "作业环境", nameLabel: ["重大", "较大", "一般", "可容许"], count: [0, 0, 0, 0], dm: 'zyhj', type: '01', icon: `aqss/icon_01.png` },
  { nameTitle: "设备设施", nameLabel: ["重大", "较大", "一般", "可容许"], count: [0, 0, 0, 0], dm: 'sbss', type: '02', icon: `aqss/icon_02.png` },
  { nameTitle: "作业活动", nameLabel: ["重大", "较大", "一般", "可容许"], count: [0, 0, 0, 0], dm: 'zyhd', type: '03', icon: `aqss/icon_03.png` },
  // { nameTitle: "评价情况", nameLabel: ["已评价/待评价"], count: [0], dm: 'pjqk', type: '4', icon: `aqss/icon_04.png` },
  { nameTitle: "评价情况", nameLabel: ["已评价", "待评价"], count: [0, 0], dm: 'pjqk', type: '4', icon: `aqss/icon_04.png` },
])
const multipleSelection = ref([]); // 存储选中的数据
const listpage = ref({
  pageCurrent: 1,
  pageSize: 10,
  planId: props.planid
})
const gytype = ref([]);
const searchArr = reactive([
  {
    showType: "daterange",
    prop: "daterange",
    width: "350px",
    placeholder: "开始时间"
  },
  {
    showType: "select",
    prop: "riskLevel",
    width: '250px',
    options: gytype,
    placeholder: '请选择风险等级',
  },
  {
    showType: "input",
    prop: "identifyAssignedUserName",
    width: '250px',
    placeholder: '请输入辨识人',
  },
]);
function onSearch (obj) {
  // 重置所有筛选条件
  listpage.value.riskLevel = '';
  listpage.value.identifyAssignedUserName = '';
  listpage.value.identifyStartTime = '';
  listpage.value.identifyEndTime = '';

  // 设置搜索参数
  if (obj.riskLevel) {
    listpage.value.riskLevel = obj.riskLevel;
  }

  if (obj.identifyAssignedUserName) {
    listpage.value.identifyAssignedUserName = obj.identifyAssignedUserName;
  }

  // 处理日期范围
  if (obj.daterange && obj.daterange[0] && obj.daterange[1]) {
    listpage.value.identifyStartTime = obj.daterange[0];
    listpage.value.identifyEndTime = obj.daterange[1];
  }

  listpage.value.pageCurrent = 1;
  getpjxqTab();
}
const OnchangeReset = () => {
  // 清除所有筛选条件
  listpage.value.riskLevel = '';
  listpage.value.identifyAssignedUserName = '';
  listpage.value.identifyStartTime = '';
  listpage.value.identifyEndTime = '';
  listpage.value.identifyCategory = '';
  listpage.value.appraiseStatus = '';
  listpage.value.identifyAssignedDeptId = '';
  listpage.value.pageCurrent = 1;
  // getpjxqTab();
};
/** 重大风险辨识遗漏驳回 组件 */
const tableData1 = ref([])
const tableData2 = ref([])
const infoList = ref([])
const tableloading = ref(false)
const chooseUserVisible = ref(false);
const leaderid = ref("");
const singleShow = ref(true); //单选多选
const tableColumn = ref([
  {
    title: "部门名称",
    prop: "entityName",
    sortable: true
  },
  {
    title: "评价情况",
    prop: "num",
    slot: true,
    // sortable: true
  },
  // {
  //   title: "状态",
  //   prop: "stage",
  //   sortable: true,
  //   slot: true
  // },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const idlist = ref({
  planid: props.planid,
})
const auditForm = ref({
  userId: '',
});
const parentstatus = ref(null)
onMounted(() => {
  proms.value.planid = props.planid
  proms.value.orgCodeIds = props.orgCodeIds
  tabHeightFn();
  getpageDate()
  getpjxqTab()
  Promise.all([
    getSysDictByCode({ dictCode: "D_BZ_FXDJ" }),
  ]).then(([gytypeRes]) => {
    if (gytypeRes) {
      gytype.value = gytypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }

  }).catch(error => {
    console.error('获取字典数据失败:', error);
  });
  getpepoList()//获取评价小组统计
  getDeptIdentifyByScope()//查询部门辨识结果风险等级统计（根据范围）
  getpjxqcountlist()//查询部门辨识结果风险等级统计（根据范围）
})

//辨识评价-页面数据详情
function getpageDate () {
  // orgcode:只有评价小组登录才传orgcode
  getApi({ planid: props.planid }, '/mosty-jcgl/dangerPlanlist/bspj/showSjInfo').then(res => {
    tableData1.value = res.list
    let arr = tableData1.value.filter(item => {
      return (item.orangePointCount + item.redPointCount + item.yellowPointCount
        + item.bluePointCount) > 0
    })
    let arr2 = tableData1.value.filter(item => {
      return item.stage == '21'
    })

    // if (arr.length > 0) {
    //   handlexg(arr[0])
    // } else if (arr2.length > 0) {
    //   handlexg(arr2[0])
    // }
    infoList.value = res.list.map(item => {
      return { entityCode: item.entityCode, entityName: item.entityName, id: item.id, usernames: item.teamUsernames, userids: item.teamUserids }
    })
    deptlist.value = res.list.map(item => {
      return { value: item.entityCode, label: item.entityName }
    })
    shsm.value = res.shsm ? res.shsm : null
    // status.value = res.entity.status
    // listpage.value = res.entity;
    proms.value.identifyEntityId = res.entity.id;
    idlist.value.identifyEntityId = res.entity.id;
    parentstatus.value = res.entity.stage
    //     10-部门辨识中
    // 20-分公司辨识中 21-分公司汇总评价中
    // 30-整体任务辨识中 31-省、市公司分管领导审核中 32- 省、市公司主管领导审核中  33-完成
    if (['30', '31', '32'].includes(res.entity.stage)) {
      status.value = 3
    } else if (res.entity.stage == '33') {
      status.value = 4
    }
  })
}
/** 重大风险驳回 */
const handelreject = (row) => {
  const params = { deptId: row.entityCode, planId: props.planid }
  postApi(params, `/mosty-jcgl/tbDangerIdentifyResult/appraiseReject`).then(res => {
    if (res) {
      ElMessage({
        type: 'success',
        message: '重大风险辨识遗漏驳回成功！',
      })
      getpageDate()
      getpjxqTab();
      getpepoList()//获取评价小组统计
      getDeptIdentifyByScope();//查询部门辨识结果风险等级统计（根据范围）
      getpjxqcountlist();//查询部门辨识结果风险等级统计（根据范围）
    }

  })
};
// 批量删除
const batchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据');
    return;
  }

  // const hasAuth = multipleSelection.value.every(row =>
  //   ['21'].includes(zbbmzt.value) && row.isHadBtnAuth
  // );
  // if (!hasAuth) {
  //   ElMessage.warning('您没有权限删除选中的数据');
  //   return;
  // }

  try {
    await proxy.$modal.confirm(`确定要删除选中的 ${multipleSelection.value.length} 条数据吗？`);
    tableloading.value = true;
    const ids = multipleSelection.value.map(item => item.id).join(',');
    const res = await deleteApi({}, `/mosty-jcgl/tbDangerIdentifyResult/cancelByIds/${ids}`);

    if (res) {
      ElMessage.success('删除成功');
      multipleSelection.value = [];
      getpageDate()
      getpjxqTab();
      getpepoList()//获取评价小组统计
      getDeptIdentifyByScope();//查询部门辨识结果风险等级统计（根据范围）
      getpjxqcountlist();//查询部门辨识结果风险等级统计（根据范围）
    } else {
      ElMessage.error(res?.msg || '删除失败');
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('删除失败');
    }
  } finally {
    tableloading.value = false;
  }
};

//评价
function handlepj (row, type) {
  idlist.value = { ...row }
  idlist.value.bmbsid = row.id
  idlist.value.objid = row.objid
  tjtype.value = type
  showpjpage.value = true
}
//关闭汇总
function changepjclose (val) {
  showpjpage.value = false;
  // listpage.value.depcode = val;
  // getpjxqTab()
}
const getSonValue = (value) => {
  if (zzlx.value == '01') {
    infoList.value.forEach((el) => {
      if (el.id == ids.value) {
        el.usernames = value.map(it => { return it.userName }).toString();
        el.userids = value.map(it => { return it.id }).toString();
      }
    })
  }
};
//提交评价小组
function savebmyj () {
  // let arr = infoList.value.filter(it => {
  //   return it.userids
  // })
  // proms.value.infoList = infoList.value;
  // if (arr.length == infoList.value.length) {
  //   getSave(proms.value)
  // } else {
  //   // ElMessage.error("还有部门的评价人员未添加");

  // }
  // setAuthObj()
  getpjxqTab()
}
// 提交
const userModelChange = (val) => {
  const params = {
    identifyEntityId: proms.value.identifyEntityId,
    userId: auditForm.value.userId
  }
  postApi(params, `/mosty-jcgl/dangerPlanlist/bspj/tjsh`).then(res => {
    if (res) {
      ElMessage.success("提交成功");
      tableData2.value = []
      getpageDate()
      getpjxqTab();
      getpepoList()//获取评价小组统计
      getDeptIdentifyByScope();//查询部门辨识结果风险等级统计（根据范围）
      getpjxqcountlist();//查询部门辨识结果风险等级统计（根据范围）
    }
  })
}
//提交审核（负责人提交审核）
function handlehz () {
  // 	辨识评价-各个市、省公司提交审核
  userModelRef.value.show(true)
}

//	辨识评价-添加、修改评价小组
function getSave (data) {
  postApi(data, '/mosty-jcgl/dangerPlanlist/bspj/addOrEditPjxz').then(res => {
    ElMessage.success("修改成功");
    addyyShow.value = false;
    // getpageDate()
  })
}
const closeJhss = (val) => {
  showJkssbm.value = val
}

// 处理表格选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
// 控制行是否可选
const selectable = (row, index) => {
  // 返回true表示可选，false表示不可选（禁用）
  return row.isHadBtnAuth;
};
//   辨识评价 - 查询各个单位的辨识情况
async function getpjxqTab () {
  tableData2.value = []
  try {
    const res = await getApi(listpage.value, '/mosty-jcgl/tbDangerIdentifyResult/selectPage')
    listpage.value.total = res.total

    if (!res.records || res.records.length === 0) {
      tableData2.value = []
      return
    }

    // 并行进行所有权限检查
    const promises = res.records.map(async (item) => {
      try {
        const authRes = await getApi(
          { identifyResultId: item.id },
          '/mosty-jcgl/tbDangerIdentifyEvaluateMember/checkEvaluatePermission'
        )
        return {
          id: item.id,
          objid: item.objid,
          isHadBtnAuth: authRes || false,
          identifyAssignedUserName: item.identifyAssignedUserName,
          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 || 0) * (item.dangerBaseInherent?.sscore || 0),
          existingMeasures: item.dangerBaseCurrent?.existingMeasures,
          risklevelCurrent: item.dangerBaseCurrent?.risklevel,
          appraiseMaintainMeasures: item.appraiseMaintainMeasures,
          appraiseStatus: item.appraiseStatus,
        }
      } catch (error) {
        console.error(`权限检查失败，bmbsid: ${item.id}`, error)
        return {
          id: item.id,
          objid: item.objid,
          isHadBtnAuth: false,
          identifyAssignedUserName: item.identifyAssignedUserName,
          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 || 0) * (item.dangerBaseInherent?.sscore || 0),
          existingMeasures: item.dangerBaseCurrent?.existingMeasures,
          risklevelCurrent: item.dangerBaseCurrent?.risklevel,
          appraiseMaintainMeasures: item.appraiseMaintainMeasures,
          appraiseStatus: item.appraiseStatus,
        }
      }
    })

    tableData2.value = await Promise.all(promises)
  } catch (error) {
    console.error('获取辨识数据失败:', error)
    tableData2.value = []
  }
}
// 方法
const tabHeightFn = () => {
  tableHeight.value =
    window.innerHeight - 100 - 57 - 60 + 'px'
}
//删除
function deldetebm (row) {
  // 	部门汇总-部门辨识数据删除
  postApi({ bmbsid: row.id, identifyEntityId: proms.value.identifyEntityId }, '/mosty-jcgl/dangerPlanlist/hzDel').then(res => {
    if (res) {
      ElMessage.success("删除成功");
      getpageDate()
      getpjxqTab();
      getpepoList()//获取评价小组统计
      getDeptIdentifyByScope();//查询部门辨识结果风险等级统计（根据范围）
      getpjxqcountlist();//查询部门辨识结果风险等级统计（根据范围）
    }
  })
}
//返回
function Close () {
  emits("close");
}
//分页
const handleSizeChange = (currentSize) => {
  listpage.value.pageSize = currentSize;
  getpjxqTab()
};
const handleCurrentChange = (currentPage) => {
  listpage.value.pageCurrent = currentPage;
  getpjxqTab()
};

const rowClick = (row, column, event) => {
  // const countNum = row.orangePointCount + row.redPointCount + row.yellowPointCount + row.bluePointCount
  //   console.log('rowClickrowClick',row,countNum);
  // const isCanClick = row.stage == '21' || countNum > 0
  // if (!isCanClick) return
  // listpage.value.depcode = row.entityCode;
  listpage.value.identifyAssignedDeptId = row.entityCode;
  zbbmzt.value = row.stage
  getpjxqTab()
}
//	辨识评价-评价-查询评价小组情况
const getpepoList = async () => {
  let params = {
    planId: proms.value.planid || '',
  }
  try {
    const res = await getApi({}, `/mosty-jcgl/tbDangerIdentifyEvaluateTeam/selectCountByPlanId/${params.planId}`)
    if (res) {
      // 更新评价小组统计数据
      countlist[0].count = [
        res.teamLeaderCount || 0,  // 组长数量
        res.teamMemberCount || 0   // 组员数量
      ]
    }
  } catch (error) {
    console.error('获取评价小组数据失败:', error)
  }
}

// 处理子项点击
const handleSubItem = ({ item, subIndex }) => {
  // console.log('子项点击:', item, '子项索引:', subIndex);

  if (item.type === '4') {
    // 评价情况标签的点击
    changetable(item, subIndex);
  } else {
    // 其他标签还是整体点击
    changetable(item);
  }
};

// 修改changetable方法，支持第二个参数
const changetable = (item, subIndex = null) => {
  // console.log('标签点击:', item, '子项索引:', subIndex);

  // 重置相关筛选条件
  listpage.value.identifyCategory = '';
  listpage.value.appraiseStatus = '';

  // 根据type设置不同的参数
  switch (item.type) {
    case '01': // 作业环境
      listpage.value.identifyCategory = '01';
      break;
    case '02': // 设备设施
      listpage.value.identifyCategory = '02';
      break;
    case '03': // 作业活动
      listpage.value.identifyCategory = '03';
      break;
    case '4': // 评价情况
      // 根据点击的子项设置appraiseStatus
      if (subIndex === 0) {
        // 点击"已评价"
        listpage.value.appraiseStatus = '1';
      } else if (subIndex === 1) {
        // 点击"待评价"
        listpage.value.appraiseStatus = '2';
      } else {
        // 点击标题，不清除状态，显示全部
        listpage.value.appraiseStatus = '';
      }
      break;
    case '0': // 评价小组
    default:
      // 不做特殊处理
      break;
  }

  listpage.value.pageCurrent = 1;
  getpjxqTab();
}
// 查询部门辨识结果风险等级统计（根据范围）
const getDeptIdentifyByScope = async () => {
  let params = {
    planId: proms.value.planid || '',
    deptId: proms.value.orgCodeIds || '',
  }
  const res = await getApi(params, '/mosty-jcgl/tbDangerIdentifyResult/selectDeptIdentifyByScope')
  try {
    if (res) {
      // 更新作业环境（场所部位）的统计数据
      // 顺序：重大风险、较大风险、一般风险、可容许风险
      // 根据风险等级映射：深红(5) > 红(4) > 橙(3) > 黄(2) > 蓝(1)
      countlist[1].count = [
        res.sitePartRiskLevelCrimsonCount || 0,  // 特别重大风险(深红区)
        res.sitePartRiskLevelRedCount || 0,      // 重大风险(红区)
        res.sitePartRiskLevelOrangeCount || 0,   // 较大风险(橙区)
        res.sitePartRiskLevelYellowCount + res.sitePartRiskLevelBlueCount || 0  // 一般风险+可容许风险
      ]

      // 更新设备设施的统计数据
      countlist[2].count = [
        res.deviceFacilityRiskLevelCrimsonCount || 0,  // 特别重大风险(深红区)
        res.deviceFacilityRiskLevelRedCount || 0,      // 重大风险(红区)
        res.deviceFacilityRiskLevelOrangeCount || 0,   // 较大风险(橙区)
        res.deviceFacilityRiskLevelYellowCount + res.deviceFacilityRiskLevelBlueCount || 0  // 一般风险+可容许风险
      ]

      // 更新作业活动的统计数据
      countlist[3].count = [
        res.workActivityRiskLevelCrimsonCount || 0,  // 特别重大风险(深红区)
        res.workActivityRiskLevelRedCount || 0,      // 重大风险(红区)
        res.workActivityRiskLevelOrangeCount || 0,   // 较大风险(橙区)
        res.workActivityRiskLevelYellowCount + res.workActivityRiskLevelBlueCount || 0  // 一般风险+可容许风险
      ]

    }
  } catch (error) {
  }
}
// 查询评价情况统计
const getpjxqcountlist = async () => {
  let params = {
    planId: proms.value.planid || '',
    deptId: proms.value.orgCodeIds || '',
  }
  const res = await getApi(params, '/mosty-jcgl/tbDangerIdentifyResult/selectAppraiseCountByScope')
  try {
    if (res) {
      // 计算已评价和未评价数量
      const identifyResultCount = res.identifyResultCount || 0 // 辨识评论数量
      const identifyAppraiseCount = res.identifyAppraiseCount || 0 // 辨识结果数量
      const unappraisedCount = Math.max(0, identifyResultCount - identifyAppraiseCount) // 未评价数量

      // 更新评价情况的统计数据
      countlist[4].count = [
        identifyAppraiseCount,  // 辨识结果数量
        unappraisedCount        // 未评价数量
      ]
    }

  } catch (error) {
  }
}
// 评价成功
const handelpjcg = () => {
  getpageDate()
  getpjxqTab();
  getpepoList()//获取评价小组统计
  getDeptIdentifyByScope();//查询部门辨识结果风险等级统计（根据范围）
  getpjxqcountlist();//查询部门辨识结果风险等级统计（根据范围）
}
</script>

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

.el-form-item__label {
  padding: 12px 12px 0 0 !important;
}

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

.left {
  width: 70%;
}

.el-select {
  width: 150px;
}

.card-top {
  height: 139px;
}

.eltab7 {
  height: 345px;
  overflow: auto;
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin: 10px;
}

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

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

.tabBox2 {
  width: 65%;
}

.fil-bbox {
  display: flex;

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

    .labs {
      color: #999494;
    }
  }
}

.operates {
  cursor: pointer;
  color: yellowgreen !important;
  display: inline-block;
  width: 40px;
  height: 23px;
  border: 1px solid #000;
  margin: 0 5px;
  background-color: #fff;
}

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

.redfont {
  color: rgb(245, 34, 34) !important;
}

.box-big {
  display: flex;
  margin-top: 10px;

  .fix-box {
    display: flex;
    margin-right: 30px;
  }
}

.el-textarea {
  --el-input-placeholder-color: #4c4e52 !important;
}

.btnpas {
  display: inline-block;
  padding: 5px 10px;
  color: #fff !important;
  margin-right: 4px;
  background-color: var(--el-color-primary);
  border-radius: 5px;
  cursor: pointer;
}

.fxdjspan {
  display: inline-block !important;
  width: 100px;
  text-align: center;
  padding: 5px 0;
  border-radius: 5px;
  color: #fff !important;
}

.reds {
  background-color: #e80000;
}

.orgs {
  background-color: #ff8040;
}

.blus {
  background-color: #e2d101;
}

.gres {
  background-color: #0080ff;
}

.serial-num.disabled {
  color: #c0c4cc;
  opacity: 0.6;
  user-select: none;
  pointer-events: none;
}
</style>
