import type { TagProps } from 'antd';
import { Tag } from 'antd';
import React, { useMemo } from 'react';
import { isHexColor } from '@/utils/color';
import { isArray, isBoolean, isNumber, isString } from '@/utils/common';
import type { DictDataType } from '@/utils/dict';
import { getDictOptions } from '@/utils/dict';

interface DictTagProps {
  type: string;
  value: string | number | boolean | Array<string | number | boolean>;
  // 字符串分隔符 只有当 value 传入值为字符串时有效
  separator?: string;
  // 每个 tag 之间的间隔，默认为 5px
  gutter?: string;
}

const DictTag: React.FC<DictTagProps> = ({
  type,
  value,
  separator = ',',
  gutter = '5px',
}) => {
  const valueArr = useMemo(() => {
    // 1. 是 Number 类型和 Boolean 类型的情况
    if (isNumber(value) || isBoolean(value)) {
      return [String(value)];
    }
    // 2. 是字符串（进一步判断是否有包含分隔符号 -> separator）
    else if (isString(value)) {
      return value.split(separator);
    }
    // 3. 数组
    else if (isArray(value)) {
      return value.map(String);
    }
    return [];
  }, [value, separator]);

  // 解决自定义字典标签值为零时标签不渲染的问题
  if (!type || value === undefined || value === null || value === '') {
    return null;
  }

  const dictOptions = getDictOptions(type);

  return (
    <div
      className="dict-tag"
      style={{
        display: 'inline-flex',
        gap: gutter,
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      {dictOptions
        .filter((dict: DictDataType) => valueArr.includes(String(dict.value)))
        .map((dict: DictDataType) => {
          // 处理 tag 类型
          const colorType: TagProps['color'] = dict.colorType || undefined;

          // if (dict.colorType !== "primary" && dict.colorType !== "default") {
          //   colorType = dict.colorType || undefined;
          // }

          // 处理自定义颜色
          const customColor =
            dict?.cssClass && isHexColor(dict?.cssClass)
              ? dict?.cssClass
              : undefined;

          console.log(customColor, 'customColor');
          console.log(colorType, 'colorType');

          return (
            <Tag
              key={`${dict.value}-${dict.label}`}
              color={customColor || colorType}
              style={{
                ...(customColor ? { color: '#fff' } : {}), // 自定义背景颜色时文字为白色
                margin: 0, // 去除默认 margin，使用 gap 控制间距
              }}
            >
              {dict.label}
            </Tag>
          );
        })}
    </div>
  );
};

export default DictTag;
