import { Empty, Form, Space, Typography } from 'antd';
import { useWatch } from 'antd/lib/form/Form';
import _ from 'lodash';
import { useContext, useEffect, useMemo, useState } from 'react';
import { useIntl } from 'umi';
import BindDataFrom from '../../BindData/BindDataFrom';
import SelectRole from '../../SelectRole';
import { AppDetailContext } from '../../utils/hooks';
import { relationUserOptionRemove } from '../api';
import { DetailContext } from '../detail';
import { createCancelInterceptor, formatOptionList } from '../util';

export interface FlagTabProps {
  flagList?: any[];
  flagData?: any[];
  detailRefresh?: () => void;
  flagRefresh?: () => void;
}

const FlagTab = (props: FlagTabProps) => {
  const { flagList, flagData, detailRefresh, flagRefresh } = props;
  const { formatMessage } = useIntl();
  const [activeKey, setActiveKey] = useState<string[]>([]);
  const { id: appId, useType, type, currentUser, detailData, form } = useContext(DetailContext);
  const { roleApprovalForData } = useContext(AppDetailContext);

  const { flagList: oldFlagList } = detailData || {};
  const optionList = useMemo(() => formatOptionList(oldFlagList, useType), [oldFlagList, useType]);

  const formFlags = useWatch('flags', form);
  const selectFlagIds = useMemo(() => {
    if (!formFlags) return [];
    return _.filter(
      _.flatten(_.map(_.values(formFlags), (v) => v?.data?.map((sv: any) => sv?.id))),
      (v) => _.isString(v),
    );
  }, [formFlags]);

  const showSelectRole = roleApprovalForData === 2 && selectFlagIds.length > 0;
  const showFlag = showSelectRole || flagData?.filter((v) => v.isAllowApply).length;

  useEffect(() => {
    const ks = flagList?.filter((v) => v?.isAllowApply && v.id).map((v) => String(v.id));
    if (ks) setActiveKey(ks);
  }, [flagList]);

  return (
    <>
      {showSelectRole && useType !== 'operation' && (
        <Space style={{ marginBottom: 10 }}>
          <div>
            <Form.Item name={'role'} noStyle>
              <SelectRole appId={appId} />
            </Form.Item>
          </div>
          <label style={{ color: '#F16622' }}>
            {formatMessage({
              id: 'component.ApplyDetail.detail.flags.for.role.name',
              defaultMessage: '（点击按钮，选择数据使用的角色）',
            })}
          </label>
        </Space>
      )}

      {showFlag ? (
        <Form.Item name={'flags'}>
          <BindDataFrom
            isAllowApply
            isHaveDay={useType !== 'operation'}
            isHaveCheckBox={useType === 'operation'}
            activeKey={activeKey}
            setActiveKey={setActiveKey}
            flagList={flagData}
            appId={appId}
            isOtherUser={type === 2}
            fixedIds={optionList}
            customRender={(name, item) => {
              return (
                <>
                  {name}
                  {useType === 'single' && type === 1 && optionList?.includes(String(item.id)) && (
                    <Typography.Text type={'danger'}>
                      {formatMessage({ id: 'base.common.owned' })}
                    </Typography.Text>
                  )}
                </>
              );
            }}
            checkInterceptor={
              useType !== 'operation' && type === 1
                ? (__, info) => {
                    const { checked, node } = info;
                    return createCancelInterceptor({
                      checked,
                      formatMessage,
                      trigger() {
                        return optionList.includes(String(node?.id));
                      },
                      request() {
                        return relationUserOptionRemove({
                          data: [{ appId, userId: currentUser?.id, optionId: node?.id }],
                        });
                      },
                      refresh: () => {
                        detailRefresh?.();
                        flagRefresh?.();
                      },
                    });
                  }
                : undefined
            }
          />
        </Form.Item>
      ) : (
        <Empty
          style={{ marginTop: '23%' }}
          description={formatMessage({
            id: 'base.common.flag.no.permission',
            defaultMessage: '没有数据权限',
          })}
        />
      )}
    </>
  );
};

export default FlagTab;
