import { Empty, Form, Typography } from 'antd';
import { useContext } from 'react';
import { useIntl } from 'umi';
import BindAllPermission from '../../BindAllPermission';
import CustomCheckboxGroup from '../../CustomCheckboxGroup';
import { relationUserRoleRemove } from '../api';
import { DetailContext } from '../detail';
import { createCancelInterceptor } from '../util';

const vanEnv = document.documentElement.dataset.vanEnv || 'stg';

export interface RoleTabProps {
  oldRoleList: any[];
  roleOptions: any[];
  selectedRole: any[];
  detailRefresh?: () => void;
  rlRefresh?: () => void;
}

const RoleTab = (props: RoleTabProps) => {
  const { oldRoleList, roleOptions, selectedRole, detailRefresh, rlRefresh } = props;

  const { id: appId, useType, type, currentUser } = useContext(DetailContext);

  const { formatMessage } = useIntl();

  return roleOptions?.length ? (
    <Form.Item name={'roles'}>
      <CustomCheckboxGroup
        oldData={oldRoleList}
        options={roleOptions}
        isOtherUser={type === 2}
        checkInterceptor={
          useType !== 'operation' && type === 1
            ? (roleId, checked) => {
                return createCancelInterceptor({
                  checked,
                  formatMessage,
                  trigger() {
                    return selectedRole?.find((item) => item.id === Number(roleId));
                  },
                  request() {
                    return relationUserRoleRemove({
                      data: [{ appId, userId: currentUser?.id, roleId: Number(roleId) }],
                    });
                  },
                  refresh: () => {
                    detailRefresh?.();
                    rlRefresh?.();
                  },
                });
              }
            : undefined
        }
        isHaveDay={useType !== 'operation'}
        isAllowApply={true}
        customRender={(d) => (
          <>
            {useType === 'single' &&
              type === 1 &&
              selectedRole?.find((item) => item.id === Number(d.id)) && (
                <Typography.Text type={'danger'} style={{ marginRight: 4 }}>
                  {formatMessage({ id: 'base.common.owned' })}
                </Typography.Text>
              )}
            <BindAllPermission appId={appId} roleId={d.id} roleName={d.name} />
          </>
        )}
        max={
          (vanEnv === 'prod' && appId === 160) ||
          (vanEnv === 'pre' && appId === 4294967315) ||
          (vanEnv === 'stg' && appId === 4294967371)
            ? (selectedRole?.length || 0) + 1
            : 0
        }
      />
    </Form.Item>
  ) : (
    <Empty
      style={{ marginTop: '23%' }}
      description={formatMessage({
        id: 'base.common.role.no.permission',
        defaultMessage: '没有角色权限',
      })}
    />
  );
};

export default RoleTab;
