import { TradeMode } from "@/common/constants/enumCommon";
import APP from '@/services';
import { message } from "ant-design-vue";
import { Marketrun } from "../go/commonMarket/interface";
import { Market } from "../go/useInfo/interface";
import { getGoodsList } from "./goods";

export function getAllMarkets(): Market[] {
    return APP.get('markets')
}

export function getMarketByTradeMode(trademode: TradeMode): Market | undefined {
    return getAllMarkets().find((el: Market) => el.trademode === trademode)
}

// 通过 trademode 获取市场信息列表
export function getMarketsByTradeMode(trademode: TradeMode): Market[] {
    return getAllMarkets().filter((el: Market) => el.trademode === trademode)
}


//  通过 trademode 获取市场ids
export function getMarketIdsByTradeMode(trademode: TradeMode): string {
    const arr = getMarketsByTradeMode(trademode)
    return arr.reduce((str: string, current: Market) => {
        return str ? (str + ',' + current.marketid) : current.marketid.toString()
    }, '')
}

// 获取市场运行信息
export function getMarketRunByTradeMode(trademode: TradeMode): Marketrun | null {
    const marketInfo = getMarketByTradeMode(trademode)
    let result = null
    if (marketInfo) {
        const temp = APP.get('marketRun').find((el: Market) => el.marketid === marketInfo.marketid)
        result = temp ? temp : null;
    }
    return result
}

// 判断市场是否在运行
export function marketIsRun(trademode: TradeMode) {
    const marketInfo = getMarketRunByTradeMode(trademode)
    let result = false
    if (marketInfo) {
        if (marketInfo.runstatus === 2) {
            result = true
        } else {
            message.error(`市场未开市：runstatus${marketInfo.runstatus}`)
            result = false
        }

    } else {
        console.warn(`没有找到trademode${trademode}对应的市场信息`)
    }
    return result
}

// 通过 商品id查找 市场id
export function getMarketByGoodsId(goodsid: number) {
    return getGoodsList().find(e => e.goodsid === goodsid)?.marketid
}
// 通过 商品id查找 市场交易属性
export function getMarketTradePropertyByGoodsId(goodsid: number) {
    let result = null
    const marketid = getMarketByGoodsId(goodsid)
    if (marketid) {
        const temp = getAllMarkets().find(el => el.marketid === marketid)?.tradeproperty
        result = temp ? temp : null
    }
    return result
}