<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>
      </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="部门名称" prop="orgname" align="center" />
          <el-table-column label="重大风险数(红色)" property="orgname"></el-table-column>
          <el-table-column label="管控实时状态" property="orgname">
            <el-table-column label="计划数" property="orgname" />
            <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 label="计划数" property="orgname" />
            <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 label="计划数" property="orgname" />
            <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 label="计划数" property="orgname" />
            <el-table-column label="实施数" property="orgname" />
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <span class="operesee" @click="handleChange(index, scope.row)"><el-icon>
                  <Compass />
                </el-icon>详情</span>
            </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="qwjcxqShow" class="dialog-box">
    <fxgkcsinfo :itemlist="itemlist" :checktype="checktype" :deptId="listQuery.ssbmid" @close="closefn" />
  </div>
  <el-dialog custom-class="productionConfig" title="风险变更" width="60%" v-model="dialogshow" :before-close="closeDialog"
    center>
    <el-form ref="dialogFormRef" label-width="140px" :model="dialogForm" :rules="rules">
      <!-- 变更类型 -->
      <el-form-item label="变更类型:">
        <el-radio-group v-model="dialogForm.checkType" style="width: 100%;">
          <el-radio label="1">升/降级</el-radio>
          <el-radio label="2">销号原因</el-radio>
        </el-radio-group>
      </el-form-item>


      <!-- 需要选择可能性 -->
      <el-form-item v-if="dialogForm.checkType === '1'" label="需要选择可能性:" prop="reportName">
        <el-select v-model="dialogForm.pjlPoint" style="width: 100%">
          <el-option v-for="item in D_BZ_LSR_L" :key="item.value" :label="item.label" :value="item.value"
            @click.native="labelClick(item.value, 0)"></el-option>
        </el-select>
      </el-form-item>


      <!-- S-R模式 -->
      <el-form-item v-if="dialogForm.checkType === '1'" label="严重程度(S):" prop="pjePoint" style="width: 100%">
        <el-select v-model="dialogForm.psePoint" style="width: 100%" disabled>
          <el-option v-for="item in D_BZ_LSR_S" :key="item" :label="item.label" :value="item.value"
            @click.native="labelClick(item.value, 1)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="dialogForm.checkType === '1'" label="风险等级(R):" prop="pjdPoint" style="width: 100%">
        <el-input v-model="dialogForm.pjrPoint" style="width: 100%" />
      </el-form-item>

      <!-- 填写升降级的原因 -->
      <el-form-item v-if="dialogForm.checkType === '1'" label="填写升降级的原因:" prop="reportTime">
        <el-input v-model="dialogForm.reportTime" type="textarea" show-word-limit maxlength="300" placeholder="请选择报告时间"
          style="width: 100%;" />
      </el-form-item>

      <!-- 选择销号原因 -->
      <el-form-item v-if="dialogForm.checkType === '2'" label="选择销号原因:" prop="secondLevelUnit">
        <el-select v-model="dialogForm.reportTime2" style="width: 100%">
          <el-option v-for="item in D_BZ_XHYY" :key="item" :label="item.label" :value="item.value"
            @click.native="labelClick(item.value, 1)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="dialogForm.reportTime3show" label="请填写具体原因:" prop="reportTime">
        <el-input v-model="dialogForm.reportTime3" type="textarea" show-word-limit maxlength="300" placeholder="请填写具体原因"
          style="width: 100%;" />
      </el-form-item>
      <!-- 上传证明材料 -->
      <el-form-item v-if="dialogForm.checkType === '2'" label="上传证明材料:" prop="upgradeReason">
        <MOSTY.Upload :limit="1" :widthNumber="732" :showinput="true"
          :placeholder="'请上传证明材料（pdf,ofd,doc,docx,xls,xlsx,wps）'"
          :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" :nopicer="true" :isImg="false"
          :ShowfileList="true" v-model="dialogForm.approvalFiles" :delrow="delrow">
        </MOSTY.Upload>
      </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="dialogshow = false" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import fxgkcsinfo from "./fxgkcsinfo.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi } from "@/api/tobAcco_api.js";
import { dateFormat } from "@/utils/tools";
import { exportXlsx } from "@/excel/Export2Excel.js";
const { proxy } = getCurrentInstance();
const { D_BZ_LSR_S, D_BZ_LSR_L, D_BZ_XHYY, } = proxy.$dict("D_BZ_LSR_S", "D_BZ_LSR_L", "D_BZ_XHYY");
const searchArr = reactive([
  // {
  //   showType: "select",
  //   prop: "type",
  //   width: '250px',
  //   options: fxType,
  //   placeholder: '请选择风险单元类型',
  //   defaultVal: ''
  // },
  {
    showType: "year",
    prop: "year",
    width: '250px',
    defaultVal: String(dateFormat({ type: "year", time: new Date() }))
  }
])
const tableData = ref([]);
//获取部门数据
const getdeptId = (val) => {
  listQuery.value.ssbmid = val.id;
  listQuery.value.pageCurrent = 1;
  getTableData();
};
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  year: String(dateFormat({ type: "year", time: new Date() }))
});
const qwjcxqShow = ref(false);
const itemlist = ref({});
const dialogFormRef = ref(null);
const dialogshow = ref(false);
const loading = ref(false);
const dialogForm = ref({
  checkType: "1",
  pjlPoint: "",
  psePoint: "",
  pjrPoint: "",
  reportTime: "",
  reportTime2: "",
  reportTime3: "",
  reportTime3show: false,
  approvalFiles: [],
});
const exportLoading = ref(false);
const rules = ref({
  reportUnit: [{ required: true, message: "请输入报告单位", trigger: "blur" }], //报告单位
  reportName: [{ required: true, message: "请输入报告名称", trigger: "blur" }], //报告名称
  reporter: [{ required: true, message: "请输入报告人员", trigger: "blur" }], //报告人员
});
onMounted(() => {
  // Promise.all([
  //   getSysDictByCode({ dictCode: "D_BZ_FXLX" }),

  // ]).then(([unitTypeRes]) => {
  //   if (unitTypeRes) {
  //     fxType.value = unitTypeRes.itemList.map(item => ({
  //       label: item.zdmc,
  //       value: item.dm
  //     }));
  //     // 设置默认选中第一个
  //     listQuery.value.type = fxType.value[0].value;
  //     searchArr[0].defaultVal = fxType.value[0].value; // 设置搜索框的默认值
  //   }

  // }).catch(error => {
  //   console.error('获取字典数据失败:', error);
  // });
});
// 获取表格数据
const getTableData = () => {
  getApi(listQuery.value, "/mosty-jcgl/jctj/gwCheckList").then((res) => {
    // const processedData = res.records.map(item => {
    //   // 根据风险类型映射字段
    //   if (listQuery.value.type === '1') {
    //     return {
    //       ...item,
    //     }
    //   } else if (listQuery.value.type === '2') {
    //     return {
    //       ...item,
    //     }
    //   } else {
    //     return item
    //   }
    // });
    tableData.value = res.records;
    console.log(tableData.value, 'tableData.value');

    listQuery.value.total = res.total;
  })
};
//页码发生变化
const handleCurrentChange = val => {
  listQuery.value.pageCurrent = val
  getTableData()
}
//查询条数发生变化
const handleSizeChange = val => {
  listQuery.value.pageSize = val
  getTableData()
}
//查询 
const onSearch = obj => {
  console.log(obj, 'obj');
  listQuery.value.type = obj.type
  listQuery.value.year = obj.year
  listQuery.pageCurrent = 1;
  getTableData();
}
const checktype = ref('')

//点击详情checktype
function handleChange (index, row) {
  qwjcxqShow.value = true;
  itemlist.value = { ...row };
}
function closefn () {
  qwjcxqShow.value = false
}



//导出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;
        });
        // =============== 修改结束 ===============
        // 生成文件名，包含当前日期
        const currentDate = dateFormat({ type: "date", time: new Date() });
        let tablename = `风险分级管控措施清单_${currentDate}.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>
