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 yhzData = ref(); // 养护站信息
const filterData = reactive({
    wzmc: '',
}); // 表格过滤条件
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;
        getyhzwzList(qxmc.value, yhzid.value, filterData);
    },
}); // 表格分页
const modelVisible = ref(false); // 弹窗显示状态
const model = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
}); // 弹窗内容
const dialogType = ref(''); // 弹窗类型
const dialogRef = ref(null); // 弹窗实例

const drawerVisible = ref(false); // 抽屉显示状态
const drawer = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    direction: 'rtl',
    size: '50%'
}); // 抽屉内容
const drawerType = ref(''); // 抽屉类型
const drawerRef = ref(null); // 抽屉实例



const INIT_FORM = {
    material: {
        rkrq: "",
        rkdw: "",
        sl: "",
        dw: "",
        cfdd: "",
        fzr: "",
        lxdh: "",
        ye: "",
        qxmc: "",
        wzmc: "",
        fzrid: "",
        yhzid: "",
        jd: "",
        wd: "",
    },
    photos: [],
}; // 表单初始值
const form = reactive({ ...INIT_FORM }); // 表单

// 重置表单方法
const resetForm = () => {
    // 深拷贝重置嵌套对象
    form.material = { ...INIT_FORM.material };
    form.photos = [...INIT_FORM.photos];

    form.material.yhzid = yhzid.value;
    form.material.jd = yhzData.value?.jd;
    form.material.wd = yhzData.value?.wd;
};



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

    const nodeData = node || {}

    if (nodeData.type === 'root') {
        return true;
    }

    // 处理区域节点匹配
    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=MATERIAL',
            method: 'GET'
        })
        if (res.code === '00000') {
            treeData.value = [{
                id: -1,
                name: `全部(${res.data.totalWzsl})`,
                type: "root",
                children: res.data.areaList.map((qx, index) => (
                    {
                        id: qx.qxmc,
                        name: `${qx.qxmc}(${qx.wzsl})`,
                        type: 'area',
                        children: qx.yhzList.map(site => ({
                            id: site.id,
                            name: `${site.mc}(${site.wzsl})`,
                            type: 'site',
                            qxmc: qx.qxmc,
                            rawName: site.mc,
                            jd: site.jd,
                            wd: site.wd,
                        })),
                        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 === 'root') {
        console.log('你点击的是全部')
        yhzid.value = ''; // 重置养护站id
        qxmc.value = ''; // 重置区县名称
        yhzData.value = null; // 重置养护站信息
        return;
    };
    // if (data.type === 'area' && node.expanded === false) {
    //     console.log('树节点关闭', node.expanded)
    //     yhzid.value = ''; // 重置养护站id
    //     qxmc.value = ''; // 重置区县名称
    //     return;
    // }
    if (data.type === 'area') {
        console.log('你点击的是区县', data.rawName)
        yhzid.value = ''; // 重置养护站id
        qxmc.value = data.rawName; // 保存区县名称
        yhzData.value = null; // 重置养护站信息
        return;
    }
    if (data.type === 'site') {
        console.log('你点击的是站点', data.name)
        yhzid.value = data.id; // 保存养护站id
        qxmc.value = ''; // 重置区县名称
        yhzData.value = {
            jd: data.jd,
            wd: data.wd,
            rawName: data.rawName,
        }
        return;
    }
};

// 获取养护站物资列表
const getyhzwzList = async (qxmc, yhzid, filterData) => {
    try {
        const data = {
            qxmc: qxmc,
            yhzid: yhzid,
            wzmc: filterData?.wzmc || '',
            pageNum: pagination.current,
            pageSize: pagination.pageSize,
            requestSource: 'web', // web: Web端请求，app：移动端请求
        }
        const res = await request({
            url: '/snow-ops-platform/yjwz/list',
            method: 'GET',
            params: data,
        })
        if (res.code === '00000') {
            tableData.value = res.data.records;
            pagination.total = Number(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: 'wzmc',
        label: '物资名称',
    },
    {
        prop: 'ye',
        label: '余量',
    },
    {
        prop: 'dw',
        label: '单位',
    },
    {
        prop: 'fzr',
        label: '负责人',
    },
    {
        prop: 'rkrName',
        label: '入库人',
    },
    {
        prop: 'rkrq',
        label: '入库日期',
    },
    {
        prop: 'yhzMc',
        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/yjwz/delete`,
                                    method: 'POST',
                                    data: {
                                        rid: row.rid,
                                    }
                                });
                                if (res.code === '00000') {
                                    ElMessage.success('删除成功');
                                    getyhzwzList(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/yjwz/update',
            method: 'POST',
            data: toRaw(form),
        });
        if (res.code === '00000') {
            ElMessage.success('编辑成功');
            dialogType.value = '';
            modelVisible.value = false;
            getyhzwzList(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/yjwz/getById?rid=${row.rid}`,
            method: 'GET',
        });
        if (!res || res.code !== '00000') {
            throw new Error('获取物资详情失败')
        }
        if (res.code === '00000') {
            if (dialogType.value === 'detail') {
                drawer.title = `物资详情`;
                drawer.content = DetailDialog;
                drawer.props = {
                    detailData: res.data,
                };
                drawer.onCancel = () => {
                    dialogType.value = '';
                    drawerVisible.value = false;
                };
                drawer.onConfirm = () => {
                    dialogType.value = '';
                    drawerVisible.value = false;
                };
                drawerVisible.value = true;
            }
            if (dialogType.value === 'edit') {
                model.title = `编辑物资`;
                model.content = EditDialog;
                Object.assign(form, res.data.material);
                model.props = {
                    detailData: res.data.material,
                    form: form,
                };
                model.onCancel = () => {
                    dialogType.value = '';
                    modelVisible.value = false;
                };
                model.onConfirm = async () => {
                    await handleEdit();
                };
                modelVisible.value = true;
            }

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

// 打开新增物资弹窗
const openAddModel = () => {
    if (!yhzid.value) {
        ElMessage.error('请先选择养护站');
        return;
    }
    model.title = `新增物资`;
    model.content = AddDialog;
    resetForm(); // 重置表单
    model.props = {
        yhzData: yhzData.value,
        form: form,
    };
    model.onCancel = () => {
        dialogType.value = '';
        modelVisible.value = false;
    };
    model.onConfirm = async () => {
        await dialogRef?.value?.dynamicComponentRef?.formRef
            .validate()
            .then(async () => {
                try {
                    console.log('form', toRaw(form))
                    const res = await request({
                        url: '/snow-ops-platform/yjwz/add',
                        method: 'POST',
                        data: toRaw(form),
                    });
                    if (res.code === '00000') {
                        ElMessage.success('新增成功');
                        dialogType.value = '';
                        modelVisible.value = false;
                        getyhzwzList(qxmc.value, yhzid.value, filterData);
                    } else {
                        throw new Error(res.message);
                    }
                } catch (error) {
                    ElMessage.error(error.message);
                    console.log('error', error)
                }
            })
            .catch((err) => {
                ElMessage.error('请处理表单中的错误项');
            });
    };
    model.width = '40%';
    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 === 3) {
                    handleAutoClickNode(visibleNodes[0])
                }
            }, 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]) => {
            getyhzwzList(newQxmc, newYhzid, newFilterData)
        },
        { deep: true }
    )


    const route = useRoute()

    onMounted(async () => {
        await getTreeData();
        await getyhzwzList();
        const rowData = (decodeURIComponent(route.params?.data));
        if (rowData !== 'undefined' && rowData !== 'null' && rowData !== '') {
            const JSONData = JSON.parse(rowData);
            filterText.value = JSONData.mc;
        };
    });
    return {
        treeRef,
        treeData,
        treeProps,
        filterText,
        filterNode,
        handleNodeClick,

        tableData,
        filterData,
        pagination,
        columns,
        modelVisible,
        dialogRef,
        model,
        openAddModel,
        drawerVisible,
        drawer,
        drawerRef,
        yhzid,
    }
}