<template>
    <div>
        <div class="bigBox">
            <!-- 基础隐患排查 -->
            <div class="left" :style="{ width: lfBoxWid }">
                <div class="title">
                    <div style="display: flex; align-items: center">
                        <div style="padding-top: 5px; margin-right: 5px">
                            <el-icon style="color: var(--el-color-primary) !important">
                                <List />
                            </el-icon>
                        </div>
                        <span class="zzjgxx" v-if="iconChange">基础隐患排查</span>
                    </div>
                    <el-icon @click="handleCollapse" v-show="iconChange">
                        <DArrowLeft />
                    </el-icon>
                    <el-icon @click="handleCollapse" v-show="!iconChange">
                        <DArrowRight />
                    </el-icon>
                </div>
                <div class="treeBox">
                    <!-- <PcflTree width="100%" clearable filterable @getdeptData="getdeptData" /> -->
                    <riskUnitTypeTree width="100%" @change="getdeptData" />
                </div>
            </div>
            <div class="right" :style="{ width: rgBoxWid }">
                <div class="headBox" style="justify-content: space-between ">
                    <div class="title">隐患排查标准库</div>
                </div>
                <el-divider />
                <MOSTY.Search ref="searchRef" :searchArr="searchArr" @submit="onSearch" />
                <div class="btnBox">
                    <el-button @click="setFn">
                        <el-icon>
                            <EditPen />
                        </el-icon>{{ setButtonText }}</el-button>
                    <el-button type="primary" @click="onloadExcel" v-loading="exportLoading">
                        <el-icon>
                            <Download />
                        </el-icon>
                        <span>导出</span>
                    </el-button>
                    <el-button type="primary" @click="add">
                        <el-icon>
                            <CirclePlus />
                        </el-icon>
                        <span>添加</span>
                    </el-button>
                </div>
                <section class="eltab3">
                    <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="loading"
                        :isSelect="false" :isSort="false" :tableHeight="'100%'">
                        <template #yhLv="{ row }">
                            <dict-tag :options="D_DBZ_YHDJ" :value="row.yhLv" :tag="false"></dict-tag>
                        </template>
                        <template #yhCategory="{ row }">
                            <dict-tag :options="D_TB_SBYHLB" :value="row.yhCategory" :tag="false"></dict-tag>
                        </template>
                        <template #yhFlag="{ row }">
                            <dict-tag :options="NYHBZ" :value="row.yhFlag" :tag="false"></dict-tag>
                        </template>
                        <template #yhLx="{ row }">
                            <dict-tag :options="D_BZ_SYPCCJ" :value="row.yhLxArr" :tag="true"></dict-tag>
                        </template>
                        <template #isPic="{ row }">
                            <dict-tag :options="NSFBXSCTP" :value="row.isPic" :tag="false"></dict-tag>
                        </template>
                        <template #status="{ row }">
                            <span>{{ row.status === '02' ? "未入库" : "已入库" }}</span>
                        </template>
                        <template #actions="{ row }">
                            <span class="operedit" @click="handleEdit(row)"><el-icon>
                                    <EditPen />
                                </el-icon>修改</span>
                            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red"
                                title="确定要删除?" @confirm="handleDelete(row)">
                                <template #reference>
                                    <span class="operdel" size="small">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                        删除</span>
                                </template>
                            </el-popconfirm>

                        </template>
                    </MOSTY.Table>
                </section>
                <div class="fenye">
                    <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange"
                        @changeSize="handleSizeChange" />
                </div>
            </div>
        </div>
        <el-dialog v-model="dialogVisible" title="设置排查频率" width="600px" :before-close="handleClose">
            <el-form style="display: block;" :model="formQuery" ref="formRef" :rules="rules">
                <el-form-item label="通用检查频率：" label-width="130px" :rules="[{ required: true, message: '请选择通用检查频率' }]"
                    prop="generalCheckFrequency" required>
                    <MOSTY.Select v-model="formQuery.generalCheckFrequency" :options="D_BZ_JCBZPL" clearable
                        placeholder="请选择通用检查频率" style="width: 250px">
                        <el-option v-for="item in D_BZ_JCBZPL" :key="item" :label="item.label" :value="item.value" />
                    </MOSTY.Select>
                </el-form-item>
                <!-- <el-form-item label="生产期：" prop="productionDate" label-width="130px">
          <el-date-picker v-model="formQuery.productionDate" type="daterange" range-separator="To"
            start-placeholder="生产期开始日期" end-placeholder="生产期结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item> -->
                <el-form-item label="生产期检查频率：" prop="productionCheckFrequency" label-width="130px">
                    <MOSTY.Select v-model="formQuery.productionCheckFrequency" :options="D_BZ_JCBZPL" clearable
                        placeholder="请选择生产期检查频率" style="width: 250px">
                        <el-option v-for="item in D_BZ_JCBZPL" :key="item" :label="item.label" :value="item.value" />
                    </MOSTY.Select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submit" :loading="buttonLoading"> <el-icon>
                            <DocumentChecked />
                        </el-icon>
                        <span>确认</span> </el-button>
                    <el-button @click="dialogVisible = false"> <el-icon>
                            <DocumentDelete />
                        </el-icon>
                        <span>关闭</span></el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 编辑排查项 -->
        <InnerDialog v-if="innerShow" :title="title" :innerShow="innerShow" @changeVi="changeVi"
            :dict="{ D_DBZ_YHDJ, NSFBXSCTP, NYHBZ, D_BZ_SYPCCJ }" :formValue="InnerForm" />
    </div>
</template>

<script setup>
// 引入
import { onMounted, ref, reactive, getCurrentInstance, nextTick, computed, watch } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import InnerDialog from "./innerDialog.vue";
import PcflTree from "../component/pcflTree.vue";
import { exportXlsx } from "@/excel/Export2Excel.js";
import riskUnitTypeTree from "@/views/fxgk/aqfxfjgk/component/riskUnitTypeTree.vue";

const { proxy } = getCurrentInstance();
const { D_DBZ_YHDJ, D_BZ_SYPCCJ, NSFBXSCTP, D_JCGL_YHPCBZKZT, NYHBZ, D_TB_SBYHLB, D_BZ_JCBZPL } = proxy.$dict(
    "D_DBZ_YHDJ", "D_BZ_SYPCCJ", "NSFBXSCTP", "D_JCGL_YHPCBZKZT", "NYHBZ", "D_TB_SBYHLB", "D_BZ_JCBZPL");
const loading = ref(false);
const tableData = ref([]);
const InnerForm = ref({})
const dialogVisible = ref(false);
const formRef = ref(null);
const formQuery = ref({
    generalCheckFrequency: "",
    productionCheckFrequency: "",
});

const rules = reactive({
    region: [{ required: true, message: "请选择通用检查频率", trigger: "blur" }]
});

// 分页
const listQuery = ref({
    pageCurrent: 1,
    pageSize: 10,
    checklibName: "",
});
const searchArr = reactive([
    {
        showType: "selectTree",
        prop: "yhCategory",
        options: "D_TB_SBYHLB",
        placeholder: "请选择隐患类别"
    },
    {
        showType: "select",
        prop: "yhLv",
        options: D_DBZ_YHDJ,
        placeholder: "请选择隐患等级"
    },
    {
        showType: "select",
        prop: "status",
        options: D_JCGL_YHPCBZKZT,
        placeholder: "请选择状态"
    },
]);
//查询
function onSearch(obj) {
    listQuery.value.pageCurrent = 1
    listQuery.value.yhCategory = obj.yhCategory;
    listQuery.value.yhLv = obj.yhLv;
    listQuery.value.status = obj.status;
    // listQuery.value.checklibName = obj.checklibName;
    getCheckLibPage();

}
const tableColumns = reactive([
    {
        title: "排查项描述",
        prop: "itemName"
    },
    // {
    //   title: "管控措施内容",
    //   prop: "itemName"
    // },
    {
        title: "隐患描述",
        prop: "yhNote",

    },
    {
        title: "隐患类别",
        prop: "yhCategory",
        slot: true

    },
    {
        title: "隐患等级",
        prop: "yhLv",
        slot: true
    },

    // {
    //   title: "隐患说明",
    //   prop: "yhNote",

    // },
    // {
    //   title: "标红项",
    //   prop: "yhFlag",
    //   slot: true
    // },
    // {
    //   title: "适用排查场景",
    //   prop: "yhLx",
    //   slot: true
    // },
    {
        title: "是否必须上传图片",
        prop: "isPic",
        slot: true
    },
    {
        title: "判断依据",
        prop: "criterion",
    },
    {
        title: "状态",
        prop: "status",
        slot: true
    },
    {
        title: "操作",
        prop: "actions",
        fixed: 'right',
        slot: true
    }
])
const innerShow = ref(false)
const title = ref('')
// 左侧树形数据
const leftData = ref(null)
// 树的展开与折叠
const iconChange = ref(true);
const lfBoxWid = ref("300px");
const rgBoxWid = ref("calc(100% - 300px)");
// 初始化
onMounted(() => {
});
// 编辑排查项回调弹窗
const changeVi = (val) => {
    innerShow.value = val;
    getCheckLibPage();
};
// 添加排查分类
const add = () => {
    InnerForm.value.id = null
    InnerForm.value.checklibId = listQuery.value.checklibId
    InnerForm.value.checklibName = listQuery.value.checklibName
    title.value = "新增隐患排查标准";
    innerShow.value = true;
}
// 删除
const handleDelete = (row) => {
    postApi({}, `/mosty-jcgl/controlLib/del/${row.id}`).then(res => {
        ElMessage.success("删除成功");
        getCheckLibPage()
    })
}
// 修改
const handleEdit = (row) => {
    title.value = "修改隐患排查标准";
    InnerForm.value.id = row.id;
    innerShow.value = true;
};
// 方法
const handleCollapse = () => {
    iconChange.value = !iconChange.value;
    if (iconChange.value) {
        lfBoxWid.value = "300px";
        rgBoxWid.value = "calc(100% - 300px)";
    } else {
        lfBoxWid.value = "40px";
        rgBoxWid.value = "calc(100% - 40px)";
    }
};
//获取部门数据
const getdeptData = (id, val, lev1) => {
    // /** 是否灭火器 */
    // const isFireExtinguisher = val.dm == "200201010000"
    // if (val.itemList && val.itemList.length > 0 && !isFireExtinguisher) {
    //     return
    // }
    // InnerForm.value.checklibId = val.dm
    // InnerForm.value.checklibName = val.zdmc
    // leftData.value = val
    // listQuery.value.checklibId = val.dm;
    // listQuery.value.pageCurrent = 1;
    // getCheckLibPage();
    const leftObj = {
        ...val,
        dm: val.id,
        zdmc: val.name,
        isHadChild: val.children?.length > 0,
        lev1: { id: lev1.id, label: lev1.name }
    }
    listQuery.value.checklibId = leftObj.id;
    listQuery.value.checklibName = leftObj.name;
    listQuery.value.pageCurrent = 1;
    getCheckLibPage()
    getCheckRate()
};
// 获取列表数据
const getCheckLibPage = () => {
    loading.value = true;
    getApi(listQuery.value, "/mosty-jcgl/controlLib/getPageList").then((res) => {
        tableData.value = Array.isArray(res.records) ? res.records : [];
        tableData.value = tableData.value.map(item => {
            item.yhLxArr = item.yhLx ? item.yhLx.split(",") : []
            return item
        })
        listQuery.value.total = res.total;
        loading.value = false;
    }).finally(() => {
        loading.value = false;
    });
};

// 页码改变触发
const handleCurrentChange = (currentPage) => {
    listQuery.value.pageCurrent = currentPage;
    getCheckLibPage();
};
// pageSize 改变触发
const handleSizeChange = (currentSize) => {
    listQuery.value.pageSize = currentSize;
    getCheckLibPage();
};
const exportLoading = ref(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_TB_SBYHLB.value) {
                        // 在字典数组中查找对应的label
                        const dictItem = D_TB_SBYHLB.value.find(dict => dict.value === item.yhCategory);
                        newItem.yhCategory = dictItem ? dictItem.label : item.yhCategory;
                    } else {
                        newItem.yhCategory = item.yhCategory || '';
                    }

                    // 同样处理隐患等级字典转换
                    if (item.yhLv) {
                        // 假设隐患等级字典名称为 D_TB_YHDJ

                        if (D_DBZ_YHDJ.value) {
                            const levelDict = D_DBZ_YHDJ.value.find(dict => dict.value === item.yhLv);
                            newItem.yhLv = levelDict ? levelDict.label : item.yhLv;
                        }
                    }
                    if (item.isPic) {
                        if (NSFBXSCTP.value) {
                            const picDict = NSFBXSCTP.value.find(dict => dict.value === item.isPic);
                            newItem.isPic = picDict ? picDict.label : item.isPic;
                        }
                    } else {
                        newItem.isPic = item.isPic || '';
                    }

                    return newItem;
                });
                // =============== 修改结束 ===============

                let tablename = `隐患排查标准库.xlsx`;
                exportXlsx(title, processedData, `隐患排查标准库`, tablename);
                exportLoading.value = false
            }
            exportLoading.value = false
        }
    }).finally(() => {
        exportLoading.value = false
    });
}
// 排查频率配置
const setFn = () => {
    // 重置表单数据
    formQuery.value = {
        generalCheckFrequency: '',
        productionDate: [new Date().toISOString().split('T')[0], new Date().toISOString().split('T')[0]]
    };
    nextTick(() => {
        if (formRef.value) {
            formRef.value.clearValidate();
        }
    });
    dialogVisible.value = true;
}
// 关闭弹窗
const handleClose = () => {
    dialogVisible.value = false;
}
const buttonLoading = ref(false)
//保存
function submit() {
    formRef.value.validate((valid) => {
        if (valid) {
            buttonLoading.value = true;
            let params = {
                ...formQuery.value,

                id: listQuery.value.checklibId
            }
            postApi(params, '/mosty-jcgl/checklib/setCheckRateNew').then(() => {
                savedConfig.value = {
                    generalCheckFrequency: formQuery.value.generalCheckFrequency,
                    productionCheckFrequency: formQuery.value.productionCheckFrequency
                };

                dialogVisible.value = false;
                ElMessage.success("修改成功");
                getCheckLibPage();
            }).finally(() => {
                buttonLoading.value = false;
                // formQuery.value = {}
            });
        } else {
            ElMessage.error("请填写完必填项!");
            return false;
        }
    });
}
const savedConfig = ref({}); // 已保存的配置，用于按钮显示
const setButtonText = computed(() => {
    const { generalCheckFrequency, productionCheckFrequency } = savedConfig.value;
    if (generalCheckFrequency && productionCheckFrequency) {
        // 两个频率都有配置
        return `通用检查频率：${getDictLabel(generalCheckFrequency, D_BZ_JCBZPL)}-生产期检查频率：${getDictLabel(productionCheckFrequency, D_BZ_JCBZPL)} `;
    } else if (generalCheckFrequency) {
        // 只有通用检查频率
        return `通用检查频率：${getDictLabel(generalCheckFrequency, D_BZ_JCBZPL)}-生产期检查频率：未配置 `;
    } else if (productionCheckFrequency) {
        // 只有生产期检查频率
        return `通用检查频率：未配置-生产期检查频率：${getDictLabel(productionCheckFrequency, D_BZ_JCBZPL)} `;
    } else {
        // 都没有配置
        return "排查频率配置";
    }
});

// 🟢 新增：获取字典标签的辅助函数
const getDictLabel = (value, dict) => {
    if (!value || !dict?.value) return value || '';
    const dictItem = dict.value.find(d => d.value === value);
    return dictItem ? dictItem.label : value;
};
watch(() => dialogVisible.value, (newVal) => {
    getCheckRate();
})
const getCheckRate = () => {
    getApi({ id: listQuery.value.checklibId }, '/mosty-jcgl/checklib/getCheckRate',).then(res => {
        if (res) {
            savedConfig.value = {
                generalCheckFrequency: res?.generalCheckFrequency || '',
                productionCheckFrequency: res?.productionCheckFrequency || ''
            };
            formQuery.value.generalCheckFrequency = res?.generalCheckFrequency || '';
            formQuery.value.productionCheckFrequency = res?.productionCheckFrequency || '';
        }


    })
}
onMounted(() => {
    getCheckRate();
    getCheckRate();
})
</script>

<style lang="scss" scoped>
.bigBox {
    display: flex;

    .title {
        height: 39px;
        line-height: 39px;
        font-size: 18px;
        color: var(--el-color-primary);
        display: flex;
        justify-content: space-between;
        align-items: center;

        .el-icon {
            cursor: pointer;
        }
    }

    .left {
        width: 300px;
        background: #ffffff;
        box-shadow: 0px 2px 10px 0px rgba(107, 107, 107, 0.1);
        border-radius: 0px 0px 0px 0px;
        opacity: 1;

        .treeBox {
            height: calc(100vh - 164px);
            overflow: auto;
        }
    }

    .right {
        padding: 0 10px;
        margin: 0px 0 0 10px;
        background: #fff;

        .headBox {
            display: flex;
            align-items: center;
        }


    }
}

.eltab3 {
    height: calc(100vh - 365px);
}

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