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

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

  const renderTigger = (): React.ReactNode | null => {
    if (children) {
      return children;
    }
    return (
      <a>
        <FormattedMessage id={`pages.funcList.${comType}`} defaultMessage="权限" />
      </a>
    );
  };

  return (
    <DrawerForm
      drawerProps={{
        destroyOnClose: true,
        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) => {
        try {
          await updateFn(values?.data?.data, list, (item: number, map: {}) => ({
            [`${comType}Id`]: item,
            appId,
            [`${type}Id`]: id,
            flagId,
            expiredAt: isHaveDate
              ? Math.round(map?.[item]?.expiredAt / 1000) || undefined
              : undefined,
          }));
          message.success(formatMessage({ id: 'component.bind.success' }));
          refresh?.();
        } catch (error) {}
        return true;
      }}
    >
      <Spin spinning={loading}>
        <Form.Item name="data">
          <CustomCheckboxGroup options={allData} isHaveDate={isHaveDate} oldData={list} />
        </Form.Item>
      </Spin>
    </DrawerForm>
  );
};
export default memo(BindRole);
