import { h, ref, onMounted, reactive, watch, toRaw, nextTick } from "vue";
import { request } from "@/utils/request";
import { Search } from "@element-plus/icons-vue";
import DetailDialog from "./detailDialog.vue";
import EditDialog from "./editDialog.vue";
import AddDialog from "./addDialog.vue";
import { useRoute } from 'vue-router'

const treeData = ref([]);
const treeProps = {
    children: "children",
    label: "name",
    key: "id",
}
const filterText = ref(''); // 树节点过滤条件
const tableData = ref([]);
const qxmc = ref(''); // 区县名称
const yhzid = ref(''); // 养护站id
const yhzmc = ref(''); // 养护站名称
const filterData = reactive({
    xm: '',
}); // 表格过滤条件
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizes: [10, 20, 50],
    layout: "prev, pager, next, jumper",
    onChange: (page, pageSize) => {
        pagination.current = page;
        pagination.pageSize = pageSize;
        getyhzryList(qxmc.value, yhzid.value, filterData);
    },
}); // 表格分页
const modelVisible = ref(false); // 弹窗显示状态
const model = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    width: '60%',
}); // 弹窗内容
const dialogType = ref(''); // 弹窗类型
const dialogRef = ref(null); // 弹窗实例

const INIT_FORM = {
    xm: "",
    sjhm: "",
    gw: "",
    cjsj: "",
    yhzid: "",
    ryjs: null, // 人员角色 1-负责人 2-普通工作人员
    userId: "",
}; // 表单初始值
const form = reactive({ ...INIT_FORM }); // 表单



// 节点过滤函数
const filterNode = (value, node) => {
    const keyword = (value || '').toLowerCase();

    const nodeData = node || {}

    // 处理区域节点匹配
    if (nodeData.type === 'area') {
        return (nodeData.rawName || '').toLowerCase().includes(keyword)
    }

    // 处理站点节点匹配
    if (nodeData.type === 'site') {
        const parentData = node.parent?.data?.type === 'area' ? node.parent.data : {}
        const parentMatch = (parentData.rawName || '').toLowerCase().includes(keyword)
        return parentMatch || (nodeData.name || '').toLowerCase().includes(keyword)
    }

    return false
}
// 获取养护站列表分组
const getTreeData = async () => {
    try {
        const res = await request({
            url: '/snow-ops-platform/yhz/listAreaGroup?dataType=PERSONNEL',
            method: 'GET'
        })
        if (res.code === '00000') {
            treeData.value = res.data.map((qx, index) => (
                {
                    id: index,
                    name: `${qx.qxmc}`,
                    type: 'area',
                    children: qx.yhzList.map(site => ({
                        id: site.id,
                        name: `${site.mc}(${site.rysl})`,
                        type: 'site',
                        rawName: site.mc,
                    })),
                    rawName: qx.qxmc, // 原始名称
                })
            );
            console.log('treeData', toRaw(treeData.value))
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log(error);
    }
};
// 处理节点点击事件
const handleNodeClick = (data, node) => {
    if (!data || !data.type) return;
    if (data.type === 'area' && node.expanded === false) {
        console.log('树节点关闭', node.expanded)
        yhzid.value = ''; // 重置养护站id
        yhzmc.value = ''; // 重置养护站名称
        qxmc.value = ''; // 重置区县名称
        return;
    }
    if (data.type === 'area') {
        console.log('你点击的是区县', data.id)
        yhzid.value = ''; // 重置养护站id
        yhzmc.value = ''; // 重置养护站名称
        qxmc.value = data.id; // 保存区县名称

    }
    if (data.type === 'site') {
        console.log('你点击的是站点', data.name)
        yhzid.value = data.id; // 保存养护站id
        yhzmc.value = data.rawName; // 保存养护站名称
        qxmc.value = ''; // 重置区县名称
    }
};

// 获取养护站人员列表
const getyhzryList = async (qxmc, yhzid, filterData) => {
    try {
        const data = {
            qxmc: qxmc,
            yhzid: yhzid,
            xm: filterData?.xm || '',
            pageNum: pagination.current,
            pageSize: pagination.pageSize,
        }
        const res = await request({
            url: '/snow-ops-platform/yhzry/list',
            method: 'GET',
            params: data,
        })
        if (res.code === '00000') {
            tableData.value = res.data.records;
            pagination.total = res.data.total;
        } else {
            tableData.value = [];
            pagination.total = 0;
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log(error);
    }
};

const columns = [
    {
        prop: 'xm',
        label: '姓名',
    },
    {
        prop: 'gw',
        label: '岗位',
    },
    {
        prop: 'sjhm',
        label: '手机号码',
    },
    {
        prop: 'cjsj',
        label: '创建时间',
        render: (row) => () => {
            // 解析 ISO 时间字符串
            const date = new Date(row.cjsj);

            // 格式化为 YYYY-MM-DD HH:mm:ss
            const format = (n) => n.toString().padStart(2, '0');
            return h("div",
                `${date.getFullYear()}-${format(date.getMonth() + 1)}-${format(date.getDate())} 
                 ${format(date.getHours())}:${format(date.getMinutes())}:${format(date.getSeconds())}`
            );
        }
    },
    {
        prop: 'ryjs',
        label: '人员角色',
        width: 100,
        render: (row) => () => {
            const roleConfig = {
                1: { label: '负责人', color: '#f56c6c' },
                2: { label: '普通工作人员', color: '#409eff' }
            };

            const config = roleConfig[row.ryjs] || { label: '未知角色', color: '#909399' };

            return h(
                ElTag,
                {
                    style: { 'margin-right': '5px' },
                    effect: "dark",
                    type: row.ryjs === 1 ? 'danger' : 'primary'
                },
                () => config.label
            );
        }
    },

    {
        label: "操作",
        fixed: "right",
        width: 150,
        render: (row) => () =>
            h("div", { class: "action-btns" }, [
                h(
                    ElButton,
                    {
                        type: "primary",
                        link: true,
                        onClick: async () => {
                            dialogType.value = 'detail'
                            await getDetailData(row);
                        },
                    },
                    () => "详情"
                ),
                h(
                    ElButton,
                    {
                        type: "primary",
                        link: true,
                        onClick: async () => {
                            dialogType.value = 'edit'
                            await getDetailData(row);
                        },
                    },
                    () => "编辑"
                ),
                h(
                    ElButton,
                    {
                        type: "danger",
                        link: true,
                        onClick: async () => {
                            try {
                                await ElMessageBox.confirm("确定要删除该人员吗？", "删除确认", {
                                    confirmButtonText: "确定",
                                    cancelButtonText: "取消",
                                    type: "warning",
                                });
                                const res = await request({
                                    url: `/snow-ops-platform/yhzry/delete`,
                                    method: 'POST',
                                    data: {
                                        id: row.id,
                                    }
                                });
                                if (res.code === '00000') {
                                    ElMessage.success('删除成功');
                                    getyhzryList(qxmc.value, yhzid.value, filterData);
                                } else {
                                    throw new Error(res.message);
                                }
                            } catch (error) {
                                ElMessage.error(error.message);
                                console.log(error);
                            }
                        },
                    },
                    () => "删除"
                ),

            ]),
    },
]

const handleEdit = async () => {
    try {
        await dialogRef?.value?.dynamicComponentRef?.formRef.validate();
        console.log('form', toRaw(form))
        const res = await request({
            url: '/snow-ops-platform/yhzry/update',
            method: 'POST',
            data: toRaw(form),
        });
        if (res.code === '00000') {
            ElMessage.success('编辑成功');
            dialogType.value = '';
            modelVisible.value = false;
            getyhzryList(qxmc.value, yhzid.value, filterData);
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log('error', error)
    }
};

// 获取养护站人员详情
const getDetailData = async (row) => {
    try {
        const res = await request({
            url: `/snow-ops-platform/yhzry/getById?id=${row.id}`,
            method: 'GET',
        });
        if (!res || res.code !== '00000') {
            throw new Error('获取人员详情失败')
        }
        if (res.code === '00000') {
            if (dialogType.value === 'detail') {
                model.title = `人员详情`;
                model.content = DetailDialog;
                model.props = {
                    detailData: res.data,
                };
                model.onCancel = () => {
                    dialogType.value = '';
                    modelVisible.value = false;
                };
                model.onConfirm = () => {
                    dialogType.value = '';
                    modelVisible.value = false;
                };
                model.width = '30%';
                modelVisible.value = true;
            }
            if (dialogType.value === 'edit') {
                model.title = `编辑人员`;
                model.content = EditDialog;
                Object.assign(form, res.data);
                model.props = {
                    detailData: res.data,
                    form: form,
                };
                model.onCancel = () => {
                    dialogType.value = '';
                    modelVisible.value = false;
                };
                model.onConfirm = async () => {
                    await handleEdit();
                };
                model.width = '30%';
                modelVisible.value = true;
            }

        }
        else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log(error);
    }
};

// 根据用户信息 查询角色列表
const getUserList = async (key) => {
    try {
        const keyword = key;
        let url = '';
        if (keyword) {
            url = `/snow-ops-platform/yhzry/getUserByKey?key=${keyword}`
        } else {
            url = `/snow-ops-platform/yhzry/getUserByKey?key=`
        }
        const res = await request({
            url: url,
            method: 'GET',
        });
        if (res.code === '00000') {
            return res.data;
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log(error);
    }
};

// 根据养护站名称 查询养护站列表
const getYhzList = async (key) => {
    try {
        const data = {
            mc: key,
            pageNum: 1,
            pageSize: 9999,
        }
        const res = await request({
            url: '/snow-ops-platform/yhz/list',
            method: 'GET',
            params: data,
        });
        if (res.code === '00000') {
            return res.data.records
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message);
        console.log(error);
    }
};

// 打开新增人员弹窗
const openAddModel = () => {
    model.title = `新增人员`;
    model.content = AddDialog;
    model.width = '30%';
    Object.assign(form, INIT_FORM);
    model.props = {
        detailData: {},
        form: form,
        getUserList: getUserList,
        treeData: treeData,
        yhzid: yhzid,
        yhzmc: yhzmc,
        getYhzList: getYhzList,
    };
    model.onCancel = () => {
        dialogType.value = '';
        modelVisible.value = false;
    };
    model.onConfirm = async () => {
        try {
            form.cjsj = new Date().toLocaleString('sv-SE', { hour12: false }).replace('T', ' ');
            console.log('form', toRaw(form))
            const res = await request({
                url: '/snow-ops-platform/yhzry/add',
                method: 'POST',
                data: toRaw(form),
            });
            if (res.code === '00000') {
                ElMessage.success('新增人员成功');
                dialogType.value = '';
                modelVisible.value = false;
                getyhzryList(qxmc.value, yhzid.value, filterData);
            } else {
                throw new Error(res.message);
            }
        } catch (error) {
            ElMessage.error(error.message);
            console.log('error', error)
        }
    };
    modelVisible.value = true;
}


export default () => {

    const treeRef = ref(null);
    watch(() => filterText.value, (val) => {
        treeRef.value.filter(val || '')

        // 添加自动点击逻辑
        nextTick(() => {
            setTimeout(() => {
                const visibleNodes = getFilteredVisibleNodes()
                if (visibleNodes.length === 2) {
                    handleAutoClickNode(visibleNodes[1])
                }
            }, 100) // 增加 100ms 延迟确保过滤完成
        })

    })

    // 获取过滤后的可见节点
    const getFilteredVisibleNodes = () => {
        return Object.values(treeRef.value?.store?.nodesMap || {})
            .filter(node => node.visible && !node.isHidden)
    }
    const handleAutoClickNode = (node) => {
        // 展开父节点
        if (node.parent) {
            node.parent.expanded = true
        }

        // 执行点击逻辑
        handleNodeClick(
            node.data,
            {
                data: node.data,
                expanded: false,
                isCurrent: true
            }
        )
    }

    watch(
        [() => filterData, qxmc, yhzid],
        ([newFilterData, newQxmc, newYhzid]) => {
            getyhzryList(newQxmc, newYhzid, newFilterData)
        },
        { deep: true }
    )


    const route = useRoute()

    onMounted(async () => {
        await getTreeData();
        await getyhzryList();
        const rowData = JSON.parse(decodeURIComponent(route.params.data));
        if (rowData) {
            filterText.value = rowData.mc;
        };
    });
    return {
        treeRef,
        treeData,
        treeProps,
        filterText,
        filterNode,
        handleNodeClick,

        tableData,
        filterData,
        pagination,
        columns,
        modelVisible,
        dialogRef,
        model,
        openAddModel,
    }
}