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

export interface PolicyTabProps {
  policyOptions: any[];
  oldPolicyList: any[];
  selectedPolicy: any[];
  detailRefresh?: () => void;
  plRefresh?: () => void;
}

const PolicyTab = (props: PolicyTabProps) => {
  const { policyOptions, oldPolicyList, selectedPolicy, detailRefresh, plRefresh } = props;

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

  const { formatMessage } = useIntl();

  return policyOptions?.length ? (
    <Form.Item name={'policies'}>
      <CustomCheckboxGroup
        isOtherUser={type === 2}
        options={policyOptions}
        isAllowApply={true}
        isHaveDay={useType !== 'operation'}
        oldData={oldPolicyList}
        customRender={(d) => {
          if (
            useType === 'single' &&
            type === 1 &&
            selectedPolicy?.find((item) => item.id === Number(d.id))
          ) {
            return (
              <Typography.Text type={'danger'}>
                {formatMessage({ id: 'base.common.owned' })}
              </Typography.Text>
            );
          }
          return undefined;
        }}
        checkInterceptor={
          useType !== 'operation' && type === 1
            ? (policyId, checked) => {
                return createCancelInterceptor({
                  checked,
                  formatMessage,
                  trigger() {
                    return selectedPolicy?.find((item) => item.id === Number(policyId));
                  },
                  request() {
                    return relationUserPolicyRemove({
                      data: [{ appId, userId: currentUser?.id, policyId: Number(policyId) }],
                    });
                  },
                  refresh: () => {
                    detailRefresh?.();
                    plRefresh?.();
                  },
                });
              }
            : undefined
        }
      />
    </Form.Item>
  ) : (
    <Empty
      style={{ marginTop: '23%' }}
      description={formatMessage({
        id: 'base.common.policie.no.permission',
        defaultMessage: '没有策略权限',
      })}
    />
  );
};

export default PolicyTab;
