import { BtnListType } from '@/common/components/btnList/interface';
import { ContextMenuTemp } from "@/common/components/contextMenu/interface";
import { handleContextMenu } from "@/common/components/contextMenu/setup";
import { TabList } from '@/common/components/description/interface';
import { getTableColumns, getTableEvent, initData } from "@/common/export/table";
import { handleModalComponent } from '@/common/setup/asyncComponent';
import { onUnmounted, ref, Ref } from "vue";
import { getBtnList_, getOrderBtnList, getThirdMenuData } from "./button";
import { handleTableColums } from './clolumn';
import { handleTableDrawer } from "./drawer";
import { ComposeOrderTableParam, ComposeTableDetailParam, ComposeTableParam, TableEventCB, TableParam } from "./interface";

export type { ComposeTableParam, ComposeTableDetailParam };

// 表格 + 表头 + 右键 + 单击表格 + 按钮列表 通用处理逻辑
export function handleComposeTable<T>({ queryFn, menuType, isDetail, tableName, tableFilterKey }: ComposeTableParam) {
    // 右键逻辑
    const { contextMenu, openContext, closeContext: closeContextAction } = handleContextMenu();
    // 表头数据
    const { columns, registerColumn, updateColumn } = getTableColumns();
    // 右键回调函数
    const eventsCB: TableEventCB = {
        contextmenuCB: (record: T, value: ContextMenuTemp) => {
            // 控制打开右键
            contextMenu.value = value
        }
    }
    // 表格事件
    const { expandedRowKeys, selectedRow, Rowclick } = getTableEvent<T>(eventsCB);
    // 表格操作按钮列表
    const [firstBtn, secondBtn] = getBtnList_(menuType, isDetail).value;
    // 控制异步组件
    const { componentId, closeComponent, openComponent } = handleModalComponent(queryFn, selectedRow);
    // 关闭右键
    function closeContext(value: BtnListType | null) {
        // 打开对应的弹窗组件
        if (value) openComponent(value, selectedRow.value)
        // 关闭右键
        closeContextAction()
    }
    onUnmounted(() => {
        // 离开组件，手动关闭右键，防止出现bug
        closeContextAction()
    })
    initData(() => {
        // 获取列表数据
        queryFn();
        // 注册表头信息 过滤
        if (tableName) {
            registerColumn(tableName, tableFilterKey);
        }
    }); return {
        contextMenu, openContext, closeContext, // 右键
        columns, registerColumn, updateColumn,  // 表头
        expandedRowKeys, selectedRow, Rowclick, // 表格折腾面板数据与单击、双击事件
        componentId, closeComponent, openComponent,  // 控制异步组件
        firstBtn, secondBtn, // 表格按钮
    }
}


// 表格 + 表头 + 表格明细 + 单击表格  通用处理逻辑
export function handleComposeTable_detail<T>({ queryFn, tableName, tableFilterKey, menuType }: ComposeTableDetailParam) {
    // 控制 drawer 组件是否显示
    const { visible, openDrawer, closeDrawer } = handleTableDrawer()
    // 表头数据
    const { columns, registerColumn, updateColumn } = getTableColumns();
    // 明细列表数据
    const detailTableList = ref<any[]>([])
    // 明细表头数据
    const { columns: columnsDetail, registerColumn: registerColumnDetail, updateColumn: updateColumnDetail } = getTableColumns();
    // 缓存点击选中的数据
    let cacheSelectedRow: null | Ref<T> = null
    // 单击回调
    const events: TableEventCB = {
        clickCB: (value: T) => {
            if (cacheSelectedRow) {
                // 点击同一个
                if (JSON.stringify(cacheSelectedRow.value) === JSON.stringify(value)) {
                    visible.value ? closeDrawer() : openDrawer()
                } else {
                    openDrawer()
                }
            } else {
                openDrawer()
            }
        },
    };
    // 表格事件
    const { expandedRowKeys, selectedRow, Rowclick } = getTableEvent<T>(events);
    cacheSelectedRow = selectedRow as Ref<T>
    // 明细tab 列表
    const data = getThirdMenuData()
    const list = data.find((e) => e.code === menuType);
    const tabList = ref<TabList[]>([])
    list?.children.forEach(el => {
        const { code, title, type } = el
        if (type === 3) {
            tabList.value.push({ lable: title, code })
        }
    })

    initData(() => {
        queryFn();
        registerColumn(tableName, tableFilterKey);
    });
    return {
        visible, openDrawer, closeDrawer,   // 控制 drawer 组件是否显示
        columns, registerColumn, updateColumn,  //  表头数据
        columnsDetail, registerColumnDetail, updateColumnDetail, detailTableList,// 明细表头数据
        expandedRowKeys, selectedRow, Rowclick, // 表格事件
        tabList,
    }
}

// 获取单据table通用逻辑
export function handleComposeOrderTable<T>({ queryFn, recordList, isDetail, tableName, }: ComposeOrderTableParam) {
    // 右键逻辑
    const { contextMenu, openContext, closeContext: closeContextAction } = handleContextMenu();
    // 表头数据
    const { columns, registerColumn, updateColumn } = getTableColumns();
    // 右键回调函数
    const eventsCB: TableEventCB = {
        contextmenuCB: (record: T, value: ContextMenuTemp) => {
            // 控制打开右键
            contextMenu.value = value
        }
    }
    // 表格事件
    const { expandedRowKeys, selectedRow, Rowclick } = getTableEvent<T>(eventsCB);
    // 表格操作按钮列表
    const btnList = getOrderBtnList(recordList, isDetail).value;
    console.log('表格操作按钮列表', btnList)
    // 控制异步组件
    const { componentId, closeComponent, openComponent } = handleModalComponent(queryFn, selectedRow);
    // 关闭右键
    function closeContext(value: BtnListType | null) {
        // 打开对应的弹窗组件
        if (value) openComponent(value, selectedRow.value)
        // 关闭右键
        closeContextAction()
    }
    onUnmounted(() => {
        // 离开组件，手动关闭右键，防止出现bug
        closeContextAction()
    })
    initData(() => {
        // 获取列表数据
        queryFn();
        // 注册表头信息 过滤
        registerColumn(tableName, []);
    }); return {
        contextMenu, openContext, closeContext, // 右键
        columns, registerColumn, updateColumn,  // 表头
        expandedRowKeys, selectedRow, Rowclick, // 表格折腾面板数据与单击、双击事件
        componentId, closeComponent, openComponent,  // 控制异步组件
        btnList, // 表格按钮
    }
}


export function handleTableEventAndData<T>({ queryFn, columnsList, clickName }: TableParam) {
    // 右键逻辑
    const { contextMenu, openContext, closeContext: closeContextAction } = handleContextMenu();
    // 表头
    const { columns, updateColumn } = handleTableColums(columnsList);
    // 控制异步组件
    const componentId = ref<string>('');
    // 关闭组件
    function closeComponent(isRefresh: boolean) {
        componentId.value = '';
        if (isRefresh) {
            queryFn()
        }
    }
    /**
 * 打开组件
 * @param item
 * @param record
 */
    function openComponent(item: BtnListType, record: T) {
        console.log('打开组件: ', item.code)
        // 更新点击的数据，处理例如，修改之后，再次打开页面是之前的数据的问题
        if (record && selectedRow) {
            selectedRow.value = record
        }
        componentId.value = item.code;
    }
    // 右键回调函数
    const eventsCB: TableEventCB = {
        contextmenuCB: (record: T, value: ContextMenuTemp) => {
            // 控制打开右键
            contextMenu.value = value
        },
        clickCB: (record: T) => {
            clickName && (componentId.value = clickName)
        }
    }
    initData(() => {
        // 获取列表数据
        queryFn();
    })
    // 表格事件
    const { expandedRowKeys, selectedRow, Rowclick } = getTableEvent<T>(eventsCB);
    // 关闭右键
    function closeContext(value: BtnListType | null) {
        // 打开对应的弹窗组件
        if (value) componentId.value = value.code;
        // 关闭右键
        closeContextAction()
    }
    return {
        contextMenu, openContext, closeContext, // 右键
        columns, updateColumn,  // 表头
        expandedRowKeys, selectedRow, Rowclick, // 表格折腾面板数据与单击、双击事件
        componentId, closeComponent, openComponent,  // 控制异步组件
    }
}