<template>
  <div class="card-box">
    <div class="card-top" style="height: 100%;">
      <BaseTag :items="countlist" :num="3" @getItem="changetable" />
    </div>
    <div style="display: flex;">
      <!-- 组织机构信息 -->
      <div class="left" :style="{ width: lfBoxWid }">
        <div class="title">
          <div style="display: flex; align-items: center">
            <div style="padding-top: 5px; margin-right: 5px">
              <el-icon style="color: var(--el-color-primary) !important">
                <List />
              </el-icon>
            </div>
            <span class="zzjgxx" v-if="iconChange">风险单元分类</span>
          </div>
          <el-icon @click="handleCollapse" v-show="iconChange">
            <DArrowLeft />
          </el-icon>
          <el-icon @click="handleCollapse" v-show="!iconChange">
            <DArrowRight />
          </el-icon>
        </div>
        <div class="treeBox">
          <!-- <PcflTree width="100%" clearable filterable @getdeptData="getdeptData" /> -->
          <riskUnitTypeTree width="100%" @change="getdeptData" />
        </div>
      </div>
      <MOSTY.PageTree class="card-center" :isShowLeftTree="false"
        :style="{ width: lfBoxWid === '300px' ? '87%' : '98%' }">
        <template #serach>
          <el-divider />
          <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
          <el-divider />
          <div class="fxtitle">
            风险辨识列表(
            <span class="title-one">辨识人员:{{ personCount }}</span>
            <span class="title-two"> 风险数量:{{ riskCount }})</span>
          </div>
          <el-divider />
          <div class="addbtn">
            <!-- <el-button :disabled="isAddShow" style="margin-bottom: 10px;" type="primary" @click="handleAdd">
              <el-icon>
                <CirclePlus />
              </el-icon>
              <span>新增风险</span>
            </el-button> -->
            <el-button type="primary" @click="batchDelete">
              <el-icon>
                <Delete />
              </el-icon>
              <span>批量删除</span>
            </el-button>
            <el-button type="primary" @click="changbs">
              <span>结束辨识</span>
            </el-button>
            <el-button type="primary" @click="sumbitBs">
              <span>提交</span>
            </el-button>
          </div>
        </template>
        <template #table>
          <section class="eltab7">
            <el-table :data="tableData" style="width: 100%" stripe border v-loading="tableloading"
              @selection-change="handleSelectionChange" height="400">
              <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="existingMeasuresCurrent" align="center" />
                <el-table-column label="可能存在的风险隐患" prop="consequenseCurrent" align="center">
                  <template #="{ row }">
                    <span v-for="it in row.consequenseCurrent.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="操作" fixed="right">
                <template #default="{ row }">
                  <el-link type="primary" style="margin-right: 10px;" @click="onView(row)">查看</el-link>
                  <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                    @confirm="onDelete(row)">
                    <template #reference>
                      <el-link type="danger">删除</el-link>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </section>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="listQuery" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
            </MOSTY.Pages>
          </div>
        </template>
      </MOSTY.PageTree>
    </div>
    <!-- 新增功能 -->
    <addrisk ref="addriskRef" @ok="headerEditOk" />
  </div>
</template>
<script setup>
// 引入
import { reactive, watch, onMounted, getCurrentInstance, ref } from 'vue'
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, postApi } from "@/api/tobAcco_api.js";
import riskUnitTypeTree from "@/views/fxgk/aqfxfjgk/component/riskUnitTypeTree.vue";
import { getSysDictByCode } from "@/api/sysDict";
import { dateFormat } from "@/utils/tools.js"
import { getItem } from "@/utils/storage";
import BaseTag from "@/views/dataReportWork/org/components/baseTag_riskidentification.vue";
import addrisk from "./components/addrisk.vue";
const { proxy } = getCurrentInstance();
const { D_BZ_FXDJS, D_BZ_KNFXHGLX } = proxy.$dict("D_BZ_FXDJS", "D_BZ_KNFXHGLX")
// 统计信息
const personCount = ref(0)
const riskCount = ref(0)
const addriskRef = ref(null);
const tableloading = ref(false)
const gytype = ref([]);
// 表格数据
const tableData = ref([])
const multipleSelection = ref([]) // 多选数据
const countlist = reactive([
  { nameTitle: [{ name: "部门辨识覆盖率", count: 0 }], nameLabel: [{ label: "部门辨识参与率", count: 0 }], dm: 'bmbsfgl', type: '0', icon: `aqss/icon_00.png` },
  { nameTitle: [{ name: "总人数", count: 0 }, { name: "参与数", count: 0 }], nameLabel: [{ label: "参与辨识人数", count: 0 }, { label: "未参与辨识人数", count: 0 }], count: 0, dm: 'all', type: '1', icon: `aqss/icon_00.png` },
  { nameTitle: [{ name: "覆盖率", count: 0 }], nameLabel: [{ label: "场所数", count: 0 }, { label: "场所辨识数", count: 0 }, { label: "部位数", count: 0 }, { label: "部位辨识数", count: 0 }], count: 0, dm: 'gw', type: '2', icon: `aqss/icon_01.png` },
  { nameTitle: [{ name: "设备设施数量", count: 0 }], nameLabel: [{ label: "已辨识数量", count: 0 }, { label: "覆盖率", count: 0 }], count: 0, dm: 'bm', type: '3', icon: `aqss/icon_02.png` },
  { nameTitle: [{ name: "作业活动风险数", count: 0 }], nameLabel: [], count: 0, dm: 'jd', type: '4', icon: `aqss/icon_03.png` },
])
const searchArr = reactive([
  {
    showType: "daterange",
    prop: "daterange",
    width: "350px",
    defaultVal: [dateFormat({ type: "firstday" }), dateFormat()],
    placeholder: "开始时间"
  },
  {
    showType: "select",
    prop: "riskLevel",
    width: '250px',
    options: gytype,
    placeholder: '请选择风险等级',
  },
  {
    showType: "input",
    prop: "identifyActualUserName",
    width: '250px',
    placeholder: '请输入辨识人',
  },
]);


// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  total: 0,
  identifyActualDeptId: getItem("deptId").ssbmdm,
  identifyStartTime: dateFormat({ type: "firstday" }) + ' 00:00:00',
  identifyEndTime: dateFormat() + ' 23:59:59',
  // riskType: "",
});

onMounted(() => {
  Promise.all([
    getSysDictByCode({ dictCode: "D_BZ_FXDJS" }),
  ]).then(([gytypeRes]) => {
    if (gytypeRes) {
      gytype.value = gytypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }

  }).catch(error => {
    console.error('获取字典数据失败:', error);
  });
  getTabList()
})
// 新增
const handleAdd = () => {
  addriskRef.value.openDialog(riskData.value, 'add')
}

// 树的展开与折叠
const iconChange = ref(true);
const lfBoxWid = ref("300px");
const handleCollapse = () => {
  iconChange.value = !iconChange.value;
  if (iconChange.value) {
    lfBoxWid.value = "300px";
  } else {
    lfBoxWid.value = "40px";
  }
};
const isAddShow = ref(true)
const riskData = ref()
//获取部门数据
const getdeptData = (val, node, lev1) => {
  isAddShow.value = true
  riskData.value = {
    sitetypeInherent: lev1.name,
    sitetypeInherentId: lev1.id,
    activityfacility: node.name,
    activityfacilityId: node.id,
    identifyActualUserName: getItem("USERNAME"),
    identifyActualDeptId: getItem("deptId").ssbmdm,
  }
  if (node.children.length === 0) isAddShow.value = false
  listQuery.value.partType = val
  getTabList();
  // getStatistics()
};
//查询
function onSearch(obj) {
  if (obj.daterange && obj.daterange.length) {
    listQuery.value.identifyStartTime = obj.daterange[0] + ' 00:00:00'
    listQuery.value.identifyEndTime = obj.daterange[1] + ' 23:59:59'
  } else {
    listQuery.value.identifyStartTime = dateFormat({ type: "firstday" }) + ' 00:00:00'
    listQuery.value.identifyEndTime = dateFormat() + ' 23:59:59'
  }
  listQuery.value.riskLevel = obj.riskLevel
  listQuery.value.identifyActualUserName = obj.identifyActualUserName
  listQuery.value.pageCurrent = 1
  getTabList();
  // getStatistics()
}
// 获取统计数据
function getStatistics() {
  const params = {
    identifyActualDeptId: listQuery.value.identifyActualDeptId,
    identifyStartTime: listQuery.value.identifyStartTime,
    identifyEndTime: listQuery.value.identifyEndTime
  }
  getApi(params, '/mosty-jcgl/dangerPlanlist/getStatistics').then((res) => {
    if (res) {
      personCount.value = res.personCount || 0
      riskCount.value = res.riskCount || 0

      // 更新countlist
      countlist[0].count = res.personCount || 0
      countlist[1].count = res.personCount || 0
      countlist[2].count = res.environmentCount || 0
      countlist[3].count = res.equipmentCount || 0
      countlist[4].count = res.activityCount || 0
    }
  }).catch(() => {
    // 如果接口不存在，使用默认数据
    personCount.value = 0
    riskCount.value = tableData.value.length
  })
}

//获取表格数据
function getTabList() {
  tableloading.value = true
  tableData.value = []
  getApi(listQuery.value, '/mosty-jcgl/tbDangerIdentifyResult/selectPage').then((res) => {
    listQuery.value.total = res.total;
    res.records.forEach((item) => {
      tableData.value.push({
        id: item.id,
        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,
        existingMeasuresCurrent: item.dangerBaseCurrent.existingMeasures,
        consequenseCurrent: item.dangerBaseCurrent.consequense,
        risklevelCurrent: item.dangerBaseCurrent.risklevel,
      })
    })
  }).finally(() => {
    tableloading.value = false
  })
}
// 删除
const onDelete = (row) => {
  deleteApi({}, `/mosty-jcgl/tbDangerIdentifyResult/${row.id}`).then(() => {
    proxy.$message.success("删除成功");
    getTabList();
  });
};
// 查看
const onView = (row) => {
  addriskRef.value.openDialog(row, 'view')
};
//条数
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getTabList();
};
// 页码
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getTabList();
};
// 表格多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 批量删除
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    proxy.$message.warning('请选择要删除的数据')
    return
  }

  proxy.$confirm(`确定要删除选中的${multipleSelection.value.length}条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id)

    // 根据接口情况选择批量删除方式
    if (ids.length === 1) {
      // 单个删除
      deleteApi({}, `/mosty-jcgl/tbDangerIdentifyResult/${ids[0]}`).then(() => {
        proxy.$message.success('删除成功')
        getTabList()
        getStatistics()
        multipleSelection.value = []
      })
    } else {
      // 批量删除
      postApi({ ids }, '/mosty-jcgl/dangerPlanlist/batchDelete').then(() => {
        proxy.$message.success('删除成功')
        getTabList()
        getStatistics()
        multipleSelection.value = []
      }).catch(() => {
        // 用户取消删除

      })
    }
  }).catch(() => {
    // 用户取消删除
  })
}
//点击辨识结束
function changbs() {
  postApi({}, `/mosty-jcgl/dangerPlanlist/updateStage/${proms.value.refId}`).then(res => {
    proxy.$message.success("辨识结束");
    reast()
  })
}
//提交
function sumbitBs() {
  console.log('提交')
}
// tag切换
const changetable = (item) => {
  if (item.type !== '0') {
    listQuery.value.riskType = item.type
  } else {
    listQuery.value.riskType = ""
  }
  listQuery.value.pageCurrent = 1
  getTabList()
}
</script>
<style lang="scss" scoped>
.card-box {
  display: flex;
  flex-direction: column;

  .card-top {
    height: 140px;
  }

  .left {
    width: 300px;
    background: #ffffff;
    box-shadow: 0px 2px 10px 0px rgba(107, 107, 107, 0.1);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;

    .title {
      height: 39px;
      line-height: 39px;
      font-size: 18px;
      color: #0f3916;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .el-icon {
        cursor: pointer;
      }

    }

    .treeBox {
      overflow: auto;
      height: 90%;
      max-height: 61vh;
    }
  }

  .card-center {
    height: calc(100% - 140px);
  }
}

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

.toggle {
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #0f3916;

  .el-icon {
    transform: rotate(90deg);
    transition: all 0.25s ease;
  }

  &.active {
    .el-icon {
      transform: rotate(-90deg);
    }
  }
}

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

.addbtn {
  display: flex;
}

.tab-box-blue {
  --el-tag-bg-color: #7f99e7;
  --el-tag-border-color: #268ae8;
  --el-tag-text-color: #1f6eb4;
  --el-tag-hover-color: #1551b2;
}

.tab-box-yellow {
  --el-tag-bg-color: #e7e57f;
  --el-tag-border-color: #e8e526;
  --el-tag-text-color: #dec90d;
  --el-tag-hover-color: #e7d10e;
}

.tab-box-orange {
  --el-tag-bg-color: #e7a97f;
  --el-tag-border-color: #e87726;
  --el-tag-text-color: #c54404;
  --el-tag-hover-color: #cd580a;
}

.tab-box-red {
  --el-tag-bg-color: #e78b7f;
  --el-tag-border-color: #e84026;
  --el-tag-text-color: #cf220f;
  --el-tag-hover-color: #d21f0b;
}

.fxtitle {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: 400;
  font-size: 20px;
  color: #000000;

  .title-one {
    font-weight: 400;
    font-size: 20px;
    color: rgb(1, 115, 89, 1);
  }

  .title-two {
    font-weight: 400;
    font-size: 20px;
    color: rgb(1, 115, 89, 1);
  }
}
</style>
