import { isOemByEnum, OemType } from '@/common/config/projectName';
import { TradeMode } from '@/common/constants/enumCommon';
import APP from '@/services';
import { isAllEnum } from '@/services/bus/allEnum';
import { isLogin } from '@/services/bus/login';
import { checkTokenLoop, handleTokenCheck } from '@/services/bus/token';
import { getAllEnums, GetPCMenus, getServerTime, queryErrorInfos, QueryTableDefine } from '@/services/go/commonService/index';
import { getAppConfig, getCommonApiUrl } from '@/services/go/config';
import { LoginQuery } from '@/services/go/useInfo/index';
import { serviceURL, setServiceURL } from '@/services/request/serviceURL';
import ProtobufCtr from '@/services/socket/protobuf/index';
import { message } from 'ant-design-vue';
import { queryMarketRun } from '../go/commonMarket';
import { GetErmcpGoods, QueryDeliveryGoodsDetail } from '../go/ermcp/goodsInfo';
import { getTaAccount } from '../go/TaAccount';
import { queryWrMarketTradeConfig } from '../go/wrtrade';
import { getMarketByTradeMode } from './market';

/**
 * 全局数据刷新
 */
export async function globalDataRefresh(): Promise<string> {
    // 全局初始化依赖查询
    await queryDependencies();
    try {
        // 首先判断是否登录 如果没有登录不需要长链
        if (isLogin()) {
            // 获取服务时间，token校验需要用到
            await getServerTime();
            // 建立行情交易长链x
            await APP.connectTrading();
            // token 校验处理
            const res = await handleTokenCheck()
                .then(() => true)
                .catch(() => false);
            if (!res) {
                // Router.push({ path: '/login' }); // 回到登录页面
                return Promise.reject('刷新时token校验失败');
            } else {
                // token校验成功 马上轮询
                checkTokenLoop();
                await Promise.all([GetErmcpGoods(), GetPCMenus(), QueryTableDefine(), LoginQuery(), QueryDeliveryGoodsDetail(), getTaAccount(), queryMarketRun()])
                const marketInfo = getMarketByTradeMode(TradeMode.WarehouseReceiptTrade);
                if (marketInfo) {
                    if (isOemByEnum(OemType.wrspot)) {
                        // 仓单贸易交易规则
                        await queryWrMarketTradeConfig({ marketid: marketInfo.marketid })
                    }
                }
            }
        } else {
            // 重置数据中心数据
            APP.reset();
        }

        // 获取错误信息
        await queryErrorInfos();
        // 获取枚举
        if (!isAllEnum()) {
            await getAllEnums();
        }
        // await queryGoodsList();
        return Promise.resolve('ok');
    } catch (error) {
        return Promise.reject('刷新数据加载失败');
    }
}

function getIco(): string {
    let result = 'favicon'
    if (isOemByEnum(OemType.manager)) {
        result = 'favicon'
    } else if (isOemByEnum(OemType.wrspot)) {
        result = 'favicon1'
    }

    return `./${result}.ico`
}



function setIcon() {
    const link: any = document.querySelector("link[rel*='icon']") || document.createElement('link');
    const obj = {
        type: 'image/x-icon',
        rel: 'shortcut icon',
        href: getIco(),
    }
    Object.assign(link, obj)
    document.title = 'WebPC'
    if (serviceURL.oem === 'yrdz') {
        document.title = '云融'
    }
    document.getElementsByTagName('head')[0].appendChild(link);
}
/**
 * 全局依赖的数据查询，涉及各个方面
 */
async function queryDependencies(): Promise<number> {
    try {
        // 加载proto文件
        await ProtobufCtr.loadProto('./proto/mtp.proto');
        /** 获取接口查询配置信息 */
        const config = await getAppConfig();
        const apiUrl = await getCommonApiUrl(config.data.apiUrl);

        if (apiUrl.data.code === 200) setServiceURL(apiUrl.data.data);
        setIcon()
        // await APP.connectQuote();
        /** 数据返回 */
        return Promise.resolve(1);
    } catch (error) {
        message.error(error.message);
        return Promise.reject(error);
    }
}
