import { BtnListType } from '@/common/components/btnList/interface';
import { ContextMenuTemp } from '@/common/components/contextMenu/interface';
import { handleContextMenu } from '@/common/components/contextMenu/setup';
import { AuctionwrType, ListingMode } from '@/common/constants/enumCommon';
import { ComposeTableParam } from '@/common/export/commonTable';
import { initData } from '@/common/methods';
import { getTableColumns, getTableEvent } from '@/common/setup/table';
import { TableEventCB } from '@/common/setup/table/interface';
import APP from '@/services';
import { TjmdMarketSection, TjmdMarketSectionConfig } from '@/services/go/Tjmd/interface';
import { queryFtDeliveryGoods } from '@/services/go/wrtrade';
import TimerUtils from '@/utils/timer/timerUtil';
import { onUnmounted, ref } from 'vue';
import { TreeDataItem } from './interface';

const buyAndSellEunm = 'buyAndSell'

// 动态市场 具体显示的市场
export const marketTradeType = ref<string>('')

export function setMarketId(value: string) {
    marketTradeType.value = value
}

function getType() {
    return marketTradeType.value.split('-')
}

// 判断 仓单类型
export function getAuctionwrType(type: AuctionwrType) {
    const arr = getType()
    return type === +arr[1]
}

// 判断 挂牌方式
export function getListingMode(mode: ListingMode) {
    const arr = getType()
    return mode === +arr[2]
}

export const useMarketsSection = () => {
    // 市场板块
    const marketsSetion = APP.getRef('marketsSection')
    // 市场
    const markets = ref<TjmdMarketSectionConfig[]>([])
    // 选中的市场
    const selctedMarket = ref<TjmdMarketSectionConfig | null>(null)
    initData(() => {
        if (marketsSetion.value.length) {
            markets.value = marketsSetion.value[0].mlist
        }
    })
    // 切换市场板块
    function selectSection(value: TjmdMarketSection) {
        markets.value = [...value.mlist, ...value.mlist]
    }
    // 切换市场
    function onSelectMarket(value: TjmdMarketSectionConfig) {
        selctedMarket.value = value
    }

    return { marketsSetion, selectSection, markets, onSelectMarket, selctedMarket }
}

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

// 表格 + 表头 + 右键 + 单击表格 + 按钮列表 通用处理逻辑
export function handleComposeTable<T>({ queryFn, tableName }: 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: BtnListType[] = []
    firstBtn.push({ lable: '买卖大厅', code: buyAndSellEunm, className: 'btnPrimary' })

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

    });

    return {
        contextMenu, openContext, closeContext, // 右键
        columns, registerColumn, updateColumn,  // 表头
        expandedRowKeys, selectedRow, Rowclick, // 表格折腾面板数据与单击、双击事件
        componentId, closeComponent,  // 控制异步组件
        firstBtn, // 表格按钮
    }
}


