import { ListingMode } from '@/common/constants/enumCommon';
import { EnumRouterName } from "@/common/constants/enumRouterName";
import { validateCommon } from "@/common/setup/validate";
import { useVerifyBeginDelistingNum, useVerifyListingBasis, useVerifyListingNum } from '@/hooks/form/verify';
import { getAccountTypeList, getCanUseMoney } from "@/services/bus/account";
import { getRules } from '@/services/bus/rules';
import { AccountListItem } from "@/services/dataCenter/interafce/account";
import { WrOrderQuote } from "@/services/go/wrtrade/interface";
import { getListingMode } from '@/views/market/market-spot/setup';
import { RuleObject } from "ant-design-vue/lib/form/interface";
import moment from "moment";
import { onBeforeUnmount, reactive, ref, UnwrapRef } from "vue";
import { getGoodsPrice } from "../buy-sell-market/setup";
import { FormParam, TempWrOrderQuoteDetail } from "./interface";

function initFormData(): FormParam {
    return {
        accountid: undefined,
        FixedPrice: 0,
        OrderQty: 0,
        PriceMove: 0,
        DelistMinQty: 0,
        DeliveryMonth: moment(),
        permanceTempName: '',
        permaceTempId: 0,
        marketid: undefined,
    }
}
const formState: UnwrapRef<FormParam> = reactive(initFormData())
export function handleForm(selectedRow: TempWrOrderQuoteDetail) {
    const formRef = ref();
    //
    const { v_num } = useVerifyListingNum<FormParam, 'DelistMinQty'>(formState, 'DelistMinQty', selectedRow.minivalue);
    const { v_basis } = useVerifyListingBasis(selectedRow, 'goodsid');
    const { v_beginDelistingRules, v_beginDelistingNum } = useVerifyBeginDelistingNum(selectedRow.minivalue)
    const v_price = async (rule: RuleObject, value: number) => {
        return validateCommon(value, '请输入挂牌价格');
    };
    const rules = {
        FixedPrice: [{ required: true, validator: v_price, trigger: 'blur', type: 'number', }],
        OrderQty: [{ required: true, validator: v_num, trigger: 'change', type: 'number' }],
        PriceMove: [{ required: true, validator: v_basis, trigger: 'blur', type: 'number', }],
        DelistMinQty: [{ required: true, validator: v_beginDelistingNum, trigger: 'blur', type: 'number', }],
        accountid: [{ required: true, message: '请输入交易账号' }],
    }
    onBeforeUnmount(() => {
        Object.assign(formState, initFormData())
    })
    return { rules, formState, formRef }
}


export function handleNumAndPrice(enumName: EnumRouterName, selectedRow: WrOrderQuote) {
    // 资金账号
    const accountList = getAccountTypeList([2]);
    // 获取选中的资金账号
    const getSelectedAccount = () => accountList.find((e) => e.accountid === formState.accountid);
    // 交易规则
    const rules = getRules()
    const { buymarginvalue, buymarginalgorithm } = rules.length ? rules[0] : { buymarginvalue: 0, buymarginalgorithm: 1 }
    //保证金模式 1： 比率 2： 固定
    const marginMethod = () => buymarginalgorithm === 1
    // 挂牌最大数量
    function getMaxNum() {
        // 可用资金
        const canUseMoney = Number(getCanUseMoney(getSelectedAccount() as AccountListItem))
        // 挂牌最大数量=可用资金/(买方履约保证金比例*挂牌价格)
        let result = 0
        if (getListingMode(ListingMode.float)) {
            const price = getPrice()
            if (price !== '--') {
                result = canUseMoney / (Number(price) * buymarginvalue)
            }
        } else {
            const margin = marginMethod() ? (buymarginvalue * formState.FixedPrice) : (buymarginvalue + formState.FixedPrice)
            if (margin) {
                result = Math.round(canUseMoney / margin)
            }
        }

        if (buymarginvalue !== 0) {
            return +result.toFixed(0)
        } else {
            // 当市场设置的买保证金为0时，不做数量限制
            return 10000
        }

    }
    //  摘牌金额
    function getMoney() {
        let result = 0
        if (formState.OrderQty) {
            if (getListingMode(ListingMode.float)) {
                const goodsPrice = getGoodsPrice()
                if (goodsPrice.value && goodsPrice.value !== '--') {   // 有实时行情价格
                    // 估算总价=挂牌基差+期货合约价；
                    const predictTotal = formState.PriceMove + (goodsPrice.value as number);
                    // 估算总额=估算总价*摘牌数量；
                    result = predictTotal * formState.OrderQty
                }
            } else {
                // 摘牌金额=挂牌价格*摘牌数量
                if (formState.FixedPrice) {
                    result = formState.OrderQty * formState.FixedPrice
                }
            }
        }
        return Number(result.toFixed(2))
    }
    // 履约保证金
    function getMargin() {
        // 浮动价 履约保证金=估算总额*买方履约保证金比例
        // 一口价 履约保证金=挂牌金额*买方履约保证金比例
        const margin = marginMethod() ? (buymarginvalue * getMoney()) : (buymarginvalue + getMoney())
        return Number((margin).toFixed(2))
    }
    function getPrice() {
        let result = '--'
        const goodsPrice = getGoodsPrice()
        if (goodsPrice.value && goodsPrice.value !== '--' && formState.PriceMove !== null) {   // 有实时行情价格
            result = ((goodsPrice.value as number) + formState.PriceMove).toFixed(2)
        }
        return result
    }
    return { getMaxNum, getMoney, getMargin, getPrice }
}