import * as React from 'react';
import { useNavigate } from "react-router-dom";
import { Dropdown, Spin, Input, Button, Space, UploadProps } from 'antd';
import { Chat } from './DeepSeekChat';
import whiteLogo from "../icons/whiteLogo.png";
import jkxz from "../icons/jkxz.png";
import { useChatStore, useGlobalStore } from "../store";
import { useMobileScreen } from '../utils';
import api from "@/app/api/api";
import './deepSeekHome.scss';
import { message, Upload } from 'antd';
import { InboxOutlined } from '@ant-design/icons';

const { Dragger } = Upload;
const DeekSeek: React.FC = () => {
    const chatStore = useChatStore();
    const globalStore = useGlobalStore();
    useGlobalStore((state) => state.setIsChatActive);
    const isMobileScreen = useMobileScreen();
    const navigate = useNavigate();

    const [listLoading, setListLoading] = React.useState(false);
    const [userInput, setUserInput] = React.useState(''); // 新增状态：用户输入

    type List = {
        title: string,
        children: {
            title: string,
            showMenu: string,
            chatMode: string,
            appId: string,
            children: List[number]['children'],
        }[],
    }[];

    const [list, setList] = React.useState<List>([]);

    const init = async () => {
        setListLoading(true);
        try {
            const res = await api.get('/deepseek/api/appType');
            setList(res.data);
        } catch (error) {
            console.error(error);
        } finally {
            setListLoading(false);
        }
    }

    React.useEffect(() => {
        chatStore.clearSessions();
        const userInfo = localStorage.getItem('userInfo');

        if (userInfo) {
            init();
        }
    }, []);

    React.useEffect(() => {
        globalStore.setDocuments([]);
        globalStore.setIsChatActive(false);
        setFileList([]);
    }, []);

    const [fileList, setFileList] = React.useState<any[]>([]);

    const props: UploadProps = {
        action: '/deepseek-api' + '/upload/file',
        method: 'POST',
        accept: ['.docx'].join(','),
        multiple: true,
        maxCount: 5,
        fileList: fileList,
        onChange(info) {
            const fileList = info.fileList.map((file) => {
                const data = file.response;
                return {
                    ...file,
                    documentId: data?.document_id || '',
                    name: file.name,
                    url: data?.document_url || file.url,
                }
            });
            setFileList(fileList);
            if (info.file.status === 'done') {// 上传成功
                const { code, message: msg } = info.file.response;
                if (code === 200) {
                    message.success('上传成功');
                } else {
                    message.error(msg);
                }
            } else if (info.file.status === 'error') {// 上传失败
                message.error('上传失败');
            }
        },
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
    };

    return (
        <Spin spinning={listLoading}>
            <div className='deekSeek'>
                {/* 主要区域 */}
                <div className='deekSeek-main'>
                    {!globalStore.isChatActive ? (
                        // 未交互状态：显示简化对话框
                        <div className='deekSeek-content'>
                            <div className='deekSeek-content-title'>
                                <img src={jkxz.src} />
                            </div>
                            <div className='deekSeek-content-title-sm' style={{ marginBottom: 40 }}>
                                您好, 我是小智文件处理助手!
                            </div>
                            {/* 输入区域 */}
                            <div className='deekSeek-input-section'>
                                <Dragger {...props}>
                                    <p className="ant-upload-drag-icon">
                                        <InboxOutlined />
                                    </p>
                                    <p className="ant-upload-text">请上传.docx格式文件</p>
                                </Dragger>
                            </div>
                            <div style={{ margin: 5 }}>
                                <Button
                                    type='primary'
                                    onClick={() => {
                                        globalStore.setDocuments(fileList.map(item => {
                                            return {
                                                id: item.documentId,
                                                name: item.name,
                                                url: item.url,
                                            }
                                        }));
                                        globalStore.setIsChatActive(true);
                                    }}
                                    disabled={fileList.filter(item => item.documentId).length === 0}
                                >
                                    开始解析
                                </Button>
                            </div>
                            {/* 底部提示 */}
                            <div className='deekSeek-footer-text'>
                                内容由AI生成，仅供参考
                            </div>
                        </div>
                    ) : (
                        // 激活状态：显示完整对话界面
                        <div className='deekSeek-content'>
                            <div className='deekSeek-content-title'>
                                <img src={jkxz.src} />
                            </div>
                            <div className='deekSeek-content-title-sm' style={{ marginBottom: isMobileScreen ? 14 : 20 }}>
                                智能问答助手
                            </div>
                            <div className={isMobileScreen ? 'deekSeek-content-mobile' : 'deekSeek-content-pc'}>
                                <Chat />
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </Spin >
    );
};

export default DeekSeek;