import { DrawerForm } from '@ant-design/pro-form';
import { Form, Spin, message } from 'antd';
import { memo } from 'react';
import { FormattedMessage, useDispatch, useIntl } from 'umi';
import { useBindData } from './hooks';
import BindDataFrom from './BindDataFrom';

interface BindDataProps {
  /**
   * @description flag-options 绑定的类型，目前支持如下两种。
   */
  type: 'user' | 'role'; // 选择类型
  /**
   * @description 绑定的类型的id，如type选了user，就要传入userId。
   */
  id?: number; // 默认参数
  /**
   * @description 是否有有效期。
   */
  isHaveDate?: boolean; // 是否有有效期
  /**
   * @description 可以自定义触发内容，默认是<a>数据</a>
   */
  children?: React.ReactChildren;
  /**
   * @description 绑定的值发生变化刷新
   */
  refresh?: () => void;
}

const BindData = ({ type, id, isHaveDate = false, children, refresh }: BindDataProps) => {
  const { formatMessage } = useIntl();
  const dispatch = useDispatch();
  const [form] = Form.useForm<{ data: string[] }>();
  const {
    initFetch,
    loading,
    flagList,
    getSelectOptions,
    selectMap,
    dataMap,
    updateFn,
    title,
    appId,
    activeKey,
    setActiveKey,
  } = useBindData({ type, id, isHaveDate, form });

  const renderTigger = (): React.ReactNode | null => {
    if (children) {
      return children;
    }
    return (
      <a>
        <FormattedMessage id={'component.bind.data'} defaultMessage="数据" />
      </a>
    );
  };

  return (
    <DrawerForm
      drawerProps={{
        destroyOnClose: false,
        keyboard: false,
        maskClosable: false,
        afterOpenChange: (val) => {
          // 只要打开，就请求值。
          // form.resetFields();
          if (val) {
            initFetch();
            if (isHaveDate) {
              dispatch({
                type: 'public/fetchAppDetail',
                payload: appId,
              });
            }
          }
        },
      }}
      title={title}
      form={form}
      // @ts-ignore
      trigger={renderTigger()}
      onFinish={async (result) => {
        const { values } = result;
        try {
          // 更新绑定的值
          await updateFn(values, dataMap, (item, map) => ({
            appId,
            flagId: map?.[item]?.flagId,
            optionId: item,
            [`${type}Id`]: id,
            expiredAt: isHaveDate
              ? Math.round(map?.[item]?.expiredAt / 1000) || undefined
              : undefined,
          }));
          refresh?.();
          message.success(formatMessage({ id: 'component.bind.success' }));
        } catch (error) {}
        return true;
      }}
    >
      <Spin spinning={loading}>
        <Form.Item name="values">
          <BindDataFrom
            isHaveDate={isHaveDate}
            activeKey={activeKey}
            setActiveKey={setActiveKey}
            selectMap={selectMap}
            flagList={flagList}
            getSelectOptions={getSelectOptions}
          />
        </Form.Item>
      </Spin>
    </DrawerForm>
  );
};

export default memo(BindData);
