import { WatchStopHandle, ref, unref, watch } from "vue";
import { BaseTableProps, TableActionType, TableColumns, TableProps, UseTableReturnType } from "../types";

/**
 * useTable 表格
 */
export function useTable(tableProps?: TableProps): UseTableReturnType {
    const tableRef = ref<Nullable<TableActionType>>(null);

    // 判断table是否挂载
    function getTableInstance(): TableActionType {
        const table = unref(tableRef);
        if (!table) {
            console.error('表格未挂载!');
        }
        return table as TableActionType;
    }
    // 停止监听器
    let stopWatch: WatchStopHandle;

    // 注册table的事件
    function register(instance: TableActionType) {
        if (instance === unref(tableRef)) return;
        tableRef.value = instance;

        stopWatch?.();

        // 监听数据并且设置table
        stopWatch = watch(
            () => tableProps,
            () => {
                tableProps && instance.setProps(tableProps as Partial<BaseTableProps>);
            },
            {
                immediate: true,
                deep: true,
            },
        );
    }

    // 处理的事件
    const methods: TableActionType = {
        // 设置table的数据
        setProps: (props: Partial<BaseTableProps>) => {
            getTableInstance().setProps(props);
        },
        // 设置table的表头内容
        setColumns: (props: TableColumns[]) => {
            getTableInstance().setColumns(props);
        },
        // 设置table数据
        setDataSource: (dataSource: Recordable[]) => {
            getTableInstance().setDataSource(dataSource);
        },
        // 获取table数据
        getDataSource: () => {
            return getTableInstance().getDataSource();
        },
        // 设置loading
        setLoading: (loading: boolean) => {
            getTableInstance().setLoading(loading);
        },
        // 获取复选框选中的数据
        getSelectRows: async () => {
            return await getTableInstance().getSelectRows();
        },
        // 清除复选框选中的数据
        clearSelectedRow: () => {
            getTableInstance().clearSelectedRow();
        },
    }

    return [register, methods];
}
