<template>
  <MOSTY.PageTree :pageTitle="'风险分级管控评估报告'" :searchType="'03'" @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="handleAdd" v-loading="exportLoading">
          <el-icon>
            <CirclePlus />
          </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" />
          <el-table-column label="报告单位" property="orgname"></el-table-column>
          <el-table-column label="报告名称" property="orgname"></el-table-column>
          <el-table-column label="报告人员" property="orgname"></el-table-column>
          <el-table-column label="报告时间" property="orgname"></el-table-column>
          <el-table-column label="二级风险单元" property="orgname"></el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="scope">
              <span 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(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>
  <div v-if="fxfjgkinfoshow" class="dialog-box">
    <fxgkpginfo :formData="itemList" :checktype="checktype" @close="closefn" />
  </div>
  <el-dialog custom-class="productionConfig" :title="dialogForm?.id ? '编辑风险分级管控评估报告' : '新增风险分级管控评估报告'" width="60%"
    v-model="dialogshow" :before-close="closeDialog" center>
    <el-form ref="dialogFormRef" label-width="120px" :model="dialogForm" :rules="rules">
      <!-- 报告单位 -->
      <el-form-item label="报告单位:" prop="reportUnit">
        <el-input v-model="dialogForm.reportUnit" placeholder="请输入报告单位" style="width: 100%;" />
      </el-form-item>

      <!-- 报告名称 -->
      <el-form-item label="报告名称:" prop="reportName">
        <el-input v-model="dialogForm.reportName" placeholder="请输入报告名称" style="width: 100%;" />
      </el-form-item>

      <!-- 报告人员 -->
      <el-form-item label="报告人员:" prop="reporter">
        <el-input v-model="dialogForm.reporter" placeholder="请输入报告人员" style="width: 100%;" />
      </el-form-item>

      <!-- 报告时间 -->
      <el-form-item label="报告时间:" prop="reportTime">
        <el-date-picker v-model="dialogForm.reportTime" type="datetime" placeholder="请选择报告时间" style="width: 100%;" />
      </el-form-item>

      <!-- 二级风险单元 -->
      <el-form-item label="二级风险单元:" prop="secondLevelUnit">
        <el-input v-model="dialogForm.secondLevelUnit" placeholder="请输入二级风险单元" style="width: 100%;" />
      </el-form-item>

      <!-- 升降级的原因 -->
      <el-form-item label="升降级的原因:" prop="upgradeReason">
        <el-input v-model="dialogForm.upgradeReason" placeholder="请输入升降级的原因" type="textarea" maxlength="500"
          style="width: 100%;" :rows="4" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button 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>关闭</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
// 引入
import { reactive, onMounted, ref, nextTick, getCurrentInstance } from "vue";
import fxgkpginfo from "./fxgkpginfo.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi } from "@/api/tobAcco_api.js";
import { dateFormat } from "@/utils/tools";
import { getSysDictByCode } from "@/api/sysDict";
import { exportXlsx } from "@/excel/Export2Excel.js";
import { ElMessage } from "element-plus";
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 unitType = ref([]);
const gytype = ref([]);
const xztype = ref([]);
const searchArr = reactive([
  {
    showType: "input",
    prop: "keywords1",
    width: '250px',
    placeholder: '请输入报告名称',
  },
  {
    showType: "year",
    prop: "year",
    width: '250px',
    defaultVal: String(dateFormat({ type: "year", time: new Date() }))
  }
])
const tableData = ref([]);
const dialogshow = ref(false);
const dialogForm = ref({});
const loading = ref(false);
const dialogFormRef = ref(null);

//获取部门数据
const getdeptId = (val) => {
  listQuery.value.ssbmid = val.id;
  listQuery.value.pageCurrent = 1;
  getTableData();
};
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  ssbmid: "",
  orglevel: "",
  year: String(dateFormat({ type: "year", time: new Date() }))
});
const fxfjgkinfoshow = ref(false);
const itemList = ref({});
onMounted(() => {
  Promise.all([
    getSysDictByCode({ dictCode: "D_BZ_FXDYLX" }),
    getSysDictByCode({ dictCode: "D_BZ_FXDJS" }),
    getSysDictByCode({ dictCode: "D_BZ_FXDJS_XY" })
  ]).then(([unitTypeRes, gytypeRes, xztypeRes]) => {
    if (unitTypeRes) {
      unitType.value = unitTypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }
    if (gytypeRes) {
      gytype.value = gytypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }
    if (xztypeRes) {
      xztype.value = xztypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }
  }).catch(error => {
    console.error('获取字典数据失败:', error);
  });
});
// 获取表格数据
const getTableData = () => {
  getApi(listQuery.value, "/mosty-jcgl/jctj/gwCheckList").then((res) => {
    res.records.forEach(item => {
      item.checktype = '1'
    })
    tableData.value = res.records;
    listQuery.value.total = res.total;
  })
};
//页码发生变化
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 checktype = ref('')

// 验证规则
const rules = {
  reportUnit: [{ required: true, message: "请输入报告单位", trigger: "blur" }],
  reportName: [{ required: true, message: "请输入报告名称", trigger: "blur" }],
  reporter: [{ required: true, message: "请输入报告人员", trigger: "blur" }],
  reportTime: [{ required: true, message: "请选择报告时间", trigger: "change" }],
  secondLevelUnit: [{ required: true, message: "请输入二级风险单元", trigger: "blur" }],
  upgradeReason: [{ required: true, message: "请输入升降级的原因", trigger: "blur" }]
};

// 保存方法
const handleSave = async (formEl) => {
  if (!formEl) return;

  await formEl.validate((valid) => {
    if (valid) {
      // 保存逻辑
      if (dialogForm.value.id) {
        // 编辑保存
        putApi(dialogForm.value, "/api/risk-report/update").then(() => {
          ElMessage.success("编辑成功");
          dialogshow.value = false;
          getTableData();
        });
      } else {
        // 新增保存
        postApi(dialogForm.value, "/api/risk-report/add").then(() => {
          ElMessage.success("新增成功");
          dialogshow.value = false;
          getTableData();
        });
      }
    }
  });
};

// 新增按钮点击事件
const handleAdd = () => {
  dialogForm.value = {
    reportUnit: "",
    reportName: "",
    reporter: "",
    reportTime: "",
    secondLevelUnit: "",
    upgradeReason: ""
  };
  dialogFormRef.value?.clearValidate();
  dialogshow.value = true;
};
//删除
const handledelete = (row) => {

}
// 编辑
const handleedit = (row) => {
  dialogForm.value = { ...row };
  dialogshow.value = true;
}
//点击详情
function handleinfo (index, row) {
  fxfjgkinfoshow.value = true;
  itemList.value = { ...row };
}
const closefn = () => {
  fxfjgkinfoshow.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
  });
}
</script>

<style lang="scss" scoped>
.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;
}
</style>
