import React, { useEffect, useRef, useState } from 'react';
import styles from './style/sideBar.module.less';
import {
  ResizeBox,
  Tree,
  Input,
  Button,
  Modal,
  Form,
  Message,
  Dropdown,
  Menu,
  Popconfirm
} from '@arco-design/web-react';
import { IconApps, IconMore, IconDelete, IconEdit } from '@arco-design/web-react/icon';
import { menuData1, menuData2 } from './config/menuData';
import { IconSearch, IconPlus } from '@arco-design/web-react/icon';
import { Selected } from '@/pages/ideContainer/types';
import { useDispatch, useSelector } from 'react-redux';
import { updateMenuData, updateFlowData, updateCurrentAppData } from '@/store/ideContainer';
import { addApp, getProjectEnv, editApp, deleteApp } from '@/api/apps';
import _ from 'lodash';
import { getAppInfoNew } from '@/api/appRes';

const TreeNode = Tree.Node;
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const MenuItem = Menu.Item;

interface MenuItemType {
  title: string;
  key?: string;
  children?: MenuItemType[];
  path?: string;
  icon?: React.ReactNode;

  [key: string]: string | MenuItemType[] | React.ReactNode;
}

interface SideBarProps {
  subMenuData: any;
  selected?: any;
  identity?: string;
  showSubMenu: boolean;
  onMenuSelect?: (selected: Selected) => void;
  onRefresh: () => void;
  onDeleteApp?: (appId: string) => void; // 添加删除应用的回调函数
}

const compTypeMap = {
  appComponent: '普通组件',
  subComponent: '复合组件'
};


const AppHandleModal = ({ appInfo, visible, type, onChangeVisible, onClose, onRefresh }) => {
  const { info } = useSelector(state => state.ideContainer);
  const [form] = Form.useForm();

  if (type === 'EDIT' && appInfo) {
    form.setFieldsValue({
      id: appInfo?.id,
      name: appInfo?.name,
      description: appInfo?.description,
      published: appInfo?.published === 1,
      logo: 'scene04.png', // 先写死
      sceneId: info.id
    });
  }

  const onOk = async () => {
    await form.validate();
    const formData = form.getFields();

    // 新增
    if (type === 'ADD') {
      // 新增应用的入参
      const params = {
        description: formData.description,
        name: formData.name,
        logo: 'scene04.png', // 先写死
        published: 0,
        sceneId: info.id
      };
      const res: any = await addApp(params);
      if (res.code === 200) Message.success('创建成功');
      else Message.error(res.message);
    }
    // 编辑
    else {
      const res: any = await editApp(formData);
      if (res.code === 200) Message.success('编辑成功');
      else Message.error(res.message);
    }

    // 清空表单数据和其他变量数据
    form.resetFields();
    onRefresh();
    onClose();

  };

  return (
    <Modal
      title={type === 'ADD' ? '新增应用' : '编辑应用'}
      visible={visible}
      onOk={() => onOk()}
      onCancel={() => onChangeVisible(false)}
      autoFocus={false}
      focusLock={true}
      maskClosable={false}
    >
      <Form form={form} autoComplete="off">
        <FormItem
          field="name"
          label="应用名称"
          required
          rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请填写应用名称');
                }
                // 检查是否只包含汉字
                const chineseOnlyRegex = /^[\u4e00-\u9fa5]+$/;
                if (!chineseOnlyRegex.test(value)) {
                  return cb('应用名称只能输入汉字');
                }

                return cb();
              }
            }
          ]}
        >
          <Input placeholder="请输入应用名称" />
        </FormItem>
        <FormItem
          field="description"
          label="应用描述"
          required
          rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请填写应用描述');
                }

                return cb();
              }
            }
          ]}
        >
          {/*<Input placeholder="请输入工程描述" />*/}
          <TextArea placeholder="请输入应用描述" />
        </FormItem>
      </Form>
    </Modal>
  );
};

const SideBar: React.FC<SideBarProps> = ({
                                           selected,
                                           identity,
                                           subMenuData,
                                           showSubMenu,
                                           onMenuSelect,
                                           onRefresh,
                                           onDeleteApp
                                         }) => {
  const [menu, setMenu] = useState<MenuItemType[]>([]);
  const [subMenuWidth, setSubMenuWidth] = useState(300); // 子菜单宽度状态
  const [isSubMenuCollapsed, setIsSubMenuCollapsed] = useState(false); // 子菜单收起状态
  const [activeKey, setActiveKey] = useState(0);
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState<'ADD' | 'EDIT'>('ADD');
  const [currentApp, setCurrentApp] = useState<any>(null);
  const resizeBoxRef = useRef<HTMLDivElement>(null); // 引用第一个 ResizeBox 容器
  const { menuData } = useSelector(state => state.ideContainer);
  const dispatch = useDispatch();

  function getMenuData(): MenuItemType[] {
    switch (identity) {
      case 'scene':
        const menuData = _.cloneDeep(menuData1);
        const newSubMenuData = _.cloneDeep(subMenuData);
        const subMenuKey = Object.keys(newSubMenuData)[0];
        const subMenuValue: any = Object.values(newSubMenuData)[0];
        const menuIndex = menuData.findIndex(v => v.key === subMenuKey);
        // 构建数据结构，这是目录默认需要的数据结构
        subMenuValue.forEach(v => {
          v.title = v.name;
          v.key = `compFlow-${v.id}`;
          v.path = 'compFlow';
          v.parentKey = subMenuKey;
          v.icon = '/ideContainer/icon/app.png';
          v.children = [
            {
              title: '事件',
              children: null,
              icon: '/ideContainer/icon/list.png'
            },
            {
              title: '组件列表',
              children: null,
              icon: '/ideContainer/icon/list.png'
            }
          ];
        });
        menuData[menuIndex]['children'] = subMenuValue;
        dispatch(updateMenuData({ 'scene': menuData }));
        return menuData;
      case 'componentDevelopment' :
        dispatch(updateMenuData({ 'componentDevelopment': menuData2 }));
        return menuData2;
      default:
        return menuData1;
    }
  }

  // 处理子菜单区域的拖拽调整大小
  const handleSubMenuResize = (e: MouseEvent, { width }: { width: number }) => {
    resizeBoxRef.current.style.width = `${width}px`;
  };

  // 切换子菜单区域的收起/展开状态
  const toggleSubMenu = () => {
    setIsSubMenuCollapsed(!isSubMenuCollapsed);
    const width = isSubMenuCollapsed ? 300 : 0;
    resizeBoxRef.current.style.width = `${width}px`;
  };

  // 处理菜单项点击事件
  const handleMenuItemClick = (item: MenuItemType, index: number) => {
    setActiveKey(index);

    if (showSubMenu) {
      // 如果点击的是当前已激活的菜单项，则切换子菜单的展开/收起状态
      if (selected.key === `${item.key}`) {
        toggleSubMenu();
      }
      else {
        // 如果点击的是其他菜单项，则展开子菜单（如果已收起）
        if (isSubMenuCollapsed) {
          setIsSubMenuCollapsed(false);
          resizeBoxRef.current.style.width = `300px`;
        }
      }
    }

    // 调用外部传入的菜单选择处理函数
    onMenuSelect?.({ ...item });
  };

  const getProjectEnvData = async (data) => {
    if (!data.path || !data.key) return;
    const parentKey = menu[activeKey]?.key;
    const currentMenu = _.cloneDeep(menuData[identity]);
    const index = currentMenu.findIndex(v => v.key === parentKey);
    // const res: any = await getProjectEnv(data.id);
    const res: any = await getAppInfoNew(data.id);
    if (res.code === 200) {
      const children = currentMenu[index].children.find(v => v.id === data.id);
      children.children[0].children = res.data.events.map(item => {
        return {
          title: item,
          children: null,
          icon: '/ideContainer/icon/list.png'
        };
      });
      children.children[1].children = Object.keys(res.data.compList).map(item => {
        return {
          title: compTypeMap[item],
          icon: item === 'appComponent' ? '/ideContainer/icon/app1.png' : '/ideContainer/icon/complexApp.png',
          children: res.data.compList[item].map(item => {
            return {
              title: item,
              children: null,
              icon: '/ideContainer/icon/tool.png'
            };
          })
        };
      });

      const findMenuItem = (menuItems: any[], key: string): any => {
        for (const item of menuItems) {
          if (item.key === key) {
            return item;
          }
          if (item.children) {
            const found = findMenuItem(item.children, key);
            if (found) return found;
          }
        }
        return null;
      };


      // 更新 menuData 中的数据
      dispatch(updateMenuData({ ...menuData, [identity]: currentMenu }));
      // 更新 flowData 中的数据
      dispatch(updateFlowData({ [data.id]: res.data }));
      // 更新 currentAppData 中的数据
      dispatch(updateCurrentAppData({ ...findMenuItem(menuData[identity], children.key) }));

      // 同时更新本地 menu 状态以触发重新渲染
      setMenu(prevMenu => {
        const newMenu = [...prevMenu];
        newMenu[activeKey] = { ...newMenu[activeKey], children: currentMenu[index].children };
        return newMenu;
      });
    }
  };

  // 渲染子菜单
  const renderMenuItems = (menuItems?: MenuItemType[], parentKey = '0') => {
    if (menuItems && menuItems.length) {
      return menuItems.map((item, index) => {
        const key = `${parentKey}-${index}`;
        const treeNodeProps = {
          title: item.title,
          key: key,
          dataRef: item // 传递原始数据，包含 path、key 等信息
        };
        if (item.children && item.children.length > 0) {
          return (
            <TreeNode
              {...treeNodeProps}
              title={item.title}
              key={key}
              icon={item?.icon ? <img src={item.icon as string} style={{ width: 14, height: 14 }} /> : null}
            >
              {renderMenuItems(item.children, key)}
            </TreeNode>
          );
        }
        else {
          return (<TreeNode
            {...treeNodeProps}
            title={item.title}
            key={key}
            icon={item?.icon ? <img src={item.icon as string} style={{ width: 14, height: 14 }} /> : null}
          />);
        }
      });
    }
    return null;
  };

  useEffect(() => {
    if (identity === 'scene') Object.keys(subMenuData).length > 0 && setMenu(getMenuData());
    else if (identity === 'componentDevelopment') setMenu(getMenuData());
  }, [subMenuData, identity]);


  // 渲染节点的额外操作按钮
  const renderNodeExtra = (node) => {
    // 只有当 node.dataRef.id 存在时才渲染操作按钮
    if (!node.dataRef?.id) {
      return null;
    }

    const dropList = (
      <Menu>
        <MenuItem
          key="editApp"
          onClick={() => {
            setCurrentApp(node.dataRef);
            setModalType('EDIT');
            setShowModal(true);
          }}
        >
          <span style={{ color: 'rgba(161, 165, 194, 1)' }}>
            <IconEdit style={{ marginRight: 6 }} />
            编辑信息
          </span>
        </MenuItem>
        <MenuItem
          key="deleteApp"
          onClick={() => {
            // 使用Hook方式调用
            Modal.confirm({
              title: '请确认是否删除该应用？',
              content: '应用删除后无法恢复，请谨慎删除！',
              maskClosable: false,
              cancelText: '取消',
              simple: false,
              closable: false,
              onOk: async () => {
                await deleteApp(node.dataRef.id);
                // 通知父组件应用已被删除
                onDeleteApp?.(node.dataRef.id);
                onRefresh();
              }
            });
          }}
        >
          <span style={{ color: 'rgba(255, 82, 25, 1)' }}>
            <IconDelete style={{ marginRight: 6 }} />
            删除应用
          </span>
        </MenuItem>
      </Menu>
    );

    return (
      <Dropdown droplist={dropList} trigger="click">
        <IconMore
          style={{
            position: 'absolute',
            right: 8,
            fontSize: 20,
            fontWeight: 700,
            top: 10,
            color: '#000000'
          }}
        />
      </Dropdown>
    );
  };

  return (
    <div
      className={styles['sider']}
    >
      <div className={styles['menu-container']}>
        {menu.map((item, index) => (
          <div
            key={index}
            className={`${styles['menu-item']} ${(selected.parentKey === `${item.parentKey}`) ? styles['menu-item-active'] : ''}`}
            onClick={() => handleMenuItemClick(item, index)}
          >
            <div className={styles['menu-item-content']}>
              {item.icon &&
                <img src={selected.parentKey === `${item.parentKey}` ? item.activeIcon as string : item.icon as string}
                     style={{ width: 20, height: 20, marginBottom: 7 }} />}
              {!item.icon && (
                <span className={styles['menu-item-icon']}>
                {item.icon || <IconApps />}
              </span>
              )}
              <span className={styles['menu-item-text']}>
                {item.title}
              </span>
            </div>
          </div>
        ))}
      </div>
      {showSubMenu && <ResizeBox
        ref={resizeBoxRef}
        directions={['right']}
        style={{
          width: subMenuWidth,
          height: '100%',
          minHeight: 'calc(100vh - 60px)'
        }}
        onMoving={handleSubMenuResize}
      >
        <div
          className={styles['sub-menu']}
        >
          {/* 搜索/添加 */}
          {menu[activeKey]?.key === 'appList' && <div className={styles['handle-box']}>
            <Input
              prefix={<IconSearch />}
              placeholder={'搜索'}
              style={{ width: '90%' }}
            />
            <Button
              type="primary"
              icon={<IconPlus />}
              style={{ marginLeft: 5 }}
              onClick={() => {
                setShowModal(true);
                setModalType('ADD');
              }}
            />
          </div>}

          {/* 子菜单 */}
          <Tree
            defaultExpandedKeys={['0-0']}
            selectedKeys={[]} // 移除选中样式
            onSelect={async (_selectedKeys, info) => {
              const selectedNode = info.node;
              const originalData = selectedNode.props.dataRef;
              await getProjectEnvData(originalData);

              // 调用外部传入的菜单选择处理函数
              originalData.key && onMenuSelect?.({ ...originalData } as Selected);
            }}
            style={{ background: 'transparent' }} // 移除背景色
            renderExtra={renderNodeExtra}
          >
            {renderMenuItems(menu[activeKey]?.children)}
          </Tree>
        </div>
      </ResizeBox>}

      {/*  新增/编辑应用 */}
      {showModal && (
        <AppHandleModal
          appInfo={currentApp}
          visible={showModal}
          type={modalType}
          onChangeVisible={(value => setShowModal(value))}
          onClose={() => setShowModal(false)}
          onRefresh={onRefresh}
        ></AppHandleModal>
      )}
    </div>
  );
};

export default SideBar;