import React, { useEffect, useRef, useMemo, useState, Fragment } from "react";
import Image from 'next/image';
import styles from "./home.module.scss";
import newStyles from './sidebar.module.scss';
import DragIcon from "../icons/drag.svg";
import logoSrc from "../icons/logo.png";
import deepSeekSrc from "../icons/deepSeek.png";
import { AppstoreOutlined, EditOutlined, MenuOutlined, HomeOutlined, PlusOutlined, StarOutlined, CommentOutlined } from '@ant-design/icons';
import * as AllIcons from '@ant-design/icons';
import { useAppConfig, useChatStore, useGlobalStore } from "../store";
import {
  DEFAULT_SIDEBAR_WIDTH,
  MAX_SIDEBAR_WIDTH,
  MIN_SIDEBAR_WIDTH,
  NARROW_SIDEBAR_WIDTH,
} from "../constant";
import { useLocation, useNavigate } from "react-router-dom";
import { isIOS, useMobileScreen, getContrastColor } from "../utils";
import api from "@/app/api/api";
import { Button, Drawer, Dropdown, Empty, Form, Input, Menu, message, Modal, Rate, Tag, Select } from "antd";
import { downloadFile } from "../utils/index";
import dayjs from "dayjs";
import type { DrawerProps, RadioChangeEvent } from 'antd';
import '@/app/styles/common.scss'
const FormItem = Form.Item;
import { processSliceData } from "@/app/utils/index";

export function useHotKey() {
 const chatStore = useChatStore();

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.altKey || e.ctrlKey) {
        if (e.key === "ArrowUp") {
          chatStore.nextSession(-1);
        } else if (e.key === "ArrowDown") {
          chatStore.nextSession(1);
        }
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  });
}

export function useDragSideBar() {
  const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);

  const config = useAppConfig();
  const startX = useRef(0);
  const startDragWidth = useRef(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  const lastUpdateTime = useRef(Date.now());

  const toggleSideBar = () => {
    config.update((config) => {
      if (config.sidebarWidth < MIN_SIDEBAR_WIDTH) {
        config.sidebarWidth = DEFAULT_SIDEBAR_WIDTH;
      } else {
        config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
      }
    });
  };

  const onDragStart = (e: MouseEvent) => {
    // Remembers the initial width each time the mouse is pressed
    startX.current = e.clientX;
    startDragWidth.current = config.sidebarWidth;
    const dragStartTime = Date.now();

    const handleDragMove = (e: MouseEvent) => {
      if (Date.now() < lastUpdateTime.current + 20) {
        return;
      }
      lastUpdateTime.current = Date.now();
      const d = e.clientX - startX.current;
      const nextWidth = limit(startDragWidth.current + d);
      config.update((config) => {
        if (nextWidth < MIN_SIDEBAR_WIDTH) {
          config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
        } else {
          config.sidebarWidth = nextWidth;
        }
      });
    };

    const handleDragEnd = () => {
      // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth
      window.removeEventListener("pointermove", handleDragMove);
      window.removeEventListener("pointerup", handleDragEnd);

      // if user click the drag icon, should toggle the sidebar
      const shouldFireClick = Date.now() - dragStartTime < 300;
      if (shouldFireClick) {
        toggleSideBar();
      }
    };

    window.addEventListener("pointermove", handleDragMove);
    window.addEventListener("pointerup", handleDragEnd);
  };

  const isMobileScreen = useMobileScreen();
  const shouldNarrow =
    !isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH;

  useEffect(() => {
    const barWidth = shouldNarrow
      ? NARROW_SIDEBAR_WIDTH
      : limit(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
    const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`;
    document.documentElement.style.setProperty("--sidebar-width", sideBarWidth);
  }, [config.sidebarWidth, isMobileScreen, shouldNarrow]);

  return {
    onDragStart,
    shouldNarrow,
  };
}
export function SideBarContainer(props: {
  children: React.ReactNode;
  onDragStart: (e: MouseEvent) => void;
  shouldNarrow: boolean;
  className?: string;
}) {
  const isMobileScreen = useMobileScreen();
  const isIOSMobile = useMemo(
    () => isIOS() && isMobileScreen,
    [isMobileScreen],
  );
  const { children, className, onDragStart, shouldNarrow } = props;

  // shadow-sidebar
  return (
    <div
      className={`${styles.sidebar} ${className} ${shouldNarrow && styles["narrow-sidebar"]} 
        bg-light-sidebar  ${isMobileScreen && newStyles.isMobildwid}`}
      style={{
        transition: isMobileScreen && isIOSMobile ? "none" : undefined,
        overflowY: "auto",
      }}
    >
      {children}
      <div
        className={styles["sidebar-drag"]}
        onPointerDown={(e) => onDragStart(e as any)}
      >
        <DragIcon />
      </div>
    </div>
  );
}
// Sidebar 头部
export function SideBarHeader(props: {
  title?: string | React.ReactNode;
  subTitle?: string | React.ReactNode;
  logo?: React.ReactNode;
  children?: React.ReactNode;
}) {
  const { title, subTitle, logo, children } = props;
  const navigate = useNavigate();

  return (
    <Fragment>
      <div className={`${styles["sidebar-header"]} cursor-pointer`} data-tauri-drag-region onClick={() => {
        window.open('http://10.1.14.17:3200/appCenter')
      }} >
        <div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
        <div className={styles["sidebar-title-container"] + ' ml-[10px]'}>
          <div className={`${styles["sidebar-title"]} text-gray-800`} data-tauri-drag-region>
            {title}
          </div>
          <div className={`${styles["sidebar-sub-title"]} text-gray-500 text-sm`}>{subTitle}</div>
        </div>
      </div>
      {children}
    </Fragment>
  );
}

export function SideBarBody(props: {
  children: React.ReactNode;
  onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
}) {
  const { onClick, children } = props;
  return (
    <div className={`${styles["sidebar-body"]} scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-transparent`} onClick={onClick}>
      {children}
    </div>
  );
}

export function SideBarTail(props: {
  primaryAction?: React.ReactNode;
  secondaryAction?: React.ReactNode;
}) {
  const { primaryAction, secondaryAction } = props;

  return (
    <div className={`${styles["sidebar-tail"]} border-t border-gray-200 pt-4`}>
      <div className={styles["sidebar-actions"]}>{primaryAction}</div>
      <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
    </div>
  );
}

interface AppDrawerProps {
  isMobileScreen: boolean,
  selectedAppId: string,
  type: 'all' | 'collect',
  open: boolean,
  onClose: () => void,
}

export const SideBar = (props: { className?: string }) => {
  // useHotKey();
  const { onDragStart, shouldNarrow } = useDragSideBar();
  const [showPluginSelector, setShowPluginSelector] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const chatStore = useChatStore();
  const globalStore = useGlobalStore();

  const [menuList, setMenuList] = useState([])
  const [modalOpen, setModalOpen] = useState(false)
  const [form] = Form.useForm();
  const getType = (): 'bigModel' | 'deepSeek' => {
    if (['/knowledgeChat', '/newChat'].includes(location.pathname)) {
      return 'bigModel';
    } else if (['/deepseekChat', '/newDeepseekChat','/welcome'].includes(location.pathname)) {
      return 'deepSeek';
    } else {
      return 'bigModel';
    }
  }
  // 获取应用类型 app_type
  const fetchAppType = async () => {
    try {
      const res = await api.get(`/deepseek/api/app_type`);
      // 解析返回并设置状态
      if (res && res.data) {
        setAppTypes([{ dictLabel: '收藏', dictValue: '收藏' }, ...res.data]);
      }
    } catch (error) {
      console.error('Failed to fetch app types:', error);
    }
  }
  // 获取应用列表
  const fetchGetApplicationList = async (typeId?: string | null, name?: string) => {
    setAppListLoading(true);
    try {
      const data = {
        pageSize: 1000,
        pageNum: 1,
        userId: 1,
        isCollect: typeId === '收藏' ? '1' : null,
        typeId: typeId === '收藏' ? null : typeId,
        name: name,
      }
      const res: any = await api.post('/deepseek/api/getApplicationList', data);
      // 解析返回并设置状态
      if (res && res.rows) {
        setAppListState(res.rows);
        if (name) {
          setSearchOptions(res.rows.map((item: any) => ({ label: item.name, value: item.appId })));
        }
      }

    } catch (error) {
      console.error('Failed to fetch app list:', error);
    } finally {
      setAppListLoading(false);
      setSearchFetching(false);
    }
  }
  // 应用类型与列表状态
  const [appTypes, setAppTypes] = useState<any[]>([]);
  const [appListState, setAppListState] = useState<any[]>([]);
  const [appListLoading, setAppListLoading] = useState<boolean>(false);
  const [openKeys, setOpenKeys] = useState<string[]>([]); // 当前打开的菜单项
  // 渲染应用列表为 Antd Menu（一级：类型，带图标；二级：该类型下的应用）
  const previewAppList = () => {
    const iconFor = (index: number) => {
      const icons = [<AppstoreOutlined />, <StarOutlined />, <HomeOutlined />];
      return icons[index % icons.length];
    };

    const items = appTypes && appTypes.length
      ? appTypes.map((t: any, idx: number) => {
        // 当该一级是当前打开项时，使用 appListState 作为 children（fetchGetApplicationList 填充）
        const typeKey = `${t.dictValue}`;
        let children = [] as any[];
        // if (openKeys.includes(typeKey)) {
        if (appListLoading) {
          children = [{ key: `${typeKey}-loading`, label: <span>加载中...</span> }];
        } else {
          children = (appListState || []).map((a: any, i: number) => ({
            key: a.appId || `app-${idx}-${i}`,
            // label: a.dictLabel || a.name || a.appName || `应用 ${i}`,
            label: a.iconColor ? (() => {
              const C = (AllIcons as any)[a.iconType];
              const iconColor = getContrastColor(a.iconColor);
              return C ? <div className="flex items-center justify-start">
                <p className="flex items-center justify-center" style={{ overflow: 'auto', background: a.iconColor, minWidth: '28px', width: 28, height: 28, borderRadius: 8, padding: 0, margin: 0, marginRight: 4 }}>
                  <C style={{ fontSize: 28, color: iconColor }} />
                </p>

                <span className="truncate ml-2">
                  {a.name || a.appName || `应用 ${i}`}
                </span>
              </div> : <span style={{ fontSize: 12 }}>{a.iconType}</span>
            })() : <span className="truncate">
              {a.name || a.appName || `应用 ${i}`}
            </span>,
            onClick: () => {
              chatStore.updateCurrentSession((value) => {
                value.appId = a.appId;
              });
              // 点击二级应用的处理：打印或导航（保留为 UI 先）
              chatStore.clearSessions();
              if (getType() === 'bigModel') {
                globalStore.setSelectedAppId(a.appId);
              } else {
                const search = `?showMenu=false&chatMode=LOCAL&appId=${a.appId}`;
                navigate({
                  pathname: '/knowledgeChat',
                  search: search,
                })
                globalStore.setSelectedAppId(a.appId);
                // location.reload();
              }
            }
          }));
        }
        // }
        if (openKeys.includes(typeKey)) {
          return {
            key: t.dictValue,
            icon: iconFor(idx),
            label: t.dictLabel || `类型 ${idx}`,
            children: children.length ? children : [{ key: `empty-${idx}`, label: <span className="text-xs text-gray-400">暂无应用</span>, }],
          };
        } else {
          return {
            key: t.dictValue,
            icon: iconFor(idx),
            label: t.dictLabel || `类型 ${idx}`,
            children: [],
          };
        }
      })
      : [];
    return (
      <Menu
        items={items}
        mode="inline"
        openKeys={openKeys}
        selectable={false}
        className={`bg-transparent p-[0] ${newStyles.sidebarContainer}`}
        style={{ border: 'none', background: 'transparent' }}
        onOpenChange={(e) => {
          console.log('e', e);
          if (e.length > 0) {
            setOpenKeys(e.slice(-1));
            fetchGetApplicationList(e.slice(-1)[0]);
          } else {
            setOpenKeys([]);
          }
        }}
      />
    );
  }


  // 获取聊天列表
  const fetchChatList = async (chatMode?: 'ONLINE' | 'LOCAL') => {
    try {
      let url = '';
      const appId = globalStore.selectedAppId;
      if (appId) {
        url = `/deepseek/api/dialog/list/${appId}`;
        const res = await api.get(url);
        const list = res.data.map((item: any) => {
          return {
            ...item,
            children: item.children.map((child: any) => {
              const items = [
                {
                  key: '1',
                  label: (
                    <a onClick={(e: React.MouseEvent) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setModalOpen(true);
                      form.setFieldsValue({
                        dialogId: child.key,
                        dialogName: child.label
                      });
                    }}>
                      重命名
                    </a>
                  ),
                },
                {
                  key: '2',
                  label: (
                    <a onClick={async () => {
                      try {
                        let blob = null;
                        if (getType() === 'bigModel') {
                          if (chatMode === 'LOCAL') {
                            blob = await api.post(`/deepseek/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
                          } else {
                            blob = await api.post(`/bigmodel/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
                          }
                        } else {
                          blob = await api.post(`/bigmodel/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
                        }
                        const fileName = `${child.label}.xlsx`;
                        downloadFile(blob, fileName);
                      } catch (error) {
                        console.error(error);
                      }
                    }}>
                      导出
                    </a>
                  ),
                },
                {
                  key: '3',
                  label: (
                    <a onClick={async () => {
                      try {
                        if (getType() === 'bigModel') {
                          if (chatMode === 'LOCAL') {
                            await api.delete(`/deepseek/api/dialog/del/${child.key}`);
                            await fetchChatList(chatMode);
                          } else {
                            await api.delete(`/bigmodel/api/dialog/del/${child.key}`);
                            await fetchChatList();
                          }
                        } else {
                          await api.delete(`/bigmodel/api/dialog/del/${child.key}`);
                          await fetchChatList();
                        }
                        chatStore.clearSessions();
                        useChatStore.setState({
                          message: {
                            content: '',
                            role: 'assistant',
                          }
                        });
                      } catch (error) {
                        console.error(error);
                      }
                    }}>
                      删除
                    </a>
                  ),
                },
              ];
              return {
                ...child,
                label: <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 10 }}>
                    {child.label}
                  </div>
                  <div style={{ width: 20 }}>
                    <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
                      <EditOutlined onClick={(e) => e.stopPropagation()} />
                    </Dropdown>
                  </div>
                </div>
              }
            })
          }
        })
        setMenuList(list);
      }
    } catch (error) {
      console.error(error)
    }
  }



  useEffect(() => {
    // if (getType() === 'bigModel') {
    if (globalStore.selectedAppId) {
      fetchChatList('LOCAL');
    }
    // }
  }, [globalStore.selectedAppId]);

  useEffect(() => {
    fetchAppType();
    chatStore.clearSessions();
    useChatStore.setState({
      message: {
        content: '',
        role: 'assistant',
      }
    });
  }, []);

  useEffect(() => {
    fetchChatList(chatStore.chatMode);
  }, [chatStore.chatMode]);

  const isMobileScreen = useMobileScreen();

  const [drawerOpen, setDrawerOpen] = useState(false);

  const [drawerType, setDrawerType] = useState<'all' | 'collect'>('all');

  // Select 远程搜索 UI 状态（UI-only 模拟）
  const [searchOptions, setSearchOptions] = useState<any[]>([]);
  const [searchFetching, setSearchFetching] = useState(false);

  const handleSearch = (value: string) => {
    console.log('search value', value);
    if (!value) {
      setSearchOptions([]);
      return;
    }
    setSearchFetching(true);
    fetchGetApplicationList(null, value);
    // 模拟异步请求
  };
  const [placement, setPlacement] = useState<DrawerProps['placement']>('left');

  return (
    <>
      {
        isMobileScreen ? globalStore.showMenu &&
          <Drawer
            title="Basic Drawer"
            placement={placement}
            closable={true}
            maskClosable={true}
            onClose={(e) => {
              console.log('close drawer');
              e.preventDefault();
              e.stopPropagation();
              globalStore.setShowMenu(false);
            }}
            open={globalStore.showMenu}
            key={placement}
            style={{
              // 1. 自定义 Drawer 整体背景色（包括头部、内容区）
              background: 'none', // 浅灰背景，可替换为 #fff、rgb(255,255,255) 等
              width: '100%',
            }}
            styles={{
              mask: {
                zIndex: 1000, // 遮罩层层级（原 maskStyle 中的配置）
                background: 'rgba(0, 0, 0, 0.3)', // 遮罩层背景色/透明度
                // 其他遮罩层样式均可在此配置，与原 maskStyle 用法一致
              },
            }}
          >
            <SideBarContainer
              onDragStart={onDragStart}
              shouldNarrow={shouldNarrow}
              {...props}
            >
              {/* {
            getType() === 'deepSeek' &&
            <div>
              <img style={{ width: '100%' }} src={deepSeekSrc.src} />
            </div>
          } */}
              <SideBarHeader
                title={getType() === 'bigModel' || true ?
                  <div className="flex items-center">
                    {/* {
                      isMobileScreen && <div>
                        <Button
                          type='text'
                          icon={<MenuOutlined />}
                          onClick={() => {
                            globalStore.setShowMenu(!globalStore.showMenu);
                          }}
                        />
                      </div>
                    } */}
                    <img style={{ height: 40 }} src={logoSrc.src} />
                    {/* 盈科 */}
                  </div>
                  :
                  ''
                }
                // logo={getType() === 'bigModel' || true ? <img style={{ height: 40 }} src={logoSrc.src} /> : ''}
              >
                <div className="w-full">
                  <Button type="primary"
                    icon={<PlusOutlined />}
                    className="border border-[#4096ff] text-[#4096ff] bg-transparent w-full mb-[10px]"
                    onClick={async () => {
                      chatStore.clearSessions();
                      chatStore.updateCurrentSession((value) => {
                        value.appId = globalStore.selectedAppId;
                      });
                      if (isMobileScreen) {
                        globalStore.setShowMenu(false);
                      }
                      if (getType() === 'bigModel') {
                        navigate({ pathname: '/newChat' });
                      } else {
                        message.info('请选择应用')
                        // navigate({ pathname: '/newDeepseekChat' });
                      }
                      if (getType() === 'bigModel') {
                        // if (chatStore.chatMode === 'LOCAL') {
                          await fetchChatList(chatStore.chatMode);
                        // } else {
                          // await fetchChatList();
                        // }
                      } else {
                        // await fetchChatList();
                      }
                    }}
                  >
                    新建对话
                  </Button>
                </div>
                {/* 搜索框 - antd Select 远程搜索（UI only） */}
                <div className="mb-[5px] text-left">
                  <Select
                    className="text-left bg-transparent w-full"
                    showSearch
                    allowClear
                    placeholder="搜索应用名称"
                    filterOption={false}
                    onSearch={handleSearch}
                    options={searchOptions}
                    notFoundContent={searchFetching ? '搜索中...' : '无匹配'}
                    onChange={(appId) => {
                      // 选择后可触发打开抽屉或填写表单等动作（目前只做UI）
                      console.log('select val', appId);
                      chatStore.updateCurrentSession((value) => {
                        value.appId = appId;
                      });
                      // 点击二级应用的处理：打印或导航（保留为 UI 先）
                      chatStore.clearSessions();
                      if (getType() === 'bigModel') {
                        globalStore.setSelectedAppId(appId);
                      } else {
                        const search = `?showMenu=false&chatMode=LOCAL&appId=${appId}`;
                        navigate({
                          pathname: '/knowledgeChat',
                          search: search,
                        })
                        globalStore.setSelectedAppId(appId);
                        // location.reload();
                      }
                    }}
                    style={{ width: '100%', textAlign: 'left', background: 'transparent' }}
                  />
                </div>
                {/* 应用列表 */}
                {previewAppList()}
              </SideBarHeader>
              {/* 最近对话 */}
              {menuList.length > 0 && <p className="text-[14px] ml-[6px]"> <CommentOutlined /> 最近对话</p>}
              <Menu
                className="bg-transparent"
                style={{ border: 'none', background: 'transparent' }}
                selectable={false}
                onClick={async (info: any) => {
                  const key = info.key;
                  // @ts-ignore
                  const props = info.item?.props;
                  const { showMenu, chatMode, appId } = props;
                  if (isMobileScreen) {
                    globalStore.setShowMenu(false);
                  }
                  let url = ``;
                  if (getType() === 'bigModel') {
                    if (chatStore.chatMode === 'LOCAL') {
                      url = `/deepseek/api/dialog/detail/${key}`;
                    }
                  } else {
                    url = `/bigmodel/api/dialog/detail/${key}`;
                  }
                  const res = await api.get(url);
                  const list = res.data.map(((item: any) => {
                    if (item.sliceInfo) {
                      let allChunkNum = 0;
                      item.sliceInfo.doc.forEach((doc: any) => {
                        allChunkNum += doc.chunk_nums;
                      });
                      item.sliceInfo.allChunkNum = allChunkNum;
                      const values1 = item.sliceInfo?.doc;
                      const result = processSliceData(values1);
                      // 使用解构赋值，让结果更清晰
                      const { withDeprecated, withoutDeprecated } = result;
                      item.sliceInfo.docDeprecated = withDeprecated;
                      item.sliceInfo.docActive = withoutDeprecated;
                      console.log('item.sliceInfo', item.sliceInfo)
                    }
                    return {
                      id: item.did,
                      role: item.type,
                      date: item.create_time,
                      content: item.content,
                      document: item.document ? item.document : undefined,
                      sliceInfo: item.sliceInfo ? item.sliceInfo : undefined,
                      delSliceInfo: item.sliceInfo ? item.sliceInfo : undefined,
                      networkInfo: item.networkInfo ? item.networkInfo : undefined,
                    }
                  }))
                  const session = {
                    appId: res.data.length ? res.data[0].appId : '',
                    dialogName: res.data.length ? res.data[0].dialog_name : '',
                    id: res.data.length ? res.data[0].id : '',
                    messages: list,
                  }
                  globalStore.setCurrentSession(session);
                  chatStore.clearSessions();
                  chatStore.updateCurrentSession((value) => {
                    value.appId = session.appId;
                    value.topic = session.dialogName;
                    value.id = session.id;
                    value.messages = list;
                  });
                  if (getType() === 'bigModel') {
                    const search = `?showMenu=${showMenu}&chatMode=${chatMode}&appId=${appId}`;
                    if (appId) {
                      navigate({
                        pathname: '/knowledgeChat',
                        search: search,
                      })
                    }
                  } 
                  // else {
                  //   navigate({ pathname: '/newDeepseekChat' });
                  // }
                }}
                mode="inline"
                items={menuList}
              />
              <Modal
                title="重命名"
                open={modalOpen}
                width={300}
                maskClosable={false}
                onOk={() => {
                  form.validateFields().then(async (values) => {
                    setModalOpen(false);
                    try {
                      if (getType() === 'bigModel') {
                        if (chatStore.chatMode === 'LOCAL') {
                          await api.put(`/deepseek/api/dialog/update`, {
                            id: values.dialogId,
                            dialogName: values.dialogName
                          });
                          await fetchChatList(chatStore.chatMode);
                        } else {
                          await api.put(`/bigmodel/api/dialog/update`, {
                            id: values.dialogId,
                            dialogName: values.dialogName
                          });
                          await fetchChatList();
                        }
                      } else {
                        await api.put(`/bigmodel/api/dialog/update`, {
                          id: values.dialogId,
                          dialogName: values.dialogName
                        });
                        await fetchChatList();
                      }
                      chatStore.updateCurrentSession((value) => {
                        value.topic = values.dialogName;
                      });
                    } catch (error) {
                      console.error(error);
                    }
                  }).catch((error) => {
                    console.error(error);
                  });
                }}
                onCancel={() => {
                  setModalOpen(false);
                }}
              >
                <Form form={form} layout='inline'>
                  <FormItem name='dialogId' noStyle />
                  <FormItem
                    label='名称'
                    name='dialogName'
                    rules={[{ required: true, message: '名称不能为空', whitespace: true }]}
                  >
                    <Input
                      style={{ width: 300 }}
                      placeholder='请输入'
                      maxLength={20}
                    />
                  </FormItem>
                </Form>
              </Modal>
            </SideBarContainer>
          </Drawer> :
          globalStore.showMenu && <SideBarContainer
            onDragStart={onDragStart}
            shouldNarrow={shouldNarrow}
            {...props}
          >
            {/* {
            getType() === 'deepSeek' &&
            <div>
              <img style={{ width: '100%' }} src={deepSeekSrc.src} />
            </div>
          } */}
            <SideBarHeader
              title={getType() === 'bigModel' || true ?
                <div className="flex items-center">
                  {
                    isMobileScreen && <div>
                      <Button
                        type='text'
                        icon={<MenuOutlined />}
                        onClick={() => {
                          globalStore.setShowMenu(!globalStore.showMenu);
                        }}
                      />
                    </div>
                  }
                  <img style={{ height: 40 }} src={logoSrc.src} />
                  {/* 盈科2 */}
                </div>
                :
                ''
              }
              // logo={getType() === 'bigModel' || true ? <Logosvg></Logosvg> : ''}
            >
              <div className="w-full">
                <Button type="primary"
                  icon={<PlusOutlined />}
                  className="border border-[#4096ff] text-[#4096ff] bg-transparent w-full mb-[10px]"
                  onClick={async () => {
                    chatStore.clearSessions();
                    chatStore.updateCurrentSession((value) => {
                      value.appId = globalStore.selectedAppId;
                    });
                    if (isMobileScreen) {
                      globalStore.setShowMenu(false);
                    }
                    if (getType() === 'bigModel') {
                      navigate({ pathname: '/newChat' });
                    } else {
                      // navigate({ pathname: '/newDeepseekChat' });
                      message.info('请选择应用')
                    }
                    if (getType() === 'bigModel') {
                      if (chatStore.chatMode === 'LOCAL') {
                        await fetchChatList(chatStore.chatMode);
                      // } else {
                        // await fetchChatList();
                      }
                    }
                    //  else {
                    //   await fetchChatList();
                    // }
                  }}
                >
                  新建对话
                </Button>
              </div>
              {/* 搜索框 - antd Select 远程搜索（UI only） */}
              <div className="mb-[5px] text-left">
                <Select
                  className="text-left bg-transparent w-full"
                  showSearch
                  allowClear
                  placeholder="搜索应用名称"
                  filterOption={false}
                  onSearch={handleSearch}
                  options={searchOptions}
                  notFoundContent={searchFetching ? '搜索中...' : '无匹配'}
                  onChange={(appId) => {
                    // 选择后可触发打开抽屉或填写表单等动作（目前只做UI）
                    console.log('select val', appId);
                    // 选择后可触发打开抽屉或填写表单等动作（目前只做UI）
                    console.log('select val', appId);
                    chatStore.updateCurrentSession((value) => {
                      value.appId = appId;
                    });
                    // 点击二级应用的处理：打印或导航（保留为 UI 先）
                    chatStore.clearSessions();
                    if (getType() === 'bigModel') {
                      globalStore.setSelectedAppId(appId);
                    } else {
                      const search = `?showMenu=false&chatMode=LOCAL&appId=${appId}`;
                      navigate({
                        pathname: '/knowledgeChat',
                        search: search,
                      })
                      globalStore.setSelectedAppId(appId);
                      // location.reload();
                    }
                  }}
                  style={{ width: '100%', textAlign: 'left', background: 'transparent' }}
                />
              </div>
              {/* 应用列表 */}
              {previewAppList()}
            </SideBarHeader>
            {/* 最近对话 */}
            {menuList.length > 0 && <p className="text-[14px] ml-[6px]"> <CommentOutlined /> 最近对话</p>}
            <Menu
              className="bg-transparent"
              style={{ border: 'none', background: 'transparent' }}
              selectable={false}
              onClick={async (info: any) => {
                const key = info.key;
                // @ts-ignore
                const props = info.item?.props;
                const { showMenu, chatMode, appId } = props;
                if (isMobileScreen) {
                  globalStore.setShowMenu(false);
                }
                let url = ``;
                if (getType() === 'bigModel') {
                  if (chatStore.chatMode === 'LOCAL') {
                    url = `/deepseek/api/dialog/detail/${key}`;
                  }
                } else {
                  url = `/bigmodel/api/dialog/detail/${key}`;
                }
                const res = await api.get(url);
                const list = res.data.map(((item: any) => {
                  if (item.sliceInfo) {
                    let allChunkNum = 0;
                    item.sliceInfo.doc.forEach((doc: any) => {
                      allChunkNum += doc.chunk_nums;
                    });
                    item.sliceInfo.allChunkNum = allChunkNum;
                    const values1 = item.sliceInfo?.doc;
                    // console.log('values1', values1);
                    const result = processSliceData(values1);
                    // console.log('result---',result)
                    // 使用解构赋值，让结果更清晰
                    const { withDeprecated, withoutDeprecated } = result;
                    item.sliceInfo.docDeprecated = withDeprecated;
                    item.sliceInfo.docActive = withoutDeprecated;
                    // console.log('item.sliceInfo',item.sliceInfo)
                  }
                  return {
                    id: item.did,
                    role: item.type,
                    date: item.create_time,
                    content: item.content,
                    document: item.document ? item.document : undefined,
                    sliceInfo: item.sliceInfo ? item.sliceInfo : undefined,
                    delSliceInfo: item.sliceInfo ? item.sliceInfo : undefined,
                    networkInfo: item.networkInfo ? item.networkInfo : undefined,
                  }
                }))
                const session = {
                  appId: res.data.length ? res.data[0].appId : '',
                  dialogName: res.data.length ? res.data[0].dialog_name : '',
                  id: res.data.length ? res.data[0].id : '',
                  messages: list,
                }
                globalStore.setCurrentSession(session);
                chatStore.clearSessions();
                chatStore.updateCurrentSession((value) => {
                  value.appId = session.appId;
                  value.topic = session.dialogName;
                  value.id = session.id;
                  value.messages = list;
                });
                if (getType() === 'bigModel') {
                  const search = `?showMenu=${showMenu}&chatMode=${chatMode}&appId=${appId}`;
                  if (appId) {
                    navigate({
                      pathname: '/knowledgeChat',
                      search: search,
                    })
                  }
                } else {
                  navigate({ pathname: '/newDeepseekChat' });
                }
              }}
              mode="inline"
              items={menuList}
            />
            <Modal
              title="重命名"
              open={modalOpen}
              width={300}
              maskClosable={false}
              onOk={() => {
                form.validateFields().then(async (values) => {
                  setModalOpen(false);
                  try {
                    if (getType() === 'bigModel') {
                      if (chatStore.chatMode === 'LOCAL') {
                        await api.put(`/deepseek/api/dialog/update`, {
                          id: values.dialogId,
                          dialogName: values.dialogName
                        });
                        await fetchChatList(chatStore.chatMode);
                      } else {
                        await api.put(`/bigmodel/api/dialog/update`, {
                          id: values.dialogId,
                          dialogName: values.dialogName
                        });
                        await fetchChatList();
                      }
                    } else {
                      await api.put(`/bigmodel/api/dialog/update`, {
                        id: values.dialogId,
                        dialogName: values.dialogName
                      });
                      await fetchChatList();
                    }
                    chatStore.updateCurrentSession((value) => {
                      value.topic = values.dialogName;
                    });
                  } catch (error) {
                    console.error(error);
                  }
                }).catch((error) => {
                  console.error(error);
                });
              }}
              onCancel={() => {
                setModalOpen(false);
              }}
            >
              <Form form={form} layout='inline'>
                <FormItem name='dialogId' noStyle />
                <FormItem
                  label='名称'
                  name='dialogName'
                  rules={[{ required: true, message: '名称不能为空', whitespace: true }]}
                >
                  <Input
                    style={{ width: 300 }}
                    placeholder='请输入'
                    maxLength={20}
                  />
                </FormItem>
              </Form>
            </Modal>
          </SideBarContainer>
      }
    </>
  );
}