import { reactive, ref } from 'vue'
import { v4 } from 'uuid'
import { Moment } from 'moment'
import { validateAction } from '@/common/setup/form'
import { requestResultLoadingAndInfo } from '@/common/methods/request/resultInfo'
import { geLoginID_number } from '@/services/bus/login'
import { getAreaUserId } from '@/services/bus/user'
import { HedgedItemAddReq } from '@/services/proto/hedgedItem/interface'
import { hedgedItemAdd } from '@/services/proto/hedgedItem'

export function useForm() {
    const loading = ref<boolean>(false);
    const formElement = ref<HTMLElement>();

    const formData = reactive<HedgedItemAddReq>({
        HedgedItemNum: '', // 被套期项目编号
        HedgedItemName: '', // 项目名称
        HedgedType: undefined, // 套期类型-1:采购计划项目
        PlanStartDate: '', // 计划开始日期
        PlanEndDate: '', // 计划结束日期
        TradeUserID: undefined, // 交易用户ID
        AreaUserID: getAreaUserId(), // 企业ID
        ApplySrc: 2, // 申请来源
        ApplyID: geLoginID_number()!, // 申请人
        SpotContractID: 0, // 现货合同ID
        Qty: 0, // 数量
        ClientTicket: v4() // 客户端流水号
    })

    const rules = {
        HedgedItemNum: [{ required: true, trigger: 'blur', message: '请输入项目编号' }],
        HedgedItemName: [{ required: true, trigger: 'blur', message: '请输入项目名称' }],
        //PlanStartDate: [{ required: true, message: '请选择开始时间' }],
        //PlanEndDate: [{ required: true, message: '请选择结束时间' }],
        HedgedType: [{ required: true, type: 'number', message: '请选择套期类型' }],
        TradeUserID: [{ required: true, type: 'number', message: '请选择套期主体' }],
    }

    // 禁选开始日期
    const disabledStartDate = (startValue: Moment) => {
        if (!startValue || !formData.PlanEndDate) return false;
        return startValue.valueOf() > new Date(formData.PlanEndDate).getTime();
    }

    // 禁选结束日期
    const disabledEndDate = (endValue: Moment) => {
        if (!endValue || !formData.PlanStartDate) return false;
        return new Date(formData.PlanStartDate).getTime() >= endValue.valueOf();
    }

    // 表单提交
    const formSubmit = (callback?: () => void) => {
        validateAction(formElement, formData).then((param) => {
            requestResultLoadingAndInfo(hedgedItemAdd, param, loading, ['新增套期项目成功', '新增套期项目失败：']).then(() => {
                callback && callback();
            }).catch(() => {
                loading.value = false;
            })
        })
    }

    return {
        loading,
        rules,
        formElement,
        formData,
        disabledStartDate,
        disabledEndDate,
        formSubmit,
    }
}