import { getGoodsAgreeunitByGoodsCode, getQuoteDayInfoByCodeFindPrice } from "@/services/bus/goods";
import { getRules } from "@/services/bus/rules";
import { WrMarketTradeConfig } from "@/services/go/wrtrade/interface";
import { CommomTradeForm, ListingTradeNumAndPrice } from './interface';

// 获取交易规则
export function useTradeRule() {
    // 交易规则
    const rules = getRules()
    console.log('rules', rules)
    // 获取履约规则中具体某个值
    // 如果没有找到就默认为0
    function getItemTradeRule(value: keyof WrMarketTradeConfig, initValue = 0) {
        return rules.length ? rules[0][value] : initValue
    }
    // 买保证金模式 1： 比率 2： 固定
    function isRatioInBuyMarginType() {
        const type = getItemTradeRule('buymarginalgorithm', 1)
        return type === 1
    }
    // 卖保证金模式 1： 比率 2： 固定
    function isRationInSellMarginType() {
        const type = getItemTradeRule('sellchargealgorithm', 1)
        return type === 1
    }

    return {
        getItemTradeRule,
        isRatioInBuyMarginType,
        isRationInSellMarginType,
        buymarginvalue: getItemTradeRule('buymarginvalue') as number,
        sellmarginvalue: getItemTradeRule('sellmarginvalue') as number
    }
}


// 买 挂牌/摘牌 固定价 最大数量 = 可用资金/(买方履约保证金比例*挂牌价格)
export function useBuyFixedPricMaxNum<T extends CommomTradeForm>(formState: T, canUseMoney: Function, agreeunit: number) {
    let result = 0
    // 可用资金
    const money = canUseMoney() > 0 ? canUseMoney() : 0
    const { isRatioInBuyMarginType, buymarginvalue } = useTradeRule()

    // 最大数量 = 可用资金/(履约保证金*挂牌价格)
    const marginValue = isRatioInBuyMarginType() ? (buymarginvalue * formState.FixedPrice) : (buymarginvalue + formState.FixedPrice)

    // 处理 0 特殊情况
    if (marginValue) {
        result = Math.round(money / (marginValue * agreeunit))
    }
    return result
}

// 卖 挂牌/摘牌  固定价 最大数量 = 可用资金/(卖方履约保证金比例*挂牌价格)
export function useSellFixedPriceMaxNum<T extends CommomTradeForm>(formState: T, canUseMoney: Function, agreeunit: number) {
    let result = 0
    // 可用资金
    const money = canUseMoney() > 0 ? canUseMoney() : 0
    const { isRationInSellMarginType, sellmarginvalue } = useTradeRule()
    // 最大数量 = 可用资金/(履约保证金*挂牌价格)
    const marginValue = isRationInSellMarginType() ? (sellmarginvalue * formState.FixedPrice) : (sellmarginvalue + formState.FixedPrice)
    if (marginValue) { // 处理 0 特殊情况
        result = Math.round(money / (marginValue * agreeunit))
    }
    return result
}


// 获取浮动价
export function useFloatPrice<T extends CommomTradeForm>(formState: T, goodscode: string) {
    let result = '--'
    if (formState.OrderQty) {
        const goodsPrice = getQuoteDayInfoByCodeFindPrice(goodscode)
        if (goodsPrice && goodsPrice !== '--') {   // 有实时行情价格
            result = ((goodsPrice as number) * formState.OrderQty + formState.PriceMove * formState.OrderQty).toFixed(2)
        }
    }
    return result
}

//  浮动价 挂牌/摘牌 金额
export function useFloatPriceMoney<T extends CommomTradeForm>(formState: T, goodscode: string, agreeunit: number) {
    let result = 0
    const goodsPrice = getQuoteDayInfoByCodeFindPrice(goodscode)
    if (goodsPrice && goodsPrice !== '--') {   // 有实时行情价格
        // 估算总价=挂牌基差+期货合约价；
        const predictTotal = formState.PriceMove + (goodsPrice as number);
        // 估算总额=估算总价*摘牌数量；
        result = predictTotal * formState.OrderQty * agreeunit
    }
    return result
}

// 获取 挂牌 的 最大可挂数量，金额，保证金
export function useListingTradeNumAndPrice<T extends CommomTradeForm>({ formState, goodscode, isFloat, canUseMoney }: ListingTradeNumAndPrice<T>) {
    const agreeunit = getGoodsAgreeunitByGoodsCode(goodscode)
    function getMaxNum(value: number, isBuy: boolean) {
        // 可用资金
        const money = canUseMoney() > 0 ? canUseMoney() : 0
        // 挂牌 最大数量=可用资金/(买方履约保证金比例*挂牌价格)
        let result = 0
        if (isFloat()) {
            const price = useFloatPrice<T>(formState, goodscode)
            if (price !== '--') {
                result = money / (Number(price) * value * agreeunit)
            }
        } else {
            result = isBuy ? useBuyFixedPricMaxNum(formState, canUseMoney, agreeunit) : useSellFixedPriceMaxNum(formState, canUseMoney, agreeunit)
        }
        return +result.toFixed(0)
    }

    // 挂买 最大数量
    function getListingBuyMaxNum() {
        const { buymarginvalue } = useTradeRule()
        return getMaxNum(buymarginvalue, true)
    }

    // 挂卖 最大数量
    function getListingSellMaxNum() {
        const { sellmarginvalue } = useTradeRule()
        return getMaxNum(sellmarginvalue, false)
    }

    // 金额
    function getMoney() {
        let result = 0
        if (isFloat()) {
            result = useFloatPriceMoney(formState, goodscode, agreeunit)
        } else {
            // 摘牌金额=挂牌价格*摘牌数量
            result = formState.OrderQty * formState.FixedPrice * agreeunit
        }
        return Number(result.toFixed(2))
    }

    // 挂买 履约保证金
    function getListingBuyMargin() {
        // 浮动价 履约保证金=估算总额*买方履约保证金比例
        // 一口价 履约保证金=挂牌金额*买方履约保证金比例
        const { isRatioInBuyMarginType, buymarginvalue } = useTradeRule()
        const margin = isRatioInBuyMarginType() ? (buymarginvalue * getMoney()) : (buymarginvalue + getMoney())
        return Number((margin).toFixed(2))
    }

    // 挂卖 履约保证金
    function getListingSellMargin() {
        // 浮动价 履约保证金=估算总额*买方履约保证金比例
        // 一口价 履约保证金=挂牌金额*买方履约保证金比例
        const { isRationInSellMarginType, sellmarginvalue } = useTradeRule()
        const margin = isRationInSellMarginType() ? (sellmarginvalue * getMoney()) : (sellmarginvalue + getMoney())
        return Number((margin).toFixed(2))
    }
    function getFloatPrice() {
        useFloatPrice(formState, goodscode)
    }
    return { getFloatPrice, getListingBuyMaxNum, getListingSellMaxNum, getListingBuyMargin, getListingSellMargin, getMoney }
}

// 获取 摘牌 买 比例 的 最大数量
export function useBuyDelistingRatioMaxNum(OrderQty: number, canUseMoney: Function) {
    let result = 0;
    const { buymarginvalue } = useTradeRule()
    const money = canUseMoney() > 0 ? canUseMoney() : 0
    if (money && !isNaN(money)) {
        const num = +(money / buymarginvalue).toFixed(0);
        // 买 最大可摘数量=min{挂牌数量，可用资金/(履约保证金比例)}
        result = Math.min(OrderQty, num);
    }
    return result
}