import { Form, type FormProps } from 'antd';
import { forwardRef, useEffect, useImperativeHandle } from 'react';
import { Fragment } from 'react/jsx-runtime';
import TabSwitch, { OptionsDto } from '../TabSwitch';
interface SearchFormProps {
  initSearch?: boolean;//默认查询
  handleSearchForm: (values: any) => void; //搜索
  onFinish?: FormProps['onFinish'];
  onFinishFailed?: FormProps['onFinishFailed'];
  layout?: FormProps['layout'];
  className?: any;
  formItemLayout: {
    type?: 'system' | 'customTabSwitch';
    name: string;
    label?: string;
    initialValue?: any; //初始值
    children?: React.ReactNode;
    hidden?: boolean;
    customtabconfig?: {
      isCount?: boolean; //是否计数
      options?: OptionsDto[]; //数据源  //目前仅用于customTabSwitch
    };
  }[];
}
export type SearchFormMethodRef = {
  /** 提供修改表单值的方法 */
  set: (key: string, value: any) => void;
};
interface CustomTabSwitchProps {
  id?: string; //name名称，唯一值
  value?: number | string; //默认值
  onChange?: (value: number | string) => void;
  options: OptionsDto[]; //数据源
  isCount?: boolean;
}

//自定义封装的CustomTabSwitch切换,绑定到Form.Item
/**
 *  
  自定义或第三方的表单控件，也可以与 Form 组件一起使用。只要该组件遵循以下的约定：
  提供受控属性 value 或其它与 valuePropName 的值同名的属性。
  提供 onChange 事件或 trigger 的值同名的事件。 
 * @returns 
 */
const CustomTabSwitch: React.FC<CustomTabSwitchProps> = (props) => {
  const { onChange, options, value, isCount } = props;
  const triggerChange = (changedValue: string | number) => {
    onChange?.(changedValue);
  };
  return (
    <TabSwitch
      isCount={isCount}
      options={options}
      defaultId={value}
      onSelect={(val: any) => {
        triggerChange(val);
      }}
    />
  );
};
const SearchForm = forwardRef<SearchFormMethodRef, SearchFormProps>(
  (props, ref) => {
    const {
      onFinishFailed,
      handleSearchForm,
      formItemLayout,
      className,
      initSearch = true,
      layout = 'inline',
    } = props;
    const [form] = Form.useForm();

    useImperativeHandle(ref, () => ({
      set: (key: string, value: any) => {
        form.setFieldValue(key, value);
      },
    }));
    useEffect(() => {
      if(initSearch) {
        handleSearchForm?.(form.getFieldsValue());
      }
    }, []);
    return (
      <Form
        className={className}
        form={form}
        layout={layout}
        onFieldsChange={() => handleSearchForm?.(form.getFieldsValue())}
        onFinishFailed={onFinishFailed}
      >
        {formItemLayout?.map(
          ({ children, hidden = false, ...itemReset }, index) => (
            <Fragment key={`form_${index}`}>
              {itemReset.type === 'customTabSwitch' ? (
                <Form.Item
                  hidden={hidden}
                  initialValue={itemReset.initialValue}
                  {...itemReset}
                >
                  <CustomTabSwitch
                    isCount={itemReset.customtabconfig?.isCount}
                    options={itemReset.customtabconfig?.options as OptionsDto[]}
                  />
                </Form.Item>
              ) : (
                <Form.Item
                  hidden={hidden}
                  initialValue={itemReset.initialValue}
                  {...itemReset}
                >
                  {children}
                </Form.Item>
              )}
            </Fragment>
          ),
        )}
      </Form>
    );
  },
);

export default SearchForm;
