/**
 * @name 组织机构管理
 */
import React, { useState, useMemo, forwardRef, useImperativeHandle } from 'react';
import { Card, Tree, Input, Empty, theme, Button, Space, Layout } from 'antd';
import { SearchOutlined, SyncOutlined } from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { AxureProps, AxureHandle } from '../../common/axure-types';
import { MENU_ITEMS, resolveMenuTarget } from '../../common/menu';
import SideMenu from '../../components/side-menu';

const { Search } = Input;

// Mock Data
const defaultDepartments: DataNode[] = [
  {
    key: '1',
    title: '腾讯科技 (深圳) 有限公司',
    children: [
      {
        key: '1-1',
        title: '平台与内容事业群 (PCG)',
        children: [
          { key: '1-1-1', title: '技术中台' },
          { key: '1-1-2', title: '内容业务线' },
          { key: '1-1-3', title: '社交平台部' },
        ],
      },
      {
        key: '1-2',
        title: '云与智慧产业事业群 (CSIG)',
        children: [
          { key: '1-2-1', title: '云产品部' },
          { key: '1-2-2', title: '智慧行业部' },
          { key: '1-2-3', title: '安全平台部' },
        ],
      },
      {
        key: '1-3',
        title: '互动娱乐事业群 (IEG)',
        children: [
            { key: '1-3-1', title: '天美工作室群' },
            { key: '1-3-2', title: '光子工作室群' },
            { key: '1-3-3', title: '魔方工作室群' },
        ]
      },
      {
          key: '1-4',
          title: '企业发展事业群 (CDG)',
          children: [
              { key: '1-4-1', title: '战略发展部' },
              { key: '1-4-2', title: '投资并购部' },
          ]
      }
    ],
  },
];

const Component = forwardRef<AxureHandle, AxureProps>((props, ref) => {
  const { data, onEvent } = props;
  const [searchValue, setSearchValue] = useState('');
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['1', '1-1', '1-2']);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const { token } = theme.useToken();

  const handleMenuSelect = React.useCallback((key: string) => {
    const target = resolveMenuTarget(key);
    if (target) {
      window.location.href = target;
    }
  }, []);

  const departments = (data?.departments as DataNode[]) || defaultDepartments;

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  // Flatten the tree for easier search
  const dataList: { key: React.Key; title: string; parentKey?: React.Key }[] = [];
  const generateList = (data: DataNode[], parentKey?: React.Key) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title: title as string, parentKey });
      if (node.children) {
        generateList(node.children, key);
      }
    }
  };
  generateList(departments);

  const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey!;
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, departments);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
      
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const loop = (data: DataNode[]): DataNode[] =>
    data.map((item) => {
      const strTitle = item.title as string;
      const index = strTitle.indexOf(searchValue);
      const beforeStr = strTitle.substring(0, index);
      const afterStr = strTitle.slice(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: token.colorError }}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{strTitle}</span>
        );
      if (item.children) {
        return { title, key: item.key, children: loop(item.children) };
      }

      return {
        title,
        key: item.key,
      };
    });

  const onSelect = (keys: React.Key[], info: any) => {
      setSelectedKeys(keys);
      if (onEvent && keys.length > 0) {
          onEvent('onDepartmentSelect', { department: info.node });
      }
  };

  useImperativeHandle(ref, () => ({
      eventList: [
        { name: 'onDepartmentSelect', desc: '选择部门时触发' },
        { name: 'onSync', desc: '点击同步按钮时触发' }
      ],
      actionList: [{ name: 'refreshData', desc: '刷新数据' }],
      varList: [{ name: 'selectedDepartment', desc: '当前选中的部门' }],
      configList: [{ type: 'input', attributeId: 'title', displayName: '页面标题', info: '页面标题', initialValue: '组织架构' }],
      dataList: [
          {
              name: 'departments',
              desc: '部门树数据',
              keys: [{ name: 'key', desc: 'ID' }, { name: 'title', desc: '名称' }]
          }
      ]
  }));

  return (
    <Layout style={{ minHeight: '100vh' }} hasSider>
      <SideMenu
        title="企微运营"
        width={280}
        defaultSelectedKey="enterprise_org"
        items={MENU_ITEMS}
        onMenuSelect={handleMenuSelect}
      />
      <Layout>
        <div style={{ padding: 24, background: '#f5f7fa', minHeight: '100vh' }}>
      <Card 
        title={<span style={{ fontWeight: 600, fontSize: 16 }}>组织架构</span>} 
        bordered={false} 
        extra={
            <Button 
                type="primary" 
                icon={<SyncOutlined />} 
                onClick={() => onEvent && onEvent('onSync', null)}
            >
                同步组织架构
            </Button>
        }
        bodyStyle={{ minHeight: 600 }}
      >
        <Search
          style={{ marginBottom: 24, maxWidth: 400 }}
          placeholder="请输入部门名称搜索"
          onChange={onChange}
          allowClear
          enterButton
        />
        {departments.length > 0 ? (
           <Tree
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            treeData={loop(departments)}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            showLine={{ showLeafIcon: false }}
            blockNode
            height={500} // Virtual scroll for performance
          />
        ) : (
            <Empty description="暂无组织架构数据" />
        )}
       
      </Card>
        </div>
      </Layout>
    </Layout>
  );
});

export default Component;
