import { BuyOrSell } from "@/common/constants/enumCommon";
import { validateCommon } from "@/common/setup/validate";
import { RuleObject } from "ant-design-vue/lib/form/interface";
import { onBeforeUnmount, reactive, ref, UnwrapRef } from "vue";
import { FormParam } from "./interface";

const formRef = ref();
const formState: UnwrapRef<FormParam> = reactive({
    accountid: undefined,
    FixedPrice: 0,
    OrderQty: 0,
    PriceMove: 0,
    priceType: 2,
})

function initForm() {
    formState.FixedPrice = 0
    formState.OrderQty = 0
    formState.PriceMove = 0
    formState.priceType = 2
}
export function handleForm() {
    const v_price = async (rule: RuleObject, value: number) => {
        return validateCommon(value, '请输入挂牌价格');
    };
    const rules = {
        FixedPrice: [{ required: true, type: 'number', validator: v_price }],
        OrderQty: [{ required: true, message: '请输入挂牌数量', trigger: 'blur', type: 'number', min: 1 }],
        PriceMove: [{ required: true, message: '请输入点差', trigger: 'blur', type: 'number' }],
        accountid: [{ required: true, message: '请输入交易账号' }],
    }
    onBeforeUnmount(() => {
        initForm()
        formRef.value.resetFields()
    })
    return { rules, formState, formRef }
}

// 是否是浮动价
export function isFloat() { return formState.priceType === 3 }


// 挂牌买卖方向
export function useBuySellDirection() {
    const direction = ref<BuyOrSell>(BuyOrSell.buy)
    function changeDirection() {
        initForm()
        direction.value = direction.value === BuyOrSell.buy ? BuyOrSell.sell : BuyOrSell.buy
    }
    function isBuy() {
        return direction.value === BuyOrSell.buy
    }
    return { direction, changeDirection, isBuy }
}

// 价格
export const usePrice = () => {
    function increasePrice(field: string) {
        formState.FixedPrice++;
        formRef.value?.validateField(field); // 触发字段验证
    }
    function decreasePrice(field: string) {
        if (formState.FixedPrice) {
            formState.FixedPrice--;
        }
        formRef.value?.validateField(field); // 触发字段验证
    }
    return { increasePrice, decreasePrice };
};

export const useNum = (getMaxNum: Function) => {
    function increaseNum(field: string) {
        const max = getMaxNum()
        if (max && formState.OrderQty < max) {
            formState.OrderQty++;
        }
        formRef.value?.validateField(field); // 触发字段验证
    }
    function decreaseNum(field: string) {
        if (formState.OrderQty) {
            formState.OrderQty--;
        }
        formRef.value?.validateField(field); // 触发字段验证
    }
    return { increaseNum, decreaseNum };
}

// 图表
export const useChart = () => {
    const showChart = ref<boolean>(false)
    function showChartAction() {
        showChart.value = !showChart.value
    }
    return { showChart, showChartAction }
}