<!-- 表格里的管理弹出框 -->
<template>
  <div>
    <MOSTY.PageTree pageTitle="风险分级管控措施实施情况跟踪记录详情列表" :isShowLeftTree="false">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
        <div class="btnBox">
          <el-button type="primary" @click="handleClose">
            <el-icon>
              <Close />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <div class="eltab99">
          <el-table :data="tableData" border stripe height="100%">
            <el-table-column label="单元名称" prop="orgname" align="center" show-overflow-tooltip />
            <el-table-column label="单元风险等级" property="orgname" show-overflow-tooltip></el-table-column>
            <el-table-column label="责任单位" property="orgname" show-overflow-tooltip></el-table-column>
            <el-table-column label="责任部门" property="orgname" show-overflow-tooltip></el-table-column>

            <el-table-column label="管控措施要求" property="orgname" show-overflow-tooltip></el-table-column>
            <el-table-column label="风险描述" property="orgname" show-overflow-tooltip></el-table-column>
            <el-table-column label="风险点风险等级" property="orgname" show-overflow-tooltip>

            </el-table-column>
            <el-table-column label="管控实时状态" property="orgname" show-overflow-tooltip>
              <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" show-overflow-tooltip></el-table-column>
            <el-table-column label="风险动态监测变化" property="orgname" show-overflow-tooltip></el-table-column>
            <el-table-column label="风险等级变化原因" property="orgname" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column property="ctype" label="类型">
              <template #default="{ row }">
                <dict-tag :options="D_TB_BMJCLX" :value="row.ctype" :tag="false" />
              </template>
</el-table-column>
<el-table-column label="检查类型" prop="checktype">
  <template #default="{ row }">
                <dict-tag :options="D_BZ_YHLX" :value="row.checktype" :tag="false" />
              </template>
</el-table-column> -->
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <span class="operesee" @click="onloadExcel"><el-icon>
                    <Download />
                  </el-icon>导出</span>
                <span class="operesee" @click="handleinfo(scope.row)"><el-icon>
                    <Compass />
                  </el-icon>详情</span>
                <span class="operesee" @click="handleEdit"><el-icon>
                    <Compass />
                  </el-icon>风险变更</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange">
            </MOSTY.Pages>
          </div>
        </div>
      </template>
    </MOSTY.PageTree>
  </div>
  <div v-if="fxfjgkinfoshow" class="dialog-box">
    <fxgkcsinfolist :formData="itemList" :checktype="checktype" @close="closefn" />
  </div>
  <!-- 风险变更 -->
  <el-dialog custom-class="productionConfig" title="修改风险变更" width="40%" 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" multiple style="width: 100%">
          <el-option v-for="item in D_BZ_KNFXHGLX" :key="item.value" :label="item.label"
            :value="item.value"></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"></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%" @change="handleXhyyChange">
          <el-option v-for="item in D_BZ_XHYY" :key="item" :label="item.label" :value="item.value"></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="closedialogshow" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>
<script setup>
// 引入
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  getCurrentInstance,
  watch,
  reactive
} from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus"
import { getApi, } from "@/api/tobAcco_api.js";
import { exportXlsx } from "@/excel/Export2Excel.js";
import { getSysDictByCode } from "@/api/sysDict";
import { dateFormat } from "@/utils/tools";
import fxgkcsinfolist from "./fxgkcsinfolist.vue";
const { proxy } = getCurrentInstance();
const { D_BZ_FXDJS, D_BZ_KNFXHGLX, D_BZ_XHYY } = proxy.$dict("D_BZ_FXDJS", "D_BZ_KNFXHGLX", "D_BZ_XHYY");
// 数据
const props = defineProps({
  itemlist: {
    type: Object,
    required: true,
    default: () => { }
  },
  deptId: {
    type: String,
    default: "",
  }
});
const emits = defineEmits(["close"]);
const dialogshow = ref(false);
const dialogForm = ref({
  checkType: "1",
})
const dialogFormRef = ref(null);
const loading = ref(false);
const rules = ref({
  time: [{ required: true, message: "请选择生产日期", trigger: "blur" }],
});

const tableData = ref([
]);
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
});
const unitType = ref([])
const gytype = ref([])
const deptId = ref('')
const fxfjgkinfoshow = ref(false)
const itemList = ref({})
const exportLoading = ref(false);
const searchArr = reactive([
  {
    showType: "select",
    prop: "Type12",
    width: '250px',
    options: gytype,
    placeholder: '请选择风险等级',
  },
  {
    showType: "select",
    prop: "Type1",
    width: '250px',
    options: unitType,
    placeholder: '请选择一级单元类型',
  },
  {
    showType: "select",
    prop: "Type1",
    width: '250px',
    options: unitType,
    placeholder: '请选择二级单元类型',
  },
  {
    showType: "deptCascader",
    prop: "deptId",
    width: '250px',
    placeholder: '请选择部门',
    deptType: "02",
    searchType: "03",
    deptId: deptId,
    immediateSearch: true, // 选择后立即查询
  },
  {
    showType: "deptCascader",
    prop: "deptId2",
    width: '250px',
    placeholder: '请选择单位',
    deptType: "02",
    searchType: "04",
    deptId: deptId,
    immediateSearch: true, // 选择后立即查询
  },
  {
    showType: "input",
    prop: "keywords1",
    width: '250px',
    placeholder: '请输入风险描述',
  },
  {
    showType: "input",
    prop: "keywords1",
    width: '250px',
    placeholder: '请输入风险单位名称',
  },
  {
    showType: "input",
    prop: "keywords1",
    width: '250px',
    placeholder: '请选择风险动态监测变化类型',
  },
  {
    showType: "daterange",
    prop: "keywords1",
    width: '250px',
    placeholder: '选择时间',
  },

  {
    showType: "year",
    prop: "year",
    width: '250px',
    defaultVal: String(dateFormat({ type: "year", time: new Date() }))
  }
])
const onSearch = (val) => {
  listQuery.value.type = val?.Type1
  listQuery.value.year = val?.year
  listQuery.value.deptId = val?.deptId
  listQuery.value.deptId2 = val?.deptId2
  listQuery.pageCurrent = 1;
  getPcxData();
}
onMounted(() => {
  Promise.all([
    getSysDictByCode({ dictCode: "D_BZ_FXDJS" }),

  ]).then(([unitTypeRes]) => {
    if (unitTypeRes) {
      gytype.value = unitTypeRes.itemList.map(item => ({
        label: item.zdmc,
        value: item.dm
      }));
    }
  }).catch(error => {
    console.error('获取字典数据失败:', error);
  });
  getPcxData()
});
// 关闭
const handleClose = () => {
  emits("close");
};

// 获取排查项列表
const getPcxData = () => {
  getApi(listQuery.value, "/mosty-jcgl/jctj/gwCheckList").then((res) => {
    tableData.value = res.records;
    listQuery.value.total = res.total
  });
};
//页码发生变化
const handleCurrentChange = val => {
  listQuery.value.pageCurrent = val
  getPcxData()
}
//查询条数发生变化
const handleSizeChange = val => {
  listQuery.value.pageSize = val
  getPcxData()
}
const handleEdit = () => {
  dialogshow.value = true
}
const closeDialog = () => {
  dialogshow.value = false;

};
const closefn = () => {
  fxfjgkinfoshow.value = false;
}
// 保存方法
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 closedialogshow = () => {
  dialogshow.value = false;

}
const handleXhyyChange = (item) => {
  console.log(item, 'item');
  if (item === '04') {
    dialogForm.value.reportTime3show = true;
  } else {
    dialogForm.value.reportTime3show = false;
  }
}
// 详情
const handleinfo = (row) => {
  fxfjgkinfoshow.value = true;
  itemList.value = { ...row };
}
//导出Excel
function onloadExcel () {
  exportLoading.value = true

  // 定义导出数据的表头
  let title = {
    orgname: "单元名称",
    riskLevel: "单元风险等级",
    responsibleUnit: "责任单位",
    responsibleDept: "责任部门",
    controlMeasures: "管控措施要求",
    riskDescription: "风险描述",
    riskPointLevel: "风险点风险等级",
    planCount: "计划数",
    implementCount: "实施数",
    unimplementCount: "未实施数",
    riskMonitorStatus: "风险动态监测情况",
    riskMonitorChange: "风险动态监测变化",
    riskLevelChangeReason: "风险等级变化原因"
  };

  // 构建查询参数，获取所有数据
  let obj = {
    pageCurrent: 1,
    pageSize: 100000,
    checklibId: listQuery.value.checklibId
  }

  // 根据你的实际API调整接口地址
  getApi(obj, "/mosty-jcgl/controlLib/getPageList").then((res) => {
    if (res && res.records) {
      let data = res.records;

      // 处理数据，确保字段对应
      const processedData = data.map(item => {
        const newItem = { ...item };

        // 处理风险等级字典转换
        if (item.riskLevel && D_BZ_FXDJS.value) {
          const dictItem = D_BZ_FXDJS.value.find(dict => dict.value === item.riskLevel);
          newItem.riskLevel = dictItem ? dictItem.label : item.riskLevel;
        }

        // 处理风险点风险等级字典转换
        if (item.riskPointLevel && D_BZ_FXDJS.value) {
          const dictItem = D_BZ_FXDJS.value.find(dict => dict.value === item.riskPointLevel);
          newItem.riskPointLevel = dictItem ? dictItem.label : item.riskPointLevel;
        }
        return newItem;
      });

      // 生成文件名，包含当前日期
      const currentDate = dateFormat({ type: "date", time: new Date() });
      let tablename = `风险分级管控措施实施情况跟踪记录_${currentDate}.xlsx`;
      exportXlsx(title, processedData, `风险分级管控措施实施情况跟踪记录`, tablename);
    }
  }).catch(error => {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  }).finally(() => {
    exportLoading.value = false;
  });
}
watch(
  () => props.itemlist?.userid,
  (val) => {
    if (val) {
      getPcxData()
    }
  },
)
watch(() => props.deptId, (val) => {
  if (val) {

    deptId.value = val
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.newAdd {
  margin-top: 6px;
  position: absolute;
  right: 20px;
}


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

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