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

interface BindFeatureProps {
  /**
   * @description feature 绑定的类型，目前支持如下两种。
   */
  type: 'user' | 'role'; // 选择类型
  /**
   * @description 绑定的类型的id，如type选了user，就要传入userId。
   */
  id?: number; // 默认参数
  /**
   * @description 是否有有效期。
   */
  isHaveDate?: boolean; // 是否有有效期
  /**
   * @description 可以自定义触发内容，默认是<a>功能</a>
   */
  children?: React.ReactChildren;
  /**
   * @description 绑定的值发生变化刷新
   */
  refresh?: () => void;
}
const BindFeature = ({ type, id, isHaveDate = false, children, refresh }: BindFeatureProps) => {
  const [form] = Form.useForm<{
    data: { data: { id: number; expiredAt: number | undefined | null }[] };
  }>();
  const { formatMessage } = useIntl();
  const dispatch = useDispatch();
  const { featureTreeData, initFetch, loading, list, appId, title, updateFn } = useBindFeature({
    id,
    type,
    isHaveDate,
    form,
  });

  const renderTigger = (): React.ReactNode | null => {
    if (children) {
      return children;
    }
    return (
      <a>
        <FormattedMessage id={'component.bind.feature'} defaultMessage="功能" />
      </a>
    );
  };
  if (!id) {
    return null;
  }
  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 (values) => {
        if (values?.data?.error?.error) {
          message.error(values.data.error.message);
          return;
        }
        try {
          await updateFn(values?.data?.data, list, (item: number, map: {}) => ({
            featureId: item,
            appId,
            [`${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="data">
          <CustomTree
            type="feature"
            oldData={list}
            treeData={featureTreeData}
            isHaveDate={isHaveDate}
            appId={appId}
          />
        </Form.Item>
      </Spin>
    </DrawerForm>
  );
};

export default memo(BindFeature, (prev, next) => {
  return prev.id === next.id;
});
