import { h, ref, onMounted, reactive, watch, toRaw, nextTick } from "vue";
import { request } from "@/utils/request";
import { useRoute, useRouter } from 'vue-router'
import DetailDrawer from "./detailDrawer.vue";
import AddDialog from "./addDialog.vue";

const tableData = ref([]); // 表格数据
const filterData = reactive({
    zdlx: "",
    mc: "",
}) // 过滤条件
const modelVisible = ref(false); // 弹窗状态
const drawerVisible = ref(false); // 抽屉状态
const model = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    width: '',
}); // 弹窗内容
const form = reactive({
});
const INIT_FORM = {
    qxmc: "",
    mc: "",
    fzrXm: "",
    fzrSjhm: "",
    fzrUserId: "",
    jd: "",
    wd: "",
};
const drawer = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    direction: 'rtl',
    size: '50%'
}); // 抽屉内容
const dialogType = ref(''); // 弹窗类型
const dialogRef = ref(null); // 弹窗实例
const drawerType = ref(''); // 抽屉类型
const drawerRef = ref(null); // 抽屉实例


// 站点类型选项
const zdlxOptions = [
    { label: "服务设施", value: "服务设施" },
    { label: "加油站", value: "加油站" },
    { label: "加气站", value: "加气站" },
    { label: "加氢站", value: "加氢站" },
    { label: "充电站", value: "充电站" },
];

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;
        getTableData(filterData);
    },
}); // 分页


// 获取养护站列表
const getTableData = async (filterData) => {
    try {
        const res = await request({
            url: "/snow-ops-platform/yhz/list",
            method: "GET",
            params: {
                mc: filterData?.mc || "",
                zdlx: filterData?.zdlx || "",
                pageNum: pagination.current,
                pageSize: pagination.pageSize,
            },
        });
        if (res.code === "00000") {
            tableData.value = res.data.records;
            pagination.total = Number(res.data.total);
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        console.log(error.message);
    }
};

// 获取养护站详情
const getYhzDetail = async (row) => {
    try {
        console.log('row', toRaw(row));
        const res = await request({
            url: `/snow-ops-platform/yhz/getById?id=${row.id}`,
            method: "GET",
        });
        if (res.code === "00000") {
            if (drawerType.value === "detail") {
                drawer.title = '详情'
                drawer.props = {
                    basicData: res.data,
                };
                drawer.onCancel = () => {
                    drawerType.value = '';
                    drawerVisible.value = false;
                    getTableData(filterData);
                };
                drawer.onConfirm = () => {
                    drawerType.value = '';
                    drawerVisible.value = false;
                };
                drawer.content = DetailDrawer;
                drawerVisible.value = true;
            }
        }
    } catch (error) {

    }
};

// 打开新增养护站弹窗
const openAddDialog = () => {
    model.title = '新增养护站';
    Object.assign(form, INIT_FORM);
    model.props = {
        form: form,
    };
    model.content = AddDialog;
    model.onCancel = () => {
        dialogType.value = '';
        modelVisible.value = false;
    };
    model.onConfirm = async () => {
        dialogType.value = '';
        await dialogRef?.value?.dynamicComponentRef?.formRef.validate().then(() => {
            addYHZ();
        })
            .catch((err) => {
                ElMessage.error('请处理表单中的错误项');
            });
    };
    model.width = "50%"
    modelVisible.value = true;
};

// 新增养护站
const addYHZ = async () => {
    try {
        const res = await request({
            url: "/snow-ops-platform/yhz/add",
            method: "POST",
            data: form,
        });
        if (res.code === "00000") {
            ElMessage.success("新增成功");
            modelVisible.value = false;
            getTableData();
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error(error.message || "新增失败");
    }
};

export default () => {

    const router = useRouter();
    const handleClickSb = (row) => {
        router.push({
            path: `/yhzsb/${encodeURIComponent(JSON.stringify(row))}`,
        });
    };
    const handleClickWz = (row) => {
        router.push({
            path: `/yhzwz/${encodeURIComponent(JSON.stringify(row))}`,
        });
    };

    const columns = [
        {
            prop: "mc",
            label: "服务站名称",
        },
        {
            prop: "sbsl",
            label: "设备数量",
            render: (row) => () =>
                h(
                    ElButton,
                    {
                        link: true,
                        type: "primary",
                        onClick: () => handleClickSb(row),
                    },
                    () => row.sbsl
                ),
        },
        {
            prop: "wzsl",
            label: "物资数量",
            render: (row) => () =>
                h(
                    ElButton,
                    {
                        link: true,
                        type: "primary",
                        onClick: () => handleClickWz(row),
                    },
                    () => row.wzsl
                ),
        },
        {
            prop: "rysl",
            label: "人员数量",
        },
        {
            prop: "qxmc",
            label: "区县名称",
        },
        {
            label: "操作",
            fixed: "right",
            width: 150,
            render: (row) => () =>
                h("div", { class: "action-btns" }, [
                    h(
                        ElButton,
                        {
                            type: "primary",
                            link: true,
                            onClick: async () => {
                                drawerType.value = "detail";
                                await getYhzDetail(row);
                            },
                        },
                        () => "详情"
                    ),
                    h(
                        ElButton,
                        {
                            type: "danger",
                            link: true,
                            style: "margin-left: 10px;",
                            onClick: async () => {
                                try {
                                    await ElMessageBox.confirm("确定要删除该站点吗？", "删除确认", {
                                        confirmButtonText: "确定",
                                        cancelButtonText: "取消",
                                        type: "warning",
                                    });
                                    const res = await request({
                                        url: `/snow-ops-platform/yhz/delete`,
                                        method: "POST",
                                        data: {
                                            id: row.id,
                                        },
                                    });
                                    if (res.code === "00000") {
                                        ElMessage.success("删除成功");
                                        getTableData();
                                    }
                                } catch (error) {
                                    if (error instanceof Error) {
                                        ElMessage.error(error.message || "删除失败");
                                    }
                                }
                            },
                        },
                        () => "删除"
                    ),
                ]),
        },
    ];



    // 监听过滤条件变化
    watch(
        [() => filterData],
        ([newFilterData]) => {
            getTableData(newFilterData)
        },
        { deep: true }
    )

    onMounted(async () => {
        await getTableData()
    });

    return {
        tableData,
        filterData,
        zdlxOptions,
        pagination,
        columns,
        handleClickSb,
        handleClickWz,

        modelVisible,
        model,
        drawerVisible,
        drawer,
        dialogRef,
        drawerRef,
        openAddDialog,

    }
}