import { TradeMode } from '@/common/constants/enumCommon';
import { validateCommon } from '@/common/setup/validate';
import { getGoodsGroupsByTradeMode, getGoodsList, getQuoteDayInfoByCodeFindPrice } from '@/services/bus/goods';
import { getRules } from '@/services/bus/rules';
import { Goods } from "@/services/go/ermcp/goodsInfo/interface";
import { WrPosition } from "@/services/go/wrtrade/interface";
import { RuleObject } from 'ant-design-vue/lib/form/interface';
import { reactive, ref, UnwrapRef } from "vue";
import { ListingForm } from "./interface";

const formState: UnwrapRef<ListingForm> = reactive({
    WRPriceType: 1,
    FixedPrice: 0,
    OrderQty: 0,
    DelistMinQty: 0,
    PriceMove: 1,
    goodsgroupid: undefined,
    goodsid: undefined,
    DeliveryMonth: ''
})
export function handleForm(data: WrPosition) {
    const formRef = ref();

    const v_group = async (rule: RuleObject, value: number) => {
        if (formState.goodsgroupid) {
            return validateCommon(value, '请选择合约');
        } else {
            return Promise.reject('请选择商品')
        }
    };
    const v_num = async (rule: RuleObject, value: number) => {
        if (value) {
            if (value > data.creditenableqty || value < 1) {
                return Promise.reject('提示挂牌数量有误')
            } else {
                return Promise.resolve();
            }
        } else {
            return Promise.reject('请输入挂牌数量')
        }
    };
    const rules = {
        FixedPrice: [{ required: true, message: '请输入挂牌价格', trigger: 'blur', type: 'number', min: 1, }],
        OrderQty: [{ required: true, validator: v_num, trigger: 'blur', type: 'number' }],
        PriceMove: [{ required: true, message: '请输入基差', trigger: 'blur', type: 'number', min: 1 }],
        DelistMinQty: [{ required: true, message: '请输入起摘数量', trigger: 'blur', type: 'number', min: 0, }],
        DeliveryMonth: [{ required: true, message: '请选择交收月', }],
        goodsid: [{ required: true, validator: v_group }],

    }
    return { rules, formState, formRef }
}

const goodsList = ref<Goods[]>([])
export function handleGoods() {
    const goodsGroup = getGoodsGroupsByTradeMode(TradeMode.quote99);
    const allGoods = getGoodsList()
    function groupsChange(id: number) {
        goodsList.value = allGoods.filter(e => e.goodsgroupid === id)
    }
    function findGoodsCode(id: number) {
        return allGoods.find(e => e.goodsid === id)?.goodscode
    }
    return { goodsGroup, goodsList, groupsChange, findGoodsCode }
}


export function handleNumAndPrice() {
    function isFloat() {
        return formState.WRPriceType === 2;
    }
    // 获取选中的资金账号
    const hasRules = () => getRules().length > 0
    //  摘牌金额
    function getMoney() {
        let result = 0
        if (isFloat()) {
            if (hasRules()) {
                const goodsCode = goodsList.value.find(e => e.goodsid === formState.goodsid)?.goodscode as string
                const goodsPrice = getQuoteDayInfoByCodeFindPrice(goodsCode);
                if (goodsPrice && goodsPrice !== '--') {
                    // 浮动价挂牌金额=（基差价格+期货合约最新价）*挂牌数量
                    result = (formState.PriceMove + (goodsPrice as number)) * formState.OrderQty
                }
            }
        } else {
            // 摘牌金额=挂牌价格*摘牌数量
            result = formState.OrderQty * formState.FixedPrice
        }
        return Number(result.toFixed(2))
    }
    // 履约保证金
    function getMargin() {
        if (hasRules()) {
            const { sellmarginvalue2, sellmarginalgorithm } = getRules()[0]
            // 浮动价 履约保证金=估算总额*卖方履约保证金比例
            // 一口价 履约保证金=挂牌金额*卖方履约保证金比例
            const margin = sellmarginalgorithm === 1 ? getMoney() * sellmarginvalue2 : getMoney() + sellmarginvalue2
            return Number(margin.toFixed(2))
        } else {
            return 0
        }

    }
    return { getMoney, getMargin, isFloat }
}