/**
 * [FE-MT001] 层级选择器组件
 * 支持商户→部门→店铺三级联动选择
 * AI注意: 此组件用于多租户数据隔离的层级选择
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Cascader,
  TreeSelect,
  Select,
  Space,
  Tag,
  Spin,
  message,
  Typography,
  Card,
  Row,
  Col,
  Button,
} from 'antd';
import {
  ApartmentOutlined,
  ShopOutlined,
  BankOutlined,
  ReloadOutlined,
  DownOutlined,
} from '@ant-design/icons';
import type { DefaultOptionType } from 'antd/es/cascader';
import type { TreeSelectProps } from 'antd';

const { Text } = Typography;
const { Option } = Select;

// 层级类型
export type HierarchyLevel = 'TENANT' | 'DEPARTMENT' | 'SHOP';

// 层级节点
export interface HierarchyNode {
  id: string;
  type: HierarchyLevel;
  parentId: string | null;
  name: string;
  path: string;
  depth: number;
  children?: HierarchyNode[];
  status?: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
  platform?: string;
}

// 选择结果
export interface HierarchySelection {
  tenantId?: string;
  departmentId?: string;
  shopId?: string;
  hierarchyPath?: string;
}

// 组件属性
export interface HierarchySelectorProps {
  mode?: 'cascader' | 'tree' | 'select';
  value?: HierarchySelection;
  onChange?: (selection: HierarchySelection) => void;
  maxLevel?: HierarchyLevel;
  showStatus?: boolean;
  disabled?: boolean;
  placeholder?: string;
  style?: React.CSSProperties;
  className?: string;
  tenantId?: string;
}

// Mock数据
const MOCK_HIERARCHY: HierarchyNode[] = [
  {
    id: 'tenant-001',
    type: 'TENANT',
    parentId: null,
    name: '演示商户',
    path: '/tenant-001',
    depth: 0,
    children: [
      {
        id: 'dept-001',
        type: 'DEPARTMENT',
        parentId: 'tenant-001',
        name: '华东区',
        path: '/tenant-001/dept-001',
        depth: 1,
        children: [
          {
            id: 'shop-001',
            type: 'SHOP',
            parentId: 'dept-001',
            name: '上海旗舰店',
            path: '/tenant-001/dept-001/shop-001',
            depth: 2,
            status: 'ACTIVE',
            platform: 'TikTok',
          },
          {
            id: 'shop-002',
            type: 'SHOP',
            parentId: 'dept-001',
            name: '杭州分店',
            path: '/tenant-001/dept-001/shop-002',
            depth: 2,
            status: 'ACTIVE',
            platform: 'Shopee',
          },
          {
            id: 'shop-003',
            type: 'SHOP',
            parentId: 'dept-001',
            name: '南京店',
            path: '/tenant-001/dept-001/shop-003',
            depth: 2,
            status: 'INACTIVE',
            platform: 'Lazada',
          },
        ],
      },
      {
        id: 'dept-002',
        type: 'DEPARTMENT',
        parentId: 'tenant-001',
        name: '华南区',
        path: '/tenant-001/dept-002',
        depth: 1,
        children: [
          {
            id: 'shop-004',
            type: 'SHOP',
            parentId: 'dept-002',
            name: '广州店',
            path: '/tenant-001/dept-002/shop-004',
            depth: 2,
            status: 'ACTIVE',
            platform: 'TikTok',
          },
          {
            id: 'shop-005',
            type: 'SHOP',
            parentId: 'dept-002',
            name: '深圳店',
            path: '/tenant-001/dept-002/shop-005',
            depth: 2,
            status: 'ACTIVE',
            platform: 'Shopee',
          },
        ],
      },
      {
        id: 'dept-003',
        type: 'DEPARTMENT',
        parentId: 'tenant-001',
        name: '华北区',
        path: '/tenant-001/dept-003',
        depth: 1,
        children: [
          {
            id: 'shop-006',
            type: 'SHOP',
            parentId: 'dept-003',
            name: '北京店',
            path: '/tenant-001/dept-003/shop-006',
            depth: 2,
            status: 'ACTIVE',
            platform: 'TikTok',
          },
        ],
      },
    ],
  },
];

// 平台颜色映射
const PLATFORM_COLORS: Record<string, string> = {
  TikTok: 'pink',
  Shopee: 'orange',
  Lazada: 'blue',
  Amazon: 'cyan',
  eBay: 'yellow',
  AliExpress: 'red',
};

const HierarchySelector: React.FC<HierarchySelectorProps> = ({
  mode = 'cascader',
  value,
  onChange,
  maxLevel = 'SHOP',
  showStatus = true,
  disabled = false,
  placeholder = '请选择层级',
  style,
  className,
  tenantId,
}) => {
  const [loading, setLoading] = useState(false);
  const [hierarchyData, setHierarchyData] = useState<HierarchyNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 加载层级数据
  const loadHierarchyData = useCallback(async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setHierarchyData(MOCK_HIERARCHY);
      
      if (value) {
        const keys: string[] = [];
        if (value.tenantId) keys.push(value.tenantId);
        if (value.departmentId) keys.push(value.departmentId);
        if (value.shopId) keys.push(value.shopId);
        setSelectedKeys(keys);
        setExpandedKeys(keys.slice(0, -1));
      }
    } catch (error) {
      message.error('加载层级数据失败');
    } finally {
      setLoading(false);
    }
  }, [value]);

  useEffect(() => {
    loadHierarchyData();
  }, [loadHierarchyData]);

  // 转换为Cascader选项
  const convertToCascaderOptions = (nodes: HierarchyNode[]): DefaultOptionType[] => {
    return nodes.map(node => ({
      value: node.id,
      label: (
        <Space>
          {node.type === 'TENANT' && <BankOutlined />}
          {node.type === 'DEPARTMENT' && <ApartmentOutlined />}
          {node.type === 'SHOP' && <ShopOutlined />}
          <span>{node.name}</span>
          {showStatus && node.status && (
            <Tag color={node.status === 'ACTIVE' ? 'success' : 'default'}>
              {node.status === 'ACTIVE' ? '正常' : '停用'}
            </Tag>
          )}
          {node.platform && (
            <Tag color={PLATFORM_COLORS[node.platform] || 'default'}>
              {node.platform}
            </Tag>
          )}
        </Space>
      ),
      children: node.children ? convertToCascaderOptions(node.children) : undefined,
      disabled: node.type === 'SHOP' && node.status !== 'ACTIVE',
    }));
  };

  // 转换为TreeSelect选项
  const convertToTreeData = (nodes: HierarchyNode[]): TreeSelectProps['treeData'] => {
    return nodes.map(node => ({
      key: node.id,
      value: node.id,
      title: (
        <Space>
          {node.type === 'TENANT' && <BankOutlined />}
          {node.type === 'DEPARTMENT' && <ApartmentOutlined />}
          {node.type === 'SHOP' && <ShopOutlined />}
          <span>{node.name}</span>
          {showStatus && node.status && (
            <Tag color={node.status === 'ACTIVE' ? 'success' : 'default'}>
              {node.status === 'ACTIVE' ? '正常' : '停用'}
            </Tag>
          )}
          {node.platform && (
            <Tag color={PLATFORM_COLORS[node.platform] || 'default'}>
              {node.platform}
            </Tag>
          )}
        </Space>
      ),
      children: node.children ? convertToTreeData(node.children) : undefined,
      disabled: node.type === 'SHOP' && node.status !== 'ACTIVE',
      selectable: maxLevel === 'TENANT' && node.type === 'TENANT' ||
        maxLevel === 'DEPARTMENT' && (node.type === 'TENANT' || node.type === 'DEPARTMENT') ||
        maxLevel === 'SHOP',
    }));
  };

  // 处理Cascader选择
  const handleCascaderChange = (selectedPath: string[]) => {
    setSelectedKeys(selectedPath);
    
    const selection: HierarchySelection = {
      hierarchyPath: selectedPath.join('/'),
    };

    selectedPath.forEach((id, index) => {
      if (index === 0) selection.tenantId = id;
      else if (index === 1) selection.departmentId = id;
      else if (index === 2) selection.shopId = id;
    });

    onChange?.(selection);
  };

  // 处理TreeSelect选择
  const handleTreeSelect = (selectedValue: string) => {
    const path = findNodePath(hierarchyData, selectedValue);
    if (path) {
      handleCascaderChange(path);
    }
  };

  // 查找节点路径
  const findNodePath = (
    nodes: HierarchyNode[],
    targetId: string,
    currentPath: string[] = []
  ): string[] | null => {
    for (const node of nodes) {
      const newPath = [...currentPath, node.id];
      if (node.id === targetId) {
        return newPath;
      }
      if (node.children) {
        const result = findNodePath(node.children, targetId, newPath);
        if (result) return result;
      }
    }
    return null;
  };

  // 获取当前选择显示
  const getDisplayValue = (): string => {
    if (!selectedKeys.length) return '';
    
    const names: string[] = [];
    let currentNodes = hierarchyData;
    
    for (const key of selectedKeys) {
      const node = currentNodes.find(n => n.id === key);
      if (node) {
        names.push(node.name);
        currentNodes = node.children || [];
      }
    }
    
    return names.join(' / ');
  };

  if (loading) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <Spin tip="加载层级数据..." />
      </div>
    );
  }

  // 级联选择器模式
  if (mode === 'cascader') {
    return (
      <Space.Compact style={{ width: '100%', ...style }} className={className}>
        <Cascader
          style={{ flex: 1 }}
          options={convertToCascaderOptions(hierarchyData)}
          value={selectedKeys}
          onChange={handleCascaderChange as any}
          placeholder={placeholder}
          disabled={disabled}
          showSearch
          expandTrigger="hover"
          changeOnSelect={maxLevel !== 'SHOP'}
          suffixIcon={<DownOutlined />}
        />
        <Button
          icon={<ReloadOutlined />}
          onClick={loadHierarchyData}
          disabled={disabled}
        />
      </Space.Compact>
    );
  }

  // 树选择器模式
  if (mode === 'tree') {
    return (
      <Space.Compact style={{ width: '100%', ...style }} className={className}>
        <TreeSelect
          style={{ flex: 1 }}
          treeData={convertToTreeData(hierarchyData)}
          value={selectedKeys[selectedKeys.length - 1]}
          onChange={handleTreeSelect}
          placeholder={placeholder}
          disabled={disabled}
          showSearch
          treeExpandedKeys={expandedKeys}
          onTreeExpand={setExpandedKeys}
          treeNodeFilterProp="title"
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        />
        <Button
          icon={<ReloadOutlined />}
          onClick={loadHierarchyData}
          disabled={disabled}
        />
      </Space.Compact>
    );
  }

  // 分离选择器模式
  return (
    <Card size="small" style={style} className={className}>
      <Row gutter={[8, 8]}>
        <Col span={24}>
          <Text type="secondary">商户</Text>
          <Select
            style={{ width: '100%' }}
            value={selectedKeys[0]}
            onChange={(tenantId) => handleCascaderChange([tenantId])}
            placeholder="选择商户"
            disabled={disabled}
          >
            {hierarchyData.map(node => (
              <Option key={node.id} value={node.id}>
                <Space>
                  <BankOutlined />
                  {node.name}
                </Space>
              </Option>
            ))}
          </Select>
        </Col>

        {(maxLevel === 'DEPARTMENT' || maxLevel === 'SHOP') && selectedKeys[0] && (
          <Col span={24}>
            <Text type="secondary">部门</Text>
            <Select
              style={{ width: '100%' }}
              value={selectedKeys[1]}
              onChange={(deptId) => handleCascaderChange([selectedKeys[0], deptId])}
              placeholder="选择部门"
              disabled={disabled || !selectedKeys[0]}
              allowClear
            >
              {hierarchyData
                .find(n => n.id === selectedKeys[0])
                ?.children?.map(node => (
                  <Option key={node.id} value={node.id}>
                    <Space>
                      <ApartmentOutlined />
                      {node.name}
                    </Space>
                  </Option>
                ))}
            </Select>
          </Col>
        )}

        {maxLevel === 'SHOP' && selectedKeys[1] && (
          <Col span={24}>
            <Text type="secondary">店铺</Text>
            <Select
              style={{ width: '100%' }}
              value={selectedKeys[2]}
              onChange={(shopId) => handleCascaderChange([selectedKeys[0], selectedKeys[1], shopId])}
              placeholder="选择店铺"
              disabled={disabled || !selectedKeys[1]}
              allowClear
            >
              {hierarchyData
                .find(n => n.id === selectedKeys[0])
                ?.children?.find(n => n.id === selectedKeys[1])
                ?.children?.map(node => (
                  <Option 
                    key={node.id} 
                    value={node.id}
                    disabled={node.status !== 'ACTIVE'}
                  >
                    <Space>
                      <ShopOutlined />
                      {node.name}
                      {node.platform && (
                        <Tag color={PLATFORM_COLORS[node.platform] || 'default'}>
                          {node.platform}
                        </Tag>
                      )}
                      {showStatus && node.status && (
                        <Tag color={node.status === 'ACTIVE' ? 'success' : 'default'}>
                          {node.status === 'ACTIVE' ? '正常' : '停用'}
                        </Tag>
                      )}
                    </Space>
                  </Option>
                ))}
            </Select>
          </Col>
        )}

        <Col span={24}>
          <Button
            icon={<ReloadOutlined />}
            onClick={loadHierarchyData}
            disabled={disabled}
            size="small"
          >
            刷新
          </Button>
        </Col>
      </Row>
    </Card>
  );
};

export default HierarchySelector;
