import { TradeMode } from '@/common/constants/enumCommon';
import { validateCommon } from '@/common/setup/validate';
import { handleForm as useForm } from '@/common/setup/warehouse_receipt_trade/listing';
import { useVerifyListingNum, useVerifyListingBasis } from '@/hooks/form/verify';
import { getGoodsGroupsByTradeMode, getIPOGoodsList, getGoodsById, getQuoteDayInfoByCode, 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 moment from 'moment';
import { onBeforeUnmount, reactive, ref, UnwrapRef } from "vue";
import { ListingForm } from "./interface";

function initFormData(): ListingForm {
    return {
        WRPriceType: 1,
        FixedPrice: 0,
        OrderQty: 0,
        DelistMinQty: 0,
        PriceMove: 1,
        goodsgroupid: undefined,
        goodsid: undefined,
        accountid: undefined,
        delistingQty: 0,
        margin: 0,
        DeliveryMonth: moment(),
        vidaliteTime: moment(),
        friends: [],
        permanceTempName: '',
        permaceTempId: 0,
    }
}

const formState: UnwrapRef<ListingForm> = reactive(initFormData())
export function handleForm(data: WrPosition) {
    const { minivalue, creditenableqty } = data
    formState.OrderQty = data.minivalue
    const { rules, formRef } = useForm();

    const v_group = async (rule: RuleObject, value: number) => {
        if (formState.goodsgroupid) {
            return validateCommon(value, '请选择合约');
        } else {
            return Promise.reject('请选择商品')
        }
    };

    const { v_num } = useVerifyListingNum<ListingForm, 'DelistMinQty'>(formState, 'DelistMinQty', minivalue, creditenableqty);
    const { v_basis } = useVerifyListingBasis(formState, 'goodsid');

    const rule = {
        FixedPrice: [{ required: true, message: '请输入挂牌价格', trigger: 'blur', type: 'number', min: 1, }],
        OrderQty: [{ required: true, validator: v_num, trigger: 'blur', type: 'number' }],
        PriceMove: [{ required: true, validator: v_basis, trigger: 'blur', type: 'number', }],
        DelistMinQty: [{ required: true, message: '请输入起摘数量', trigger: 'blur', type: 'number', min: 0, }],
        DeliveryMonth: [{ required: true, message: '请选择交收月', }],
        goodsid: [{ required: true, validator: v_group }],

    }
    Object.assign(rules, rule)
    onBeforeUnmount(() => {
        Object.assign(formState, initFormData())
    })
    return { rules, formState, formRef }
}

const goodsList = ref<Goods[]>([])
export function handleGoods() {
    const goodsGroup = getGoodsGroupsByTradeMode(TradeMode.quote99);
    const allGoods = getIPOGoodsList()
    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;
    }
    function isFixed() {
        return formState.WRPriceType === 1;
    }
    function isBlocs() {
        return formState.WRPriceType === 3;
    }
    // 获取选中的资金账号
    const hasRules = () => getRules().length > 0
    //  摘牌金额
    function getWrMoney() {
        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 getWrMargin() {
        if (hasRules()) {
            const { sellmarginvalue2, sellmarginalgorithm } = getRules()[0]
            // 浮动价 履约保证金=估算总额*卖方履约保证金比例
            // 一口价 履约保证金=挂牌金额*卖方履约保证金比例
            const margin = sellmarginalgorithm === 1 ? getWrMoney() * sellmarginvalue2 : getWrMoney() + sellmarginvalue2
            return Number(margin.toFixed(2))
        } else {
            return 0
        }

    }
    return { getWrMoney, getWrMargin, isFloat, isFixed, isBlocs }
}
