import { ref, Ref } from 'vue';
import { Taaccount } from '@/services/go/TaAccount/interface';
import { getTaacountStatus, getPayCurrencyTypeEnumItemName } from '@/common/constants/enumsName';
import { formatAmount } from '@/utils/number';

import { hasSystemParam } from '@/hooks/system';
import { findGoodsCode, useDetail } from '@/views/order/swap_the_order/components/swap_commodity_contract_summary/setup';
import { TradeMode } from '@/common/constants/enumCommon';
import { queryResultLoadingAndInfo } from '@/common/methods/request/resultInfo';
import { queryTableList } from '@/common/setup/table';
import { useHolderprice } from '@/services/bus/holdPosition';
import { getMarketIdsByTradeMode, getMarketTradePropertyByGoodsId } from '@/services/bus/market';
import { getUserAccountType, getUserId } from '@/services/bus/user';
import { AccountListItem } from '@/services/dataCenter/interafce/account';
import { queryTradePosition } from '@/services/go/ermcp/order';
import { QueryTradePositionRsp } from '@/services/go/ermcp/order/interface';
import { queryTradeHolderDetail } from "@/services/go/order";
import { QueryTradeHolderDetailRsp } from "@/services/go/order/interface";
import { queryQuoteGoodsList } from '@/services/go/Tjmd';
import { QueryQuoteGoodsListReq, QueryQuoteGoodsListRsp } from '@/services/go/Tjmd/interface';
import { handleSubcriteQuote } from '@/common/setup/table/tableQuote';
import { formatDecimal } from '@/utils/number';

export function getColumns() {
    const columns = [
        {
            title: '资金账号',
            key: 'accountid',
        },
        {
            title: '币种',
            key: 'currencyid',
            customRender: ({ record }: { record: Taaccount }) => {
                return getPayCurrencyTypeEnumItemName(record.currencyid)
            }
        },
        {
            title: '当前权益',
            key: 'equity',
            customRender: ({ text }: { text: number }) => formatAmount(text)
        },
        {
            title: '可用资金',
            key: 'availableBalance',
            customRender: ({ text }: { text: number }) => formatAmount(text)
        },
        {
            title: '占用资金',
            key: 'usedmargin',
            customRender: ({ text }: { text: number }) => formatAmount(text)
        },
        {
            title: '冻结金额',
            key: 'freezeAmount',
            customRender: ({ text }: { text: number }) => formatAmount(text)
        },
        {
            title: '持仓盈亏',
            key: 'positionProfitAndLoss',
            customRender: ({ text }: { text: number }) => {
                if (text === 0) return 0;
                return handlePriceColor(text, formatAmount(text));
            }
        },
        {
            title: '平仓盈亏',
            key: 'closepl',
            customRender: ({ text }: { text: number }) => formatAmount(text)
        },
        {
            title: '风险率',
            key: 'hazardRatio',
            customRender: ({ text }: { text: number }) => {
                if (text > 0) {
                    return (text * 100).toFixed(2) + '%';
                }
                return 0;
            }
        },
        {
            title: '状态',
            key: 'tradestatus',
            customRender: ({ record }: { record: Taaccount }) => {
                return getTaacountStatus(record.tradestatus)
            }
        },
    ];

    return columns.map(el => {
        return {
            dataIndex: el.key,
            width: 150,
            align: 'center',
            slots: { customRender: el.key, },
            ...el
        }
    })
}

/**
 * 处理显示颜色
 */
function handlePriceColor(value: number, text: string) {
    let className = ''
    if (value > 0) {
        className = 'up-quote-color'
    } else {
        className = 'down-quote-color'
    }
    return <span class={className}>{text}</span>;
}

/**
 * 这是旧的掉期资金账户数据计算------------------------待优化废除，资金计算需要最新持仓数据，因此每次资金变动都要重新请求接口，由于资金变动通知引用的页面太多，会导致大量接口重复请求
 * 期货订单和掉期订单的资金计算有点区别，后期废除需整合到 @/hooks/account/index.ts
 */
export function useHazardRates() {
    const { getDetailProfitloss } = useDetail();
    const positionList = ref<QueryTradePositionRsp[]>([]); // 所有持仓汇总
    const positionDetailList = ref<QueryTradeHolderDetailRsp[]>([]); // 所有持仓明细
    const swapList = ref<QueryQuoteGoodsListRsp[]>([]); // 交割商品

    const getHoldsList = async (loading: Ref<boolean>, tradeMode?: string) => {
        // 获取头寸
        await queryResultLoadingAndInfo(queryTradePosition, loading, tradeMode).then((res) => {
            const goodsSet = new Set<string>();
            positionList.value = res;

            res.forEach((el) => {
                // 商品掉期取参考行情最新价，挂牌点选取自己行情的最新价
                const goodscode = findGoodsCode(el.goodsid, el.goodscode, swapList.value);
                if (goodscode) {
                    goodsSet.add(goodscode);
                }
            });

            //  行情订阅
            const { subscribeAction } = handleSubcriteQuote();
            subscribeAction([...goodsSet]);
        })
        await queryResultLoadingAndInfo(queryTradeHolderDetail, loading, { userid: getUserId() }).then(res => {
            positionDetailList.value = res
        })
    }

    function getSwapList() {
        const { queryTable } = queryTableList<QueryQuoteGoodsListRsp>();
        // 组装 参数
        const marketids = getMarketIdsByTradeMode(TradeMode.DiaoQi)
        const param: QueryQuoteGoodsListReq = {
            usertype: getUserAccountType(),
        }
        if (marketids) {
            param.marketids = marketids
        }
        queryTable(queryQuoteGoodsList, param).then(res => swapList.value = res)
    }

    // 获取报价小数位
    function getDecimalplace() {
        return positionList.value.length > 0 ? positionList.value[0].decimalplace : 2
    }

    // 获取当前资金账号对应的头寸
    function getTaaccountPosition(accountid: number) {
        return positionList.value.filter(e => e.accountid === accountid)
    }

    // 获取持仓明细
    function getTradeHolderDetail(record: QueryTradePositionRsp) {
        const { accountid, trademode, marketid, goodsid, buyorsell } = record;
        return positionDetailList.value.filter((e) => e.accountid === accountid && e.trademode === trademode && e.marketid === marketid && e.goodsid === goodsid && e.buyorsell === buyorsell);
    }

    // 持仓盈亏
    // 浮动盈亏	持仓单：
    // 收益权=(最新价-持仓价)*持仓数量*合约单位*方向(买[1]:卖[-1])(*汇率)
    // 所有权=(最新价*持仓数量*合约单位(*汇率) - 持仓金额)
    function useProfitloss(record: QueryTradePositionRsp) {
        const detailList = getTradeHolderDetail(record);
        const result = detailList.reduce((res, item) => {
            const goodscode = findGoodsCode(item.goodsid, item.goodscode, swapList.value);
            res += Number(getDetailProfitloss(item, goodscode));
            return res;
        }, 0)

        return result.toFixed(record.decimalplace);
    }

    // 汇总资金账号 的 浮动盈亏
    function handleProfitloss({ accountid }: Taaccount, isDecimalPace = true) {
        const decimalplace = getDecimalplace()
        const result = getTaaccountPosition(accountid).reduce((acc: number, current: QueryTradePositionRsp) => {
            const tradeproperty = getMarketTradePropertyByGoodsId(current.goodsid);
            // 资金 只算 收益权
            if (tradeproperty === 1) {
                acc += +useProfitloss(current);
            }
            return acc
        }, 0)
        return isDecimalPace ? result.toFixed(decimalplace) : result
    }

    // 计算 市值
    function handleHoldPrice(accountid: number) {
        return getTaaccountPosition(accountid).reduce((acc: number, current: QueryTradePositionRsp) => {
            const price = useHolderprice(current)
            const temp = price === '--' ? 0 : Number(price)
            return acc + temp
        }, 0)
    }

    // 风险净值
    function handleRiskValue(taaccount: Taaccount) {
        const { accountid, currentbalance, otherfreezemargin, outamountfreeze } = taaccount
        // 浮动盈亏
        const profitloss = handleProfitloss(taaccount, false) as number

        // 市值
        const price = hasSystemParam('087', '1') ? handleHoldPrice(accountid) : 0
        // 风险净值	根据系统参数“087 风险净值是否加上市值 - 0:不加 1:加“
        // 0. 风险净值=期末余额+浮动盈亏(收益权)-其他冻结-出金冻结
        // 1. 风险净值=期末余额+市值+浮动盈亏(收益权)-其他冻结-出金冻结
        return currentbalance + price + profitloss - otherfreezemargin - outamountfreeze
    }

    // 净值
    // 根据系统参数“307 账户净值是否减冻结资金 - 0:不减 1:减“
    //0.净值=期末余额+市值+浮动盈亏(收益权)
    //1.净值=期末余额+市值+浮动盈亏(收益权)-其他冻结-出金冻结
    function netWorth(taaccount: Taaccount) {
        const { accountid, currentbalance, otherfreezemargin, outamountfreeze } = taaccount
        // 浮动盈亏
        const free = hasSystemParam('037', '1') ? (otherfreezemargin + outamountfreeze) : 0

        const profitloss = handleProfitloss(taaccount, false) as number
        // 市值
        const price = handleHoldPrice(accountid)
        const decimalplace = getDecimalplace()
        return (currentbalance + profitloss + price - free).toFixed(decimalplace)
    }

    // 风险率
    function hazardRates(taaccount: Taaccount) {
        const { usedmargin, mortgagecredit } = taaccount
        // 风险净值
        const riskValue = handleRiskValue(taaccount)
        //   风险率	根据系统参数“132   风险率计算公式”：
        // 1. 风险率=占用/风险净值
        // 2. 风险率=(占用-授信金额)/(风险净值-授信金额)
        const credit = hasSystemParam('132', '1') ? 0 : mortgagecredit
        let result = 0
        if (riskValue && (riskValue - credit)) {
            result = (usedmargin - credit) / (riskValue - credit)
        }
        result = result ? result * 100 : 0
        return formatDecimal(result, 2, false) + '%'
    }

    // 可用资金
    function canUseMoney(taaccount: Taaccount | AccountListItem) {
        const { currentbalance, usedmargin, freezemargin, freezecharge, otherfreezemargin, outamountfreeze } = taaccount

        // 浮动盈亏
        const profitloss = handleProfitloss(taaccount as Taaccount, false) as number
        // 占用+冻结+其它冻结+手续费冻结+出金冻结
        const freeze = usedmargin + freezemargin + freezecharge + otherfreezemargin + outamountfreeze
        let result = 0
        if (profitloss < 0) {
            // 账户总浮动盈亏为负：= 期末余额+总浮动盈亏-占用-冻结-其它冻结-手续费冻结-出金冻结
            result = currentbalance + profitloss - freeze
        } else {
            // *系统参数”113“（当日浮动盈利是否可用） 0:不可用 1:可用
            const isUse = hasSystemParam('113', '1')
            if (isUse) {
                // 账户总浮动盈亏为正 且 113 = 1 ：=期末余额+总浮动盈亏-占用-冻结-其它冻结-手续费冻结-出金冻结
                result = currentbalance + profitloss - freeze
            } else {
                // 账户总浮动盈亏为正 且 113 = 0 ：=期末余额-占用-冻结-其它冻结-手续费冻结-出金冻结
                result = currentbalance - freeze
            }
        }
        const decimalplace = getDecimalplace()
        return Number(result.toFixed(decimalplace))
    }

    return {
        positionList,
        swapList,
        useProfitloss,
        handleProfitloss,
        getTradeHolderDetail,
        getSwapList,
        hazardRates,
        netWorth,
        canUseMoney,
        getHoldsList,
        handleHoldPrice
    }
}