/**
 * KRA - Authority Select Component
 * Cascader component for selecting user authorities/roles
 */
import React, { useState, useRef } from 'react';
import { Cascader, Tag } from 'antd';

interface AuthorityOption {
  authorityId: string;
  authorityName: string;
  children?: AuthorityOption[];
}

interface AuthoritySelectProps {
  value: string[];
  options: AuthorityOption[];
  onChange: (ids: string[]) => void;
  disabled?: boolean;
}

const AuthoritySelect: React.FC<AuthoritySelectProps> = ({
  value,
  options,
  onChange,
  disabled = false,
}) => {
  const [tempValue, setTempValue] = useState<string[]>([]);
  const isOpenRef = useRef(false);

  // 转换选项为 Cascader 格式
  const convertToCascaderOptions = (opts: AuthorityOption[]): any[] => {
    return opts.map((item) => ({
      value: item.authorityId,
      label: item.authorityName,
      children: item.children ? convertToCascaderOptions(item.children) : undefined,
    }));
  };

  // 处理下拉框显示/隐藏
  const handleVisibleChange = (visible: boolean) => {
    if (visible) {
      // 打开时保存当前值
      setTempValue([...value]);
      isOpenRef.current = true;
    } else if (isOpenRef.current) {
      // 关闭时提交变更
      isOpenRef.current = false;
      if (JSON.stringify(tempValue) !== JSON.stringify(value)) {
        // 值有变化，不需要额外操作，onChange 已经在 Cascader 的 onChange 中处理
      }
    }
  };

  // 处理值变化
  const handleChange = (newValue: any) => {
    // Cascader 返回的是二维数组，需要提取最后一级的值
    const ids = Array.isArray(newValue) 
      ? newValue.map((v: any) => (Array.isArray(v) ? v[v.length - 1] : v))
      : [];
    onChange(ids);
  };

  // 处理标签移除
  const handleRemoveTag = (removedId: string) => {
    const newIds = value.filter((id) => id !== removedId);
    onChange(newIds);
  };

  // 查找角色名称
  const findAuthorityName = (id: string, opts: AuthorityOption[]): string => {
    for (const opt of opts) {
      if (opt.authorityId === id) {
        return opt.authorityName;
      }
      if (opt.children) {
        const found = findAuthorityName(id, opt.children);
        if (found) return found;
      }
    }
    return id;
  };

  // 自定义显示渲染
  const displayRender = (labels: string[]) => {
    return labels[labels.length - 1];
  };

  return (
    <Cascader
      options={convertToCascaderOptions(options)}
      value={value.map((id) => [id])}
      onChange={handleChange}
      onDropdownVisibleChange={handleVisibleChange}
      multiple
      showCheckedStrategy="SHOW_CHILD"
      displayRender={displayRender}
      disabled={disabled}
      style={{ width: '100%' }}
      tagRender={({ label, value: tagValue, closable, onClose }) => (
        <Tag
          color="blue"
          closable={closable && !disabled}
          onClose={(e) => {
            e.preventDefault();
            handleRemoveTag(tagValue as string);
          }}
          style={{ marginRight: 3 }}
        >
          {label}
        </Tag>
      )}
      maxTagCount="responsive"
      placeholder="请选择角色"
    />
  );
};

export default AuthoritySelect;
