import { BtnListType } from '@/common/components/btnList/interface';
import { ContextMenuTemp } from "@/common/components/contextMenu/interface";
import { handleContextMenu } from "@/common/components/contextMenu/setup";
import { EnumRouterName } from '@/common/constants/enumRouterName';
import { getTableColumns, getTableEvent, initData } from "@/common/export/table";
import { findChildList, getClassName } from "@/common/setup/table/button";
import { ComposeTableParam, TableEventCB } from "@/common/setup/table/interface";
import { OperationTabMenu } from '@/services/go/commonService/interface';
import { queryFilterItem, queryFtDeliveryGoods } from '@/services/go/wrtrade';
import { WrFilterItem } from '@/services/go/wrtrade/interface';
import TimerUtils from '@/utils/timer/timerUtil';
import { onMounted, onUnmounted, ref } from "vue";
import { BuyAndSellMarket, TreeDataItem } from './interface';

const buyAndSellEunm = 'buyAndSell'

export function handleSpotBtnList(menuType: EnumRouterName) {
    let firstBtn: BtnListType[] = []
    // 买大厅数据
    const buyMarket: BuyAndSellMarket = {
        isMarket: true,
        btnList: []
    }

    // 卖大厅数据
    const sellMarket: BuyAndSellMarket = {
        isMarket: true,
        btnList: []
    }
    // 表格操作按钮列表
    const list = findChildList(menuType);
    if (list) {
        const fnMap = (arr: OperationTabMenu[]) => {
            return arr.map(e => {
                const { code, title } = e;
                return { lable: title, code, className: getClassName(code) }
            })
        }
        // 过滤报价大厅按钮列表
        const temp = list.children.filter(e => e.type === 2)
        firstBtn = fnMap(temp)

        const fn = (code: EnumRouterName) => {
            const findResult = list.children.find(e => e.code === code)
            const result: BuyAndSellMarket = { isMarket: false, btnList: [] }
            if (findResult) {
                result.isMarket = true
                const arr = findResult.children.filter(e => e.type === 2)
                result.btnList = fnMap(arr)
            }
            return result
        }

        // 处理买大厅
        Object.assign(buyMarket, fn(EnumRouterName.spot_trade_warehouse_buy_hall))
        // 处理卖大厅
        Object.assign(sellMarket, fn(EnumRouterName.spot_trade_warehouse_sell_hall))
    }
    return { firstBtn, buyMarket, sellMarket }
}

// 表格 + 表头 + 右键 + 单击表格 + 按钮列表 通用处理逻辑
export function handleComposeTable<T>({ queryFn, menuType, isDetail, tableName, tableFilterKey }: ComposeTableParam) {
    // 右键逻辑
    const { contextMenu, openContext, closeContext: closeContextAction } = handleContextMenu();
    // 表头数据
    const { columns, registerColumn, updateColumn } = getTableColumns();
    // 控制异步组件
    const componentId = ref<string>('');
    // 关闭组件
    function closeComponent(isRefresh: boolean) {
        componentId.value = '';
        if (isRefresh) {
            queryFn()
        }
    }
    // 右键回调函数
    const eventsCB: TableEventCB = {
        contextmenuCB: (record: T, value: ContextMenuTemp) => {
            // 控制打开右键
            contextMenu.value = value
        },
        clickCB: (record: T) => {
            componentId.value = buyAndSellEunm
        }
    }
    // 表格事件
    const { expandedRowKeys, selectedRow, Rowclick } = getTableEvent<T>(eventsCB);
    // 表格操作按钮列表
    const { firstBtn } = handleSpotBtnList(menuType)
    firstBtn.push({ lable: '买卖大厅', code: buyAndSellEunm, className: 'btnPrimary' })

    // 关闭右键
    function closeContext(value: BtnListType | null) {
        // 打开对应的弹窗组件
        if (value) componentId.value = value.code;
        // 关闭右键
        closeContextAction()
    }
    onUnmounted(() => {
        // 离开组件，手动关闭右键，防止出现bug
        closeContextAction()
    })
    initData(() => {
        // 获取列表数据
        queryFn();
        // 10秒刷新一次列表
        TimerUtils.setInterval(() => {
            queryFn()
        }, 10 * 1000, 'spotTrade')
        // 注册表头信息 过滤
        if (tableName) {
            registerColumn(tableName, tableFilterKey);
        }

    });
    onMounted(() => {
        TimerUtils.clearInterval('spotTrade')
    });
    return {
        contextMenu, openContext, closeContext, // 右键
        columns, registerColumn, updateColumn,  // 表头
        expandedRowKeys, selectedRow, Rowclick, // 表格折腾面板数据与单击、双击事件
        componentId, closeComponent,  // 控制异步组件
        firstBtn, // 表格按钮
    }
}


const FtDeliveryGoods = ref<TreeDataItem[]>([])
// 获取报价大厅商品过滤项数据
export function handleFtDeliveryGoods() {
    if (FtDeliveryGoods.value.length === 0) {
        initData(() => {
            queryFtDeliveryGoods().then(res => {
                const result: TreeDataItem[] = []
                res.forEach(el => {
                    const { deliverygoodsid, deliverygoodsname, wdlst } = el
                    const item: TreeDataItem = {
                        title: deliverygoodsname,
                        key: deliverygoodsid,
                        value: deliverygoodsid,
                        children: []
                    }
                    wdlst.forEach(e => {
                        const { wrstandardid, wrstandardname } = e
                        item.children?.push({ value: wrstandardid, key: wrstandardid, title: wrstandardname })
                    })
                    result.push(item)
                })
                FtDeliveryGoods.value = result;
            })
        })
    }
    return { FtDeliveryGoods }
}

// 处理仓库
const warehouseList = ref<WrFilterItem[]>([])
export function handleWarehouse() {
    initData(() => {
        if (warehouseList.value.length === 0) {
            queryFilterItem({ itype: '3' }).then(res => {
                warehouseList.value = res
            })
        }
    })
    return { warehouseList }
}

