import { BuyOrSell } from "@/common/constants/enumCommon";
import { EnumRouterName } from "@/common/constants/enumRouterName";
import { queryResultLoadingAndInfo } from "@/common/methods/request/resultInfo";
import { getAccountTypeList, getCanUseMoney } from "@/services/bus/account";
import { getRules } from '@/services/bus/rules';
import { AccountListItem } from "@/services/dataCenter/interafce/account";
import { queryHoldLB, queryWrPosition } from '@/services/go/wrtrade';
import { QueryWrPositionReq, WrHoldLB, WrOrderQuote, WrOrderQuoteDetail, WrPosition } from "@/services/go/wrtrade/interface";
import { reactive, Ref, ref, UnwrapRef } from "vue";
import { getGoodsPrice, handleIs } from "../../setup";
import { ListingForm, Wrhold } from "./interface";

export function handleForm(data: WrOrderQuoteDetail) {
    const formRef = ref();
    const formState: UnwrapRef<ListingForm> = reactive({
        accountid: undefined,
        num: 0,
        LadingBillId: '',
    })
    const rules = {
        accountid: [{ required: true, message: '请选择交易账户' }],
        LadingBillId: [{ required: true, message: '请选择现货仓单' }],
        num: [{ required: true, message: '请输入摘牌数量', trigger: 'blur', type: 'number', min: 1, ma: data.orderqty }],

    }
    return { rules, formState, formRef }
}

// 预售仓单汇总
const wrPostion = ref<WrPosition[]>([])
export function getWrPosition(enumName: EnumRouterName, buyOrSell: BuyOrSell, loading: Ref<boolean>) {
    const { isWR, isBuy } = handleIs(enumName, buyOrSell)
    if (isBuy() && !isWR()) {
        const param: QueryWrPositionReq = {
            haswr: 0,
            querytype: 2,
        };
        queryResultLoadingAndInfo(queryWrPosition, loading, param).then(res => {
            wrPostion.value = res;
        })
    }
}

const allWR = ref<WrHoldLB[]>([])
// 处理现货仓单
export function handleSpotWarrant(enumName: EnumRouterName, buyOrSell: BuyOrSell, selectedRow: WrOrderQuote, loading: Ref<boolean>) {
    const { isWR, isBuy } = handleIs(enumName, buyOrSell)
    const wrHoldList = ref<Wrhold[]>([])
    if (isBuy()) {
        if (isWR()) {
            queryResultLoadingAndInfo(queryHoldLB, loading).then(res => {
                allWR.value = res;
                wrHoldList.value = res.filter((e: WrHoldLB) => e.wrfactortypeid === String(selectedRow.wrfactortypeid)).map((e: WrHoldLB) => {
                    const { wrholdeno, enableqty, ladingbillid, enumdicname } = e
                    return { id: ladingbillid, name: `${wrholdeno}（${enableqty}${enumdicname}）` }
                })
            })
        }
    }
    return { wrHoldList }
}

export function handleNumAndMoney(enumName: EnumRouterName, buyOrSell: BuyOrSell, selectedRow: WrOrderQuoteDetail, parantSelectedRow: WrOrderQuote, formState: UnwrapRef<ListingForm>) {
    const { isWR, isBuy, isFloat } = handleIs(enumName, buyOrSell)
    // 资金账号
    const accountList = getAccountTypeList([2]);
    // 获取选中的资金账号
    const getSelectedAccount = () => accountList.find((e) => e.accountid === formState.accountid);
    // 交易规则
    const rules = getRules()
    // 是否有规则
    const hasRule = () => rules.length > 0;
    const { buymarginvalue, buymarginalgorithm } = rules[0]
    //保证金模式 1： 比率 2： 固定
    const marginMethod = () => buymarginalgorithm === 1
    const { fixedprice, orderqty, pricemove } = selectedRow;
    // 获取摘牌最大可摘量
    function getMaxNum() {
        let result = 0;
        if (hasRule()) {
            // 可用资金
            const canUseMoney = Number(getCanUseMoney(getSelectedAccount() as AccountListItem))
            if (!isBuy()) {
                if (isFloat()) {
                    const goodsPrice = getGoodsPrice()
                    // 估算总价=挂牌基差+期货合约价；
                    if (goodsPrice.value && goodsPrice.value !== '--') {   // 有实时行情价格
                        // 估算总价
                        const predictTotal = pricemove + (goodsPrice.value as number);
                        // 买方履约保证金比例*估算总价
                        const marginMoney = marginMethod() ? (buymarginvalue * predictTotal) : (buymarginvalue + predictTotal)
                        // 浮动价 摘买 最大数量=min{可用资金/（买方履约保证金比例*估算总价），挂牌数量}
                        result = Math.min(orderqty, canUseMoney / marginMoney)
                    }
                } else {
                    // 买方履约保证金比例*挂牌价格
                    const marginMoney = marginMethod() ? (buymarginvalue * fixedprice) : (buymarginvalue + fixedprice)
                    //  一口价 摘买 最大数量=min{挂牌数量，可用资金/（买方履约保证金比例*挂牌价格）
                    result = Math.min(orderqty, canUseMoney / marginMoney)
                }
            } else {
                if (isWR()) {
                    if (formState.LadingBillId) {
                        // 现货库存数量
                        const warehouseNum = allWR.value.find((e) => e.ladingbillid === formState.LadingBillId)?.enableqty;
                        // 仓单贸易 一口价/浮动价 摘卖 最大数量=min（现货库存可用数量，挂牌数量），现货库存数量为所选仓单数量
                        if (warehouseNum) {
                            result = Math.min(orderqty, warehouseNum)
                        }
                    }
                } else {
                    // 获取头寸
                    const item = wrPostion.value.find(e => String(e.wrfactortypeid) === String(parantSelectedRow.wrfactortypeid))
                    if (item) {
                        result = item.enalbeqty
                    }
                }
            }
        }
        return Math.floor(result)
    }
    //  摘牌金额
    function getMoney() {
        let result = 0
        if (isFloat()) {
            const goodsPrice = getGoodsPrice()
            if (goodsPrice.value && goodsPrice.value !== '--') {   // 有实时行情价格
                // 估算总价=挂牌基差+期货合约价；
                const predictTotal = pricemove + (goodsPrice.value as number);
                // 估算总额=估算总价*摘牌数量；
                result = predictTotal * formState.num
            }
        } else {
            // 摘牌金额=挂牌价格*摘牌数量
            result = formState.num * fixedprice
        }
        return Number(result.toFixed(2))
    }
    // 履约保证金
    function getMargin() {
        // fixed sell  履约保证金=卖方履约保证金比例*摘牌金额
        // fixed bull  履约保证金=买方履约保证金比例*摘牌金额
        // floor sell  履约保证金=卖方履约保证金比例*估算总额，履约保证金为0则括号内容不显示
        //  floor  buy 履约保证金=买方履约保证金比例*估算总额
        let result = 0
        if (hasRule()) {
            const { buymarginvalue, sellmarginvalue } = rules[0]
            const margin = isBuy() ? sellmarginvalue : buymarginvalue
            result = marginMethod() ? margin * getMoney() : margin + getMoney()
        }
        return Number(result.toFixed(2))
    }
    return { getMaxNum, getMoney, getMargin }
}