<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 :disabled="true" style="margin-bottom: 5px;" type="primary">
          <span> 评价范围分工方式:{{ getDutyTypeLabel(fromsetObj.form.checkType) }}</span>
        </el-button>
        <el-button style="margin-bottom: 5px;" type="primary" @click="handelSet" v-loading="exportLoading">
          <el-icon>
            <EditPen />
          </el-icon>
          <span>设置</span>
        </el-button>
        <el-button style="margin-bottom: 5px;" type="primary" @click="handleAdd" v-loading="exportLoading">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>添加小组</span>
        </el-button>
        <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="Close">
          <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="teamLeaderUserName"></el-table-column>
          <el-table-column label="评价小组成员" property="teamMemberUserNames"></el-table-column>
          <el-table-column label="操作" fixed="right" max-width="320">
            <template #default="scope">
              <span v-if="['10', '20', '21'].includes(liststatus)" class="operesee"
                @click="handlesetfg(scope.row)"><el-icon>
                  <Compass />
                </el-icon>配置分工</span>
              <span class="operesee" @click="onloadExcel(scope.row)"><el-icon>
                  <Download />
                </el-icon>导出</span>
              <span v-if="['10', '20', '21'].includes(liststatus)" class="operesee"
                @click="handleedit(scope.row)"><el-icon>
                  <EditPen />
                </el-icon>编辑</span>
              <span class="operesee" @click="handleinfo(scope.row)"><el-icon>
                  <Compass />
                </el-icon>详情</span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="handledelete(scope.row)">
                <template #reference>
                  <span v-if="['10', '20', '21'].includes(liststatus)" 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>
  <!-- 添加小组 -->
  <el-dialog :title="isDetailMode ? '评价小组详情' : (fromObj.teamLeaderUserId ? '修改评价小组' : '增加评价小组')" width="50%"
    align-center v-model="dialogshow" :before-close="closeDialog" center>
    <el-form :disabled="isDetailMode" style="flex-wrap: wrap;" :model="fromObj" ref='dialogFormRef' :rules="rules"
      label-width="120px" status-icon>
      <el-form-item label="检查组长:" prop="teamLeaderUserName" style="width: 100%;">
        <el-input :disabled="isDetailMode" v-model="fromObj.teamLeaderUserName" readonly style="width: 100%;">
          <template #append>
            <el-button :disabled="isDetailMode" class='cursor' @click="ChooesDdld('02')">选择</el-button></template>
        </el-input>
      </el-form-item>
      <el-form-item label="检查成员:" prop="teamMemberUserNames" style="width: 100%;">
        <el-input :disabled="isDetailMode" v-model="fromObj.teamMemberUserNames" readonly style="width: 100%;">
          <template #append>
            <el-button :disabled="isDetailMode" class='cursor' @click="ChooesDdld('03')">选择</el-button></template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!isDetailMode" type="primary" :loading="loading" @click="handleSave(dialogFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button @click="closeDialog" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>{{ isDetailMode ? '关闭' : '取消' }}</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 评价分工方式 -->
  <el-dialog custom-class="dialog-box1" :title="fromsetObj.form.id ? '修改评价分工方式' : '设置评价分工方式'" width="40%" align-center
    v-model="setdutyshow" :before-close="closeDialog" center>
    <el-form style="flex-wrap: wrap;" :model="fromsetObj" ref='dialogsetFormRef' :rules="rules" label-width="120px"
      status-icon>
      <el-form-item label="分工方式:" prop="fgfx" style="width: 100%;">
        <el-radio-group v-model="fromsetObj.form.checkType" style="width: 100%;">
          <el-radio :label="item.value" v-for="item in feedBackTypeRange" :key="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handlesetSave(dialogsetFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button @click="closesetDialog" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 选择人员 -->
  <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
    @choosedUsers="getSonValue">
  </ChooseUser>
  <!-- 详情界面 -->
  <div v-if="qwjcxqShow" class="dialog-box">
    <listEvaluationteamsinfo :itemList="itemlist" @close="closefn" />
  </div>
</template>
<script setup>
// 引入
import { onMounted, ref, watch, getCurrentInstance, defineEmits, defineProps, computed } from "vue";
import listEvaluationteamsinfo from "./listEvaluationteamsinfo.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import { getSysDictByCode } from "@/api/sysDict";
import { ElMessage, ElMessageBox } from "element-plus";
import { exportXlsx } from "@/excel/Export2Excel.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
const props = defineProps({
  planid: {
    type: String,
    default: ""
  },
  idlist: {
    type: Object,
    default: () => { }
  },
  parentstatus: {
    type: String,
    default: null
  }
})
const emit = defineEmits(["close"]);
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 zzlx = ref(null);
const qwjcxqShow = ref(false);
const chooseUserVisible = ref(false);
const singleShow = ref(false);
const leaderid = ref(null);
const memberList = ref([]);
const fromObj = ref({
  planId: '',//辨识id
  teamLeaderOrgId: "",// 组长所属部门ID
  teamLeaderOrgName: "",//组长所属部门名称
  teamLeaderUserId: "",//组长用户ID
  teamLeaderUserName: "",//组长用户名称
  memberList: [],//成员list
  teamMemberUserNames: "",//成员用户名称
  evaluateScopeType: "",//评价范围类型
})
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  planId: '',
});

const fromsetObj = ref({
  form: {
    checkType: ''
  }
})
const setdutyshow = ref(false);
const dialogsetFormRef = ref(null);
const tableData = ref([]);
const dialogshow = ref(false);
const loading = ref(false);
const dialogFormRef = ref(null);
const isDetailMode = ref(false); // 详情模式标识
const itemlist = ref({});
const feedBackTypeRange = ref([]);
// 验证规则
const rules = {
  teamLeaderUserName: [{ required: true, message: "请选择检查组长", trigger: "blur" }],
  teamMemberUserNames: [{ required: true, message: "请选择检查成员", trigger: "blur" }],
};
//添加小组选择按钮
const ChooesDdld = (val) => {
  zzlx.value = val;
  if (val == "02") {
    leaderid.value = "";
    leaderid.value = fromObj.value.teamLeaderUserId;
    singleShow.value = true;
    chooseUserVisible.value = true;

  } else {
    // 成员list用作表格回显
    if (fromObj.value.memberList) {
      memberList.value = fromObj.value.memberList.map((item) => {
        return item.userId;
      });
    } else {
      memberList.value = [];
    }
    chooseUserVisible.value = true;
    singleShow.value = false;

  }
}
// 选择人员回调方法
const getSonValue = (value) => {
  if (zzlx.value == "02") {
    fromObj.value.teamLeaderUserName = value[0].userName;
    fromObj.value.teamLeaderUserId = value[0].id;
    fromObj.value.teamLeaderOrgId = value[0].deptId;
    fromObj.value.teamLeaderOrgName = value[0].deptName;
  } else if (zzlx.value == "03") {
    let arr = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      element.zzlx = zzlx.value;
      arr.push(element.userName);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    fromObj.value.memberList = value.map((item) => {
      return {
        teamMemberUserId: item.id,
        teamMemberUserName: item.userName,
        teamMemberOrgId: item.deptId,
        teamMemberOrgName: item.deptName,

      };
    });
    fromObj.value.teamMemberUserNames = arr.join(",");
  }
};
// const searchArr = reactive([
//   {
//     showType: "select",
//     prop: "keywords1",
//     width: '250px',
//     placeholder: '请选择部门单位',
//   },
// ])
// 获取分工方式标签
const getDutyTypeLabel = (value) => {
  const item = feedBackTypeRange.value.find(item => item.value === value);
  return item ? item.label : '未知分工方式';
};
onMounted(() => {
  Promise.all([
    getSysDictByCode({ dictCode: "D_BZ_PJFWFGFS" }),

  ]).then(([unitTypeRes]) => {
    if (unitTypeRes) {
      feedBackTypeRange.value = unitTypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }

  }).catch(error => {
  });
  getTableData();
});
const liststatus = ref(null)
watch(() => props.parentstatus, (newVal) => {
  if (newVal) {
    liststatus.value = newVal
  }
}, { immediate: true })

// 获取表格数据
const getTableData = () => {
  getApi(listQuery.value, "/mosty-jcgl/tbDangerIdentifyEvaluateTeam/selectPage").then((res) => {
    tableData.value = res.records;
    listQuery.value.total = res.total;
    // 设置分工方式：如果列表存在且有evaluateScopeType字段，则使用该字段值，否则使用默认值01
    if (res.records && res.records.length > 0 && res.records[0].evaluateScopeType) {
      fromsetObj.value.form.checkType = res.records[0].evaluateScopeType;
    } else {
      fromsetObj.value.form.checkType = '01'; // 默认值
    }
  }).catch((err) => {
    console.log(err);
    // 如果请求失败也设置默认值
    fromsetObj.value.form.checkType = '01';
  })
};
//页码发生变化
const handleCurrentChange = val => {
  listQuery.value.pageCurrent = val
  getTableData()
}
//查询条数发生变化
const handleSizeChange = val => {
  listQuery.value.pageSize = val
  getTableData()
}
//查询 
// const onSearch = obj => {
//   listQuery.value.year = obj.year
//   listQuery.pageCurrent = 1;
//   getTableData();
// }
// 保存方法
const handleSave = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      // 保存逻辑
      if (fromObj.value.id) {
        // 编辑保存
        postApi(fromObj.value, "/mosty-jcgl/tbDangerIdentifyEvaluateTeam/update").then(() => {
          ElMessage.success("修改成功");
          dialogshow.value = false;
          getTableData();
        });
      } else {
        // 新增保存
        postApi(fromObj.value, "/mosty-jcgl/tbDangerIdentifyEvaluateTeam/save").then(() => {
          ElMessage.success("新增成功");
          dialogshow.value = false;
          getTableData();
        });
      }
    }
  });
};

// 新增按钮点击事件
const handleAdd = () => {
  fromObj.value = {
    teamLeaderOrgId: "",// 组长所属部门ID
    teamLeaderOrgName: "",//组长所属部门名称
    teamLeaderUserId: "",//组长用户ID
    teamLeaderUserName: "",//组长用户名称
    memberList: [],//成员list
    teamMemberUserNames: "",//成员用户名称
    planId: fromObj.value.planId, //计划id
    evaluateScopeType: fromsetObj.value.form.checkType,//分工方式
  };
  isDetailMode.value = false;
  dialogFormRef.value?.clearValidate();
  dialogshow.value = true;
};
//删除
const handledelete = async (row) => {
  let id = ''
  const res = await deleteApi({}, `/mosty-jcgl/tbDangerIdentifyEvaluateTeam/${id = row.id}`)
  if (res) {
    ElMessage.success("删除成功");
    getTableData();
  }
}
// 配置分工
const handlesetfg = (row) => {
  itemlist.value = {
    ...row,
    evaluateScopeType: fromsetObj.value.form.checkType
  };
  qwjcxqShow.value = true;
}
// 编辑
const handleedit = (row) => {
  fromObj.value = { ...row };
  isDetailMode.value = false;
  dialogshow.value = true;
}
//点击详情
function handleinfo(row) {
  fromObj.value = { ...row };
  isDetailMode.value = true;
  dialogshow.value = true;
}
const closefn = () => {
  qwjcxqShow.value = false;
}
// 关闭弹窗
const closeDialog = () => {
  dialogshow.value = false;
  dialogFormRef.value?.clearValidate();
};
//导出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 handelSet = () => {
  setdutyshow.value = true
}
// 保存分工方式
const handlesetSave = async (formEl) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 确认提示框
        await ElMessageBox.confirm(
          `切换后,之前所有的配置范围信息将被删除,是否确认保存？`,
          '提示',
          {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning',
            center: false,
          }
        );
        let params = {
          evaluateScopeType: fromsetObj.value.form.checkType,
        }
        // 编辑保存
        await postApi(params, "/mosty-jcgl/tbDangerIdentifyEvaluateTeam/switchEvaluateScopeType");
        setdutyshow.value = false;
        ElMessage.success("设置保存成功");
        getTableData();

      } catch (error) {
        // 用户点击取消或关闭弹窗

      }
    }
  });
};
//关闭弹窗
const closesetDialog = () => {
  setdutyshow.value = false;
  dialogsetFormRef.value?.clearValidate();
}
//返回
const Close = () => {
  emit("close");
}
watch(() => props.planid, (newval) => {
  if (newval) {
    fromObj.value.planId = newval
    listQuery.value.planId = newval
  }

}, { immediate: 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>
