import { DynamicProps } from "@/types/utils";
import { FormItemProp, FormRules } from "element-plus";
import { Arrayable } from "element-plus/es/utils";
import { unref, Ref } from "vue";

// 表单的常用字段类型
export interface FormSchema {
    field: string//后端字段
    component: ComponentType//选择不同输入框
    label: string//标题
    defaultValue?: string | boolean | number//默认值
    labelWidth?: string | number//标签的长度
    options?: Recordable[] | Ref//下拉框数组
    islabel?: boolean//是否显示标签
    width?: number | string//文本框宽度
    minWidth?: number//文本框最小宽度
    required?: boolean | Ref//必须值
    rules?: FormRules[]//表单验证规则
    inline?: boolean//行内表单模式
    type?: string//输入框类型如：number、text，默认text
    filterable?: boolean//下拉框开启搜索
    filterMethod?: Function//自定义下拉框搜索
    clearable?: boolean//是否清除内容
    propsCol?: Recordable//col排版
    multiple?: boolean//是否多选
    disabled?: boolean | Ref//禁止输入
    inputRegex?: Recordable//输入框的正则
    componentProps?: object//继承el组件中的属性
}

export interface BaseFormData {
    schemas: FormSchema[]
    schemasForm: Recordable
    rules: FormRules
}

// 表单常用属性
export interface BaseFormProps extends BaseFormData {
    layout?: 'vertical' | 'inline';
}

// useForm传参类型
// export type FormPropsSchema = Partial<DynamicProps<FormSchema>>[]
export type FormPropsSchema = Partial<DynamicProps<BaseFormProps>>

// 表单内容选择
export type ComponentType =
    | 'Text'
    | 'Input'
    | 'Select'
    | 'Checkbox'
    | 'DatePicker'
    | 'Slot'
    | 'SelectV2'
    | 'Datetime';

// 可选参数类型
export type SchemasForm = Partial<FormSchema>

// useForm表单事件
export interface FormActionType {
    // Partial<FormProps>
    setProps: (formProps: SchemasForm) => Promise<void>// 设置表单内容
    getVaule: () => any// 获取表单内容
    setDefaultValue: (dataSource: Recordable) => void//设置默认字段内容
    getFieldsValue: () => Recordable;
    resetForm: () => void//重置表单内容
    clearValidate: () => void//清除校验
    validateFieldForm: (list: Arrayable<FormItemProp>) => Promise<void>//校验指定字段
}

// useForm注册事件
export type RegisterFn = (formInstance: FormActionType) => void;

// useForm返回的事件
export type UseFormReturnType = [RegisterFn, FormActionType];

// 动态使用挂钩道具
export function getDynamicProps<T extends Record<string, unknown>, U>(props: T): Partial<U> {
    const ret: Recordable = {};
    Object.keys(props).map((key) => {
        ret[key] = unref((props as Recordable)[key]);
    });

    return ret as Partial<U>;
}