import { Table } from "./interface";
import { reactive, computed, toRefs, watch, isRef } from "vue";

export const useTable = (
    routeName: any,
    api?: (params: any) => Promise<any>,
    initParam: object | Ref<object> = {},
    isPageable: boolean = true,
    requestError?: (error: any) => void,
    clearSelection?: () => void
) => {
    const state = reactive<Table.StateProps>({
        tableData: [],
        pageable: {
            page: 1,
            size: 50,
            total_size: 0
        },
        searchParam: {},
        totalParam: {} // 保留作为参数快照
    });

    // 分页参数计算属性
    const pageParam = computed({
        get: () => ({
            page: state.pageable.page,
            size: state.pageable.size
        }),
        set: (newVal: any) => {
            console.log("分页参数更新:", newVal);
        }
    });

    //数据处理
    const initSubscribeData = () => {
        if (routeName === "foundationSubscribeList") {
            if (Array.isArray(state.totalParam?.org_number) && state.totalParam?.org_number?.length) {
                state.totalParam.org_number = state.totalParam.org_number.join(",");
            }
            //品线
            if (Array.isArray(state.totalParam?.product_line_name) && state.totalParam?.product_line_name?.length) {
                state.totalParam.org_number = state.totalParam.product_line_name.join(",");
            }
            //客户名称
            if (Array.isArray(state.totalParam?.customer_number) && state.totalParam?.customer_number?.length) {
                state.totalParam.customer_number = state.totalParam.customer_number.join(",");
            }
            //客户编码
            if (state.totalParam?.customer_number1) {
                if (Array.isArray(state.totalParam.customer_number) && !state.totalParam.customer_number.length) {
                    state.totalParam.customer_number = state.totalParam.customer_number1;
                } else {
                    state.totalParam.customer_number = state.totalParam.customer_number + "," + state.totalParam.customer_number1;
                }
            }
        }
        if (routeName === "foundationSubscribeWarehousing") {
            if (Array.isArray(state.totalParam?.org_number) && state.totalParam?.org_number?.length) {
                state.totalParam.org_number = state.totalParam.org_number.join(",");
            }
            if (state.totalParam?.subscriber_name) {
                // let names: any = "";
                state.totalParam.subscriber_name = state.totalParam?.subscriber_name.replace(/[，,]/g, ",");
            }
        }
    };
    //删除临时参数和空值参数
    const deleteParams = () => {
        const KEY = ["Time", "customer_number1"];
        for (let key in state.totalParam) {
            if (KEY.includes(key) || !state.totalParam[key]) {
                delete state.totalParam[key];
            }
        }
    };
    /**
     * 获取表格数据
     * 每次请求都基于最新的initParam和分页参数重新合并
     */
    const getTableList = async () => {
        if (!api) return;

        try {
            initSubscribeData();
            deleteParams();
            let params = {
                ...state.totalParam,
                ...pageParam.value
            };
            const { data } = await api(params);
            state.tableData = data.data || [];
            clearSelection && clearSelection();
            if (isPageable && data.total_size !== undefined) {
                updatePageable({
                    page: state.pageable.page,
                    size: state.pageable.size,
                    total_size: data.total_size
                });
            }
        } catch (error) {
            console.error("表格数据请求失败:", error);
            requestError && requestError(error);
        }
    };

    /**
     * 更新分页信息
     */
    const updatePageable = (pageable: Table.Pageable) => {
        Object.assign(state.pageable, pageable);
    };

    /**
     * 处理每页条数变化
     */
    const handleSizeChange = (val: number) => {
        state.pageable.page = 1; // 重置到第一页
        state.pageable.size = val;
        getTableList();
    };

    /**
     * 处理当前页变化
     */
    const handleCurrentChange = (val: number) => {
        state.pageable.page = val;
        getTableList();
    };

    /**
     * 监听initParam变化，同步到searchParam和totalParam
     */
    watch(
        () => (isRef(initParam) ? initParam.value : initParam),
        (newVal: any) => {
            state.totalParam = {};
            // 同步到查询参数
            state.searchParam = { ...newVal };
            // 同步到参数快照
            state.totalParam = { ...newVal, ...pageParam.value };
        },
        { deep: true, immediate: true }
    );

    return {
        ...toRefs(state),
        getTableList,
        handleSizeChange,
        handleCurrentChange,
        updatePageable
    };
};
