<template>
  <MOSTY.PageTree :pageTitle="'评价小组成员分工清单'" :searchType="'03'" :isShowLeftTree="false" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <!-- <MOSTY.Search :searchArr="searchArr" @submit="onSearch" /> -->
      <div class="btnBox">
        <el-button style="margin-bottom: 5px;" type="primary" @click="onloadExcel" v-loading="exportLoading">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出</span>
        </el-button>
        <el-button style="margin-bottom: 5px;" type="primary" @click="handleReturn">
          <el-icon>
            <Back />
          </el-icon>
          <span>返回上级</span>
        </el-button>
      </div>
    </template>
    <template #table>
      <div class="eltab99">
        <el-table ref="multipleTableRef" :data="tableData" height="100%" stripe style="width: 100%" border :fit="true">
          <el-table-column label="序号" type="index" align="center" width="100" />
          <el-table-column label="岗位" property="teamMemberUserPositionName"></el-table-column>
          <el-table-column label="姓名" property="teamMemberUserName"></el-table-column>
          <el-table-column label="部门" property="teamMemberOrgName"></el-table-column>
          <el-table-column label="评价范围" property="scopeOrgNames"></el-table-column>
          <el-table-column label="操作" fixed="right" max-width="200">
            <template #default="scope">
              <span class="operesee" @click="handlesetfg(scope.row)"><el-icon>
                  <EditPen />
                </el-icon>配置评价范围</span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="handledelete(scope.row, $index)">
                <template #reference>
                  <span class="operdel" size="small">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除</span>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange">
        </MOSTY.Pages>
      </div>
    </template>
  </MOSTY.PageTree>
  <!-- 选择部门 -->
  <ChooseDept v-if="showDept" :formInfo="cybmList" :showDdld="showDept" @closezzjg="showDept = false"
    @listdata="getUserOrDept" />
  <!-- 风险单元 -->
  <bshzTree  v-if="showdialog" ref="riskTreeRef" :showdialog="showdialog" width="100%" @save="handleSaveDept"
    @dialogshow="dialogshow" :selected-data="selectedRiskUnit" />
</template>
<script setup>
// 引入
import { onMounted, ref, getCurrentInstance, defineEmits, defineProps, watch, nextTick } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { exportXlsx } from "@/excel/Export2Excel.js";
import ChooseDept from "@/components/MyComponents/ChooseDept/Departqx.vue";
import bshzTree from "./bshzTree.vue";
const { proxy } = getCurrentInstance();
const { D_BZ_YHLX, D_BZ_FXDYLX, D_BZ_FXDJS } = proxy.$dict("D_BZ_YHLX", "D_BZ_FXDYLX", "D_BZ_FXDJS");
const props = defineProps({
  itemList: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits(['close'])
const exportLoading = ref(false)
const cybmList = ref({})
const id = ref('') //评价小组id
const scopeList = ref([]) //评价范围
const showDept = ref(false);
const showdialog = ref(false)
const evaluateScopeTypes = ref('') //评价范围类型(风险单元)
const evaluateScopeTypelist = ref([]) //评价范围数据(风险单元)
const selectedRiskUnit = ref([]);
const tableData = ref([]);
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  total: 0,
  teamId: ''
});
const riskTreeRef = ref(null);
const memberRiskUnits = ref({});
// 配置评价范围方法
const handlesetfg = (row) => {
  id.value = row.id
  if (evaluateScopeTypes.value == '01') {
    showDept.value = true
  } else {
    const savedData = memberRiskUnits.value[row.id];
    selectedRiskUnit.value = Array.isArray(savedData) ? savedData : (savedData ? [savedData] : []);
    console.log(selectedRiskUnit.value,'selectedRiskUnit.value');
    
    showdialog.value = true
  }
}
// 获取表格数据
const getTableData = () => {
  getApi(listQuery.value, "/mosty-jcgl/tbDangerIdentifyEvaluateMember/selectPage").then((res) => {
    if (res) {
      tableData.value = res.records;
      listQuery.value.total = res.total;
      // 提取每个成员的风险单元信息
      if (res.records && res.records.length > 0) {
        res.records.forEach(record => {
          if (record.scopeList && record.scopeList.length > 0) {
            // 确保存储为数组
            memberRiskUnits.value[record.id] = record.scopeList.map(scopeData => ({
              node: {
                id: scopeData.orgId,
                name: scopeData.orgName
              },
              lev1: {
                id: scopeData.orgId,
                name: scopeData.orgName
              }
            }));
          }
        });
      }
    }
  })
};
//页码发生变化
const handleCurrentChange = val => {
  listQuery.value.pageCurrent = val
  getTableData()
}
//查询条数发生变化
const handleSizeChange = val => {
  listQuery.value.pageSize = val
  getTableData()
}

//删除
const handledelete = async (row) => {
  let memberId = ''
  const res = await deleteApi({}, `/mosty-jcgl/tbDangerIdentifyEvaluateScope/cancelListByMemberId/${memberId = row.id}`)
  if (res) {
    ElMessage.success("删除成功");
    getTableData()
  }
}
// 返回上级页面
const handleReturn = () => {
  emits("close");
}
//导出Excel
function onloadExcel () {
  exportLoading.value = true
  let title = {
    yhCategory: "风险单元类别",
    lev1: "一级单元",
    lev2: "二级单元",
    checklibName: "单元名称",
    itemName: "排查项描述",
    yhNote: "隐患描述",
    yhLv: "隐患等级",
    isPic: "是否必须上传图片",
    criterion: "判断依据",
  };

  let obj = {
    pageCurrent: 1,
    pageSize: 100000,
    checklibId: listQuery.value.checklibId
  }
  getApi(obj, "/mosty-jcgl/controlLib/getPageList").then((res) => {
    if (res) {
      let data = res.records;
      if (data) {
        // =============== 修改开始：使用项目字典工具 ===============
        const processedData = data.map(item => {
          const newItem = { ...item };
          // 处理parentList数据
          if (item.parentList && Array.isArray(item.parentList)) {
            const level1 = item.parentList.find(p => p.level === 1);
            const level2 = item.parentList.find(p => p.level === 2);

            newItem.lev1 = level1 ? level1.name : '';
            newItem.lev2 = level2 ? level2.name : '';
          } else {
            newItem.lev1 = '';
            newItem.lev2 = '';
          }

          // 处理固有风险等级类别字典转换
          if (item.yhCategory && D_BZ_FXDJS.value) {
            // 在字典数组中查找对应的label
            const dictItem = D_BZ_FXDJS.value.find(dict => dict.value === item.yhCategory);
            newItem.yhCategory = dictItem ? dictItem.label : item.yhCategory;
          } else {
            newItem.yhCategory = item.yhCategory || '';
          }

          // 同样现状风险等级等级字典转换
          if (item.yhLv) {


            if (D_BZ_FXDJS_XY.value) {
              const levelDict = D_BZ_FXDJS_XY.value.find(dict => dict.value === item.yhLv);
              newItem.yhLv = levelDict ? levelDict.label : item.yhLv;
            }
          }
          return newItem;
        });
        // =============== 修改结束 ===============

        let tablename = `风险分级管控措施清单.xlsx`;
        exportXlsx(title, processedData, `风险分级管控措施清单`, tablename);
        exportLoading.value = false
      }
      exportLoading.value = false
    }
  }).finally(() => {
    exportLoading.value = false
  });
}
// 获取部门
const getUserOrDept = async (val) => {
  // 回显部门勾选的数据
  cybmList.value = val.map((item) => {
    return item.id;
  }).toString();
  cybmList.value = cybmList.value ? cybmList.value.split(',') : []
  // 评价范围
  scopeList.value = val.map((item) => ({
    orgId: item.id,
    orgName: item.orgName
  }))
  let params = {
    memberId: id.value,
    scopeList: scopeList.value ? scopeList.value : []
  }
  const res = await postApi(params, "/mosty-jcgl/tbDangerIdentifyEvaluateScope/handle")
  if (res) {
    ElMessage.success('部门设置成功')
    showDept.value = false
    getTableData()
  }
}
//获取风险单元添加保存处理方法
const handleSaveDept = async (nodes, lev1Nodes) => {
  // 保存选中的数据用于回显
  selectedRiskUnit.value = nodes.map(node => ({
    node: node,
    lev1: lev1Nodes?.find(lev1 => lev1.id === node.id) || node // 匹配对应的lev1节点
  }));
  memberRiskUnits.value[id.value] = selectedRiskUnit.value;
  evaluateScopeTypelist.value = nodes.map(node => ({
    orgId: node.id,
    orgName: node.name
  }));

  let params = {
    memberId: id.value,
    scopeList: evaluateScopeTypelist.value
  };

  const res = await postApi(params, "/mosty-jcgl/tbDangerIdentifyEvaluateScope/handle");
  if (res) {
    ElMessage.success('风险单元设置成功');
  }
  listQuery.value.pageCurrent = 1;
  getTableData();
};

const dialogshow = () => {
  showdialog.value = false
}
onMounted(() => {
})
watch(() => props.itemList, (newval) => {
  if (newval) {
    const { id, evaluateScopeType } = newval
    listQuery.value.teamId = id
    evaluateScopeTypes.value = evaluateScopeType
    getTableData()
  }
}, { immediate: true, deep: true })
</script>

<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-wrap: wrap;
}

.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);
    }
  }
}

//表格高度=》加分页,查询，新增
.eltab99 {
  height: calc(100vh - 480px) !important;
}

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

.pxfs {
  color: black;
  font-size: 16px;
  line-height: 16px;
  margin-right: 5px;
}
</style>
