import { Empty, Form, message, Modal, Typography } from 'antd';
import _ from 'lodash';
import { useContext, useMemo } from 'react';
import { useIntl } from 'umi';
import CityModal from '../../CityModal';
import CustomTree from '../../CustomTree';
import { relationFeatureCityRemove, relationUserFeatureRemove } from '../api';
import { DetailContext } from '../detail';
import { createCancelInterceptor, dealTreeData } from '../util';

export interface FeatureTabProps {
  filterFeatureTreeData: any;
  featureCityIds?: any[];
  oldFeatureCityIds: any[];
  featureTree: any;
  detailRefresh: () => void;
  ftdRefresh: () => void;
}

const FeatureTab = (props: FeatureTabProps) => {
  const {
    filterFeatureTreeData,
    featureCityIds,
    oldFeatureCityIds,
    featureTree,
    detailRefresh,
    ftdRefresh,
  } = props;

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

  const { formatMessage } = useIntl();

  const featureList = useMemo(() => {
    return dealTreeData(featureTree)
      ?.filter((item: any) => {
        if (useType == 'operation') {
          return false; // 运营端不进行已绑定过滤
        }
        return item.isBind && (!item.expiredAt || item.expiredAt * 1000 >= new Date().getTime());
      })
      ?.map((item: any) => `${item.id}`);
  }, [featureTree, useType]);

  return filterFeatureTreeData?.length ? (
    <Form.Item name={'features'}>
      <CustomTree
        type={'feature'}
        treeData={filterFeatureTreeData}
        isAllowApply={true}
        isHaveDay={useType !== 'operation'}
        appId={appId}
        isOtherUser={type === 2}
        fixedIds={featureList}
        customRender={(name, item) => {
          return (
            <>
              {name}&nbsp;
              {/* 功能权限绑定城市权限，单个申请暂时隐藏  */}
              {useType !== 'single' && item.isReport === 1 && item.type === 3 && (
                <CityModal
                  onFinish={(values) => {
                    const { cityIds } = values;
                    setFeatureCityIds?.((prev) => {
                      const newFeatureCityIds = [...(prev || [])];
                      const index = newFeatureCityIds.findIndex(
                        (element) => element.featureId === item.id,
                      );
                      if (index !== -1) {
                        newFeatureCityIds[index].cityIds = cityIds;
                      } else {
                        newFeatureCityIds.push({
                          featureId: item.id,
                          cityIds,
                        });
                      }
                      return newFeatureCityIds;
                    });
                  }}
                  cityIds={(
                    featureCityIds?.find((element) => element.featureId === item.id)?.cityIds || []
                  ).map((id: any) => String(id))}
                  cancelCityCreator={
                    useType !== 'operation' && type === 1
                      ? (cancelIds: string[], checked: boolean) => {
                          return new Promise<boolean>((resolve) => {
                            if (checked) {
                              resolve(false);
                              return;
                            }
                            const cityIds =
                              oldFeatureCityIds?.find((ele) => ele.featureId === item.id)
                                ?.cityIds || [];
                            const deleteIds = cancelIds
                              .map((deleteId) => Number(deleteId))
                              .filter((id) => cityIds.includes(id));
                            if (!_.isEmpty(deleteIds)) {
                              Modal.confirm({
                                title: formatMessage({
                                  id: 'component.ApplyDetail.detail.cancel.tips',
                                }),
                                async onOk() {
                                  try {
                                    await relationFeatureCityRemove({
                                      data: [
                                        {
                                          appId,
                                          account: currentUser?.account,
                                          featureId: item?.id,
                                          cityIds: deleteIds,
                                          userId: currentUser?.id,
                                        },
                                      ],
                                    });
                                    detailRefresh?.();
                                    message.success(
                                      formatMessage({
                                        id: 'component.ApplyDetail.detail.cancel.success',
                                      }),
                                    );
                                    resolve(false);
                                  } catch (e) {
                                    resolve(true);
                                  }
                                },
                                onCancel() {
                                  resolve(true);
                                },
                              });
                            } else {
                              resolve(false);
                            }
                          });
                        }
                      : undefined
                  }
                />
              )}
              {useType === 'single' && type === 1 && featureList?.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 featureList.includes(String(node?.id));
                  },
                  request() {
                    return relationUserFeatureRemove({
                      data: [{ appId, userId: currentUser?.id, featureId: node?.id }],
                    });
                  },
                  refresh: () => {
                    detailRefresh?.();
                    ftdRefresh?.();
                  },
                });
              }
            : undefined
        }
      />
    </Form.Item>
  ) : (
    <Empty
      style={{ marginTop: '23%' }}
      description={formatMessage({
        id: 'base.common.feature.no.permission',
        defaultMessage: '没有功能权限',
      })}
    />
  );
};

export default FeatureTab;
