import { TradeMode } from '@/common/constants/enumCommon';
import { initData } from '@/common/methods';
import APP from '@/services';
import { Ref, ref, toRefs } from 'vue';
import { Goods, GoodsQuote } from '../go/ermcp/goodsInfo/interface';
import { QueryQuoteDayRsp } from '../go/quote/interface';
import { Goodsgroup, Market } from '../go/useInfo/interface';
import { getMarketByTradeMode } from './market';

// 获取全部商品信息
export function getGoodsList(): Goods[] {
    return APP.get('Goods')
}

// 获取全部上市 商品信息
export function getIPOGoodsList(): Goods[] {
    //商品状态- 1:待审核 2:未上市 3:上市 4:已注销 5:审核拒绝 6:退市 7:待退市
    return getGoodsList().filter(e => e.goodsstatus === 3)
}

// 通过trademode 获取商品
export function getGoodsListByTrade(trademode: TradeMode): Ref<Goods[]> {
    const result = ref<Goods[]>([])
    initData(() => {
        const marketInfo = getMarketByTradeMode(trademode)
        if (marketInfo) {
            result.value = getGoodsList().filter(e => e.marketid === marketInfo.marketid)
        }
    })
    return result
}

// 通过trademode 获取行情，并获取goodsname
export function getQutoGoodsByTradeMode(trademode: TradeMode) {
    const result = ref<QueryQuoteDayRsp[]>([])
    initData(() => {
        // 获取市场信息
        const marketInfo = getMarketByTradeMode(trademode)
        if (marketInfo) {
            // 过滤商品信息
            // goodsstatus: number;//商品状态- 1:待审核 2:未上市 3:上市 4:已注销 5:审核拒绝 6:退市 7:待退市
            const goodsList = getGoodsList().filter(e => (e.goodsstatus === 3 && e.marketid === marketInfo.marketid))
            goodsList.forEach(el => {
                // 找到行情数据
                const quote = getQuoteDayInfoByCode(el.goodscode);
                if (quote) {
                    Object.assign(quote, { goodsname: el.goodsname, goodsid: el.goodsid })
                    result.value.push(quote)
                }
                console.log('result', result)
            })
        }
    })
    return result
}

export function getGoodsByCode(goodsCode: string): Goods | undefined {
    return getGoodsList().find(e => e.goodscode.toUpperCase() === goodsCode.toUpperCase())
}

// 获取全部盘面信息
export function getAllQuoteDayInfo(): QueryQuoteDayRsp[] {
    return APP.get('quoteDayInfo')
}

// 通过goodscode获取对应的商品盘面信息
export function getQuoteDayInfoByCode(goodsCode: string): QueryQuoteDayRsp | undefined {
    return getAllQuoteDayInfo().find(e => e.goodscode.toUpperCase() === goodsCode.toUpperCase())
}

// 通过goodcode 获取商品最新价
export function getQuoteDayInfoByCodeFindPrice(goodsCode: string) {
    const goods = getGoodsByCode(goodsCode);
    let result: number | string = '--';
    if (goods) {
        const quoteData = getQuoteDayInfoByCode(goodsCode);
        // 期货合约取价顺序：现价－>实时结算价->昨结算价
        if (quoteData) {
            if (quoteData.last) {
                result = quoteData.last;
            } else if (quoteData.settle) {
                result = quoteData.settle;
            } else if (quoteData.presettle) {
                result = quoteData.presettle;
            } else {
                result = '--'
            }
        }
        // result = typeof result === 'number' ? Number(result.toFixed(goods?.decimalplace)) : result;
    }
    return result
}

// 获取全部商品组信息
export function getAllGoodsGroups(): Goodsgroup[] {
    return APP.get('goodsgroups')
}

export function getGoodsGroupsByTradeMode(trademode: TradeMode): Goodsgroup[] {
    const marketInfo = getMarketByTradeMode(trademode)
    let result: Goodsgroup[] = []
    if (marketInfo) {
        result = getAllGoodsGroups().filter(e => e.marketid === marketInfo.marketid)
    } else {
        console.warn(`trademode:${trademode}市场信息不存在`)
    }
    return result
}

// 通过 goodsid 查找 商品
export function getGoodsById(goodsid: number) {
    return getGoodsList().find(el => el.goodsid === goodsid)
}

// 通过 goodscode 查找 商品
export function getGoodsByGoodsCode(goodscode: string) {
    return getGoodsList().find(el => el.goodscode === goodscode)
}

// 通过goodsid 获取商品合约单位
export function getGoodsAgreeunitByGoodsId(goodsid: number): number {
    const result = getGoodsById(goodsid)
    return result ? result.agreeunit : 1
}
// 通过goodsid 获取商品合约单位
export function getGoodsAgreeunitByGoodsCode(goodscode: string): number {
    const result = getGoodsByGoodsCode(goodscode)
    return result ? result.agreeunit : 1
}

// 通过 goodsid 查找 trademode
export function findGoodsTradeModeById(goodsid: number) {
    const marketid = getGoodsById(goodsid)!.marketid
    return APP.get('markets').find((el: Market) => el.marketid === marketid).trademode
}

// 获取商品行情列表
export function getGoodsQuoteList(exchangeId?: number): GoodsQuote[] {
    let goodsList: Goods[] = [];
    const goodsGroups = getAllGoodsGroups();

    if (exchangeId) {
        // 根据交易所 id 查找对应的商品组
        const exchangeGoodsGroups = goodsGroups.filter(e => e.exexchangeid === exchangeId).map(el => el.goodsgroupid);
        // 过滤出对应的商品
        goodsList = getGoodsList().filter((e) => e.goodsstatus === 3 && exchangeGoodsGroups.includes(e.goodsgroupid));
    } else {
        goodsList = getGoodsList().filter((e) => [3, 7].includes(e.goodsstatus));
    }

    // 按照 goodscode 字母升序排序
    goodsList = goodsList.sort((a, b) => a.goodscode.localeCompare(b.goodscode));

    return goodsList.map((el) => {
        const item: GoodsQuote = {
            goodsgroupid: el.goodsgroupid,
            goodsid: el.goodsid,
            goodscode: el.goodscode,
            goodsname: el.goodsname,
            decimalplace: el.decimalplace,
            marketid: el.marketid,
            quoteminunit: el.quoteminunit,
            outerdealmode: el.outerdealmode,
            last: 0, // 最新价
            lasttime: '', // 最新时间
            bid: 0,// 买价
            ask: 0, // 卖价
            bidvolume: 0, // 买量
            askvolume: 0, // 卖量
            totalvolume: 0, // 总量
            lastvolume: 0, // 现量
            holdvolume: 0, // 持仓量
            holdincrement: 0, // 日增
            presettle: 0, // 昨结价
            totalturnover: 0, // 金额
            opened: 0, // 开盘
            highest: 0, // 最高
            lowest: 0, // 最低
            limitup: 0,
            limitdown: 0,
            totalbidvolume: 0,
            totalaskvolume: 0,
            settle: 0,
        }
        // 找出已订阅的盘面数据
        const quote = getQuoteDayInfoByCode(el.goodscode);
        if (quote) {
            const refs = toRefs(quote)
            item.last = refs.last; // 最新价
            item.lasttime = refs.lasttime;
            item.bid = refs.bid; // 买价
            item.ask = refs.ask; // 卖价
            item.bidvolume = refs.bidvolume; // 买量
            item.askvolume = refs.askvolume; // 卖量
            item.totalvolume = refs.totalvolume; // 总量
            item.lastvolume = refs.lastvolume; // 现量
            item.holdvolume = refs.holdvolume; // 持仓量
            item.holdincrement = refs.holdincrement; // 日增
            item.presettle = refs.presettle; // 昨结价
            item.totalturnover = refs.totalturnover; // 金额
            item.opened = refs.opened; // 开盘
            item.highest = refs.highest; // 最高
            item.lowest = refs.lowest; // 最低
            item.limitup = refs.limitup;
            item.limitdown = refs.limitdown;
            item.totalbidvolume = refs.totalbidvolume;
            item.totalaskvolume = refs.totalaskvolume;
            item.settle = refs.settle;
        }
        return item;
    })
}

// 通过 goodscode 获取商品小数位
export function getGoodsDecimalplaceByGoodsCode(goodscode: string) {
    const obj = getGoodsByCode(goodscode)
    return obj ? obj.decimalplace : 1
}