// 获取最新价

import { BuyOrSell, TradeMode } from "@/common/constants/enumCommon";
import { queryResultLoadingAndInfo } from "@/common/methods/request/resultInfo";
import { queryTableList } from "@/common/setup/table";
import { useSetColumns } from "@/hooks/table/columns";
import { ItemColumns } from "@/hooks/table/interface";
import { findGoodsTradeModeById, getQuoteDayInfoByCodeFindPrice } from "@/services/bus/goods";
import { getMarketIdsByTradeMode } from "@/services/bus/market";
import { getUserAccountType, getUserId } from "@/services/bus/user";
import { QueryTradePositionRsp } from "@/services/go/ermcp/order/interface";
import { queryTradeHolderDetail } from "@/services/go/order";
import { QueryTradeHolderDetailReq, QueryTradeHolderDetailRsp } from "@/services/go/order/interface";
import { queryQuoteGoodsList } from "@/services/go/Tjmd";
import { QueryQuoteGoodsListReq, QueryQuoteGoodsListRsp } from "@/services/go/Tjmd/interface";
import { ref } from "vue";

export const useIsDiaoQi = (goodsid: number) => {
    return findGoodsTradeModeById(goodsid) === TradeMode.DiaoQi
}


// 商品掉期取参考行情最新价，挂牌点选取自己行情的最新价
export function findGoodsCode(goodsid: number, goodscode: string, swapList: QueryQuoteGoodsListRsp[]) {
    const result = useIsDiaoQi(goodsid) ? swapList.find((el) => el.goodsid === goodsid)?.refgoodscode : goodscode;
    return result ? result : ''
}

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

export function getTableColums() {
    const list: ItemColumns[] = [
        { key: 'goodsname', title: '订单合约' },
        { key: 'buyorsell', title: '方向' },
        { key: 'curpositionqty', title: '持有数量' },
        { key: 'enableqty', title: '可用数量' },
        { key: 'frozenqty', title: '冻结数量' },
        { key: 'averageprice', title: '均价' },
        { key: 'lastprice', title: '现价' },
        { key: 'curholderamount', title: '持仓金额' },
        // { key: 'marketamount', title: '市值' },
        { key: 'profitloss', title: '浮动盈亏' },
    ]
    return useSetColumns(list)
}

// 明细
export const useDetail = () => {
    // 详情列表数据
    const detailTableList = ref<QueryTradeHolderDetailRsp[]>([])
    // 详情 loading
    const detailLoading = ref<boolean>(false)
    // 获取明细
    function getTradeHolderDetail({ accountid, trademode, marketid, goodsid, buyorsell }: QueryTradePositionRsp) {
        const param: QueryTradeHolderDetailReq = {
            userid: getUserId(),
            accids: accountid.toString(),
            trademodes: trademode.toString(),
            marketids: marketid.toString(),
            goodsid,
            buyorsell,
        }
        queryResultLoadingAndInfo(queryTradeHolderDetail, detailLoading, param).then(res => {
            detailTableList.value = res
        })
    }

    // 表头
    function getDetailColums() {
        const list: ItemColumns[] = [
            { key: 'tradetime', title: '建仓时间', width: 140 },
            { key: 'expiredate', title: '到期日' },
            { key: 'openqty', title: '建仓数量' },
            { key: 'holderqty', title: '可用数量' },
            { key: 'freezeqty', title: '冻结数量' },
            { key: 'openprice', title: '建仓价' },
            { key: 'tradeid', title: '持仓单号', width: 160 },
            { key: 'holderamount', title: '建仓金额' },
            // { key: 'marketamount', title: '市值' },
            { key: 'profitloss', title: '浮动盈亏' },
            { key: 'operate', title: '操作', width: 160 },
        ]
        return useSetColumns(list)
    }

    // 计算 明细列表里 具体一条数据的 市值
    // 市值(所有权) = 数量 * 现价 * 合约单位
    function getDetailMarketAmount(record: QueryTradeHolderDetailRsp) {
        // 最新价
        const lastPrice = getQuoteDayInfoByCodeFindPrice(record.goodscode);
        if (lastPrice !== '--') {
            const { decimalplace, agreeunit, holderqty } = record;
            return (+lastPrice * holderqty * agreeunit).toFixed(decimalplace);
        } else {
            return lastPrice
        }
    }
    // 计算 明细列表里 具体一条数据的 浮动盈亏
    // 持仓盈亏
    // 浮动盈亏	持仓单：
    // 收益权=(最新价-持仓价)*持仓数量*合约单位*方向(买[1]:卖[-1])(*汇率)
    // 所有权=(最新价*持仓数量*合约单位(*汇率) - 持仓金额)
    function getDetailProfitloss(record: QueryTradeHolderDetailRsp, goodscode: string) {
        // 最新价
        const lastPrice = getQuoteDayInfoByCodeFindPrice(goodscode);
        if (lastPrice !== '--') {
            const { holderprice, decimalplace, agreeunit, holderqty, buyorsell } = record;
            const temp = buyorsell === BuyOrSell.buy ? 1 : -1
            const result = ((+lastPrice - holderprice) * holderqty * agreeunit * temp).toFixed(decimalplace);
            return result === '-0' ? '0' : result
        } else {
            return lastPrice;
        }
    }

    return { getTradeHolderDetail, detailLoading, getDetailColums, detailTableList, getDetailProfitloss, getDetailMarketAmount }
}