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,
    num: 0,
    priceType: 1,
    price: 0,
})

function initForm() {
    formState.num = 0
}
export function handleForm() {
    const v_price = async (rule: RuleObject, value: number) => {
        return validateCommon(value, '请输入限价');
    };

    const rules = {
        num: [{ required: true, message: '请输入挂牌数量', trigger: 'blur', type: 'number', min: 1 }],
        price: [{ required: true, trigger: 'blur', type: 'number', validator: v_price }],
    }
    onBeforeUnmount(() => {
        initForm()
        formRef.value.resetFields()
    })
    return { rules, formState, formRef }
}

// 价格
export const useBlocksPrice = () => {
    const priceCheck = ref<boolean>(false); // 是否可议价
    function increasePrice(field: string) {
        formState.price++;
        formRef.value?.validateField(field); // 触发字段验证
    }
    function decreasePrice(field: string) {
        if (formState.price) {
            formState.price--;
        }
        formRef.value?.validateField(field); // 触发字段验证
    }
    return { priceCheck, increasePrice, decreasePrice };
};

// 数量
export const useBlocksNumber = () => {
    function increaseNumber(field: string) {
        formState.num++;
        formRef.value?.validateField(field); // 触发字段验证
    }
    function decreaseNumber(field: string) {
        if (formState.num) {
            formState.num--;
        }
        formRef.value?.validateField(field); // 触发字段验证
    }
    return { increaseNumber, decreaseNumber };
};