import {useState, useEffect} from 'react';
import './App.css';
import * as dd from 'dingtalk-jsapi';
import FileSelector from './FileSelector';
import FileInfoModal from './FileInfoModal';
import DocUrlModal from './DocUrlModal';

interface UserInfo {
    name: string;
    userid: string;
    unionid: string;
    sys: boolean;
    sys_level: number;
}

function App() {
    const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
    const [showUserInfo, setShowUserInfo] = useState(false);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [showFileInfoModal, setShowFileInfoModal] = useState(false);
    const [fileInfoLoading, setFileInfoLoading] = useState(false);
    const [docUrl, setDocUrl] = useState('');
    const [showDocUrlModal, setShowDocUrlModal] = useState(false);

    // 页面加载时自动触发免登
    useEffect(() => {
        // alert('免登useEffect已执行');
        const urlParams = new URLSearchParams(window.location.search);
        const corpId = urlParams.get('corpid');
        const clientId = import.meta.env.VITE_CLIENT_ID;
        console.log('corpId:', corpId, 'clientId:', clientId);
        if (!corpId || !clientId) {
            console.error('缺少必要参数');
            //setLoading(false);
            return;
        }
        dd.requestAuthCode({
            corpId,
            clientId,
            onSuccess: async (result: { code: string }) => {
                try {
                    const response = await fetch(`http://127.0.0.1:8080/api/getUserInfo?code=${result.code}&corpId=${corpId}`);
                    const data = await response.json();
                    if (data.success && data.data) {
                        setUserInfo(data.data);
                        setShowUserInfo(true);
                    } else {
                        alert('获取用户信息失败: ' + (data.message || '未知错误'));
                    }
                } catch (error) {
                    console.error('获取用户信息失败：', error);
                } finally {
                    //setLoading(false);
                }
            },
            onFail: (err: any) => {
                console.error('获取授权码失败：', err);
                //setLoading(false);
            }
        });
    }, []);

    const getRoleInfo = (level: number) => {
        switch (level) {
            case 1:
                return {text: '主管理员', color: 'red'};
            case 2:
                return {text: '子管理员', color: 'orange'};
            case 100:
                return {text: '老板', color: 'gold'};
            default:
                return {text: '普通员工', color: 'blue'};
        }
    };

    // 文件选择后弹窗
    const handleFileSelected = (file: File) => {
        setSelectedFile(file);
        setShowFileInfoModal(true);
    };

    // 弹窗点击提交，直接上传
    const handleFileInfoSubmit = async () => {
        if (!userInfo || !selectedFile) return;
        setFileInfoLoading(true);
        try {
            const formData = new FormData();
            formData.append('file', selectedFile);
            formData.append('unionId', userInfo.unionid);
            formData.append('dentryName', selectedFile.name);
            formData.append('size', selectedFile.size.toString());
            const resp = await fetch('http://127.0.0.1:8080/api/commit-file', {
                method: 'POST',
                body: formData
            });
            if (!resp.ok) {
                const text = await resp.text();
                alert('上传失败: ' + resp.status + ' ' + text);
                setFileInfoLoading(false);
                return;
            }
            let result;
            try {
                result = await resp.json();
            } catch (jsonErr) {
                alert('响应内容不是JSON，无法解析');
                setFileInfoLoading(false);
                return;
            }
            if (result && result.success === true && result.data && result.data.success === true && result.data.docUrl) {
                setDocUrl(result.data.docUrl);
                setShowDocUrlModal(true);
                setShowFileInfoModal(false);
                setSelectedFile(null);
            } else {
                alert('上传失败');
            }
        } catch (e) {
            alert('请求失败: ' + (e instanceof Error ? e.message : e));
        } finally {
            setFileInfoLoading(false);
        }
    };

    // 关闭文件信息弹窗
    const handleFileInfoClose = () => {
        setShowFileInfoModal(false);
        setSelectedFile(null);
    };

    // 下载文件
    const handDownFile = async () => {
        let data;
        try {
            if (!userInfo) return;
            const response = await fetch(`http://127.0.0.1:8080/api/downfile?unionId=${userInfo.unionid}`);
            if (!response.ok) { // 检查HTTP状态码是否在200-299之间
                throw new Error('Network response was not ok');
            }

            try {
                data = await response.json; // 解析JSON数据
            } catch (jsonErr) {
                alert('响应内容不是JSON，无法解析');
                setFileInfoLoading(false);
                return;
            }
            if (data.toString() != "") {
                alert("下载成功。")
            }
        }catch (e) {
          alert('下载失败: ' + (e instanceof Error ? e.message : e));
        }
    }


    // 关闭文档链接弹窗
    const handleDocUrlClose = () => {
        setShowDocUrlModal(false);
        setDocUrl('');
    };

    return (
        <div className="app-container">
            {/* 右上角用户信息条 */}
            {showUserInfo && userInfo && (
                <div className="user-info-bar" style={{
                    position: 'fixed',
                    top: 20,
                    right: 32,
                    zIndex: 1000,
                    background: 'rgba(255,255,255,0.95)',
                    borderRadius: 12,
                    boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
                    display: 'flex',
                    alignItems: 'center',
                    padding: '0 18px',
                    height: 44,
                    minWidth: 50
                }}>
                    <span className="user-name"
                          style={{fontWeight: 500, color: '#333', marginRight: 12, fontSize: 18}}>{userInfo.name}</span>
                    <span
                        className="user-role"
                        style={{
                            background: getRoleInfo(userInfo.sys_level).color,
                            color: '#fff',
                            borderRadius: 6,
                            padding: '2px 10px',
                            fontSize: 14,
                            fontWeight: 500,
                            display: 'inline-block'
                        }}
                    >
            {getRoleInfo(userInfo.sys_level).text}
          </span>
                </div>
            )}

            {/* 页面中间内容 */}
            <div className="main-content">
                {showUserInfo && userInfo ? (
                    <>
                        {/* 文件选择组件，仅登录后展示 */}
                        <FileSelector onFileSelected={handleFileSelected}/>
                        {/* 文件信息弹窗 */}
                        {selectedFile && showFileInfoModal && (
                            <FileInfoModal
                                visible={showFileInfoModal}
                                unionId={userInfo.unionid}
                                fileName={selectedFile.name}
                                fileSize={selectedFile.size}
                                onSubmit={handleFileInfoSubmit}
                                onClose={handleFileInfoClose}
                                loading={fileInfoLoading}
                            />
                        )}
                        {/* 上传成功后弹出文档链接 */}
                        {showDocUrlModal && (
                            <DocUrlModal visible={showDocUrlModal} url={docUrl} onClose={handleDocUrlClose}
                                         DownLoadFile={handDownFile}/>
                        )}
                    </>
                ) : (
                    <div style={{textAlign: 'center', marginTop: 80, color: '#888'}}>
                        <span>正在自动登录，请稍候...</span>
                    </div>
                )}
                {/* 你后续的操作内容可以加在这里 */}
            </div>
        </div>
    );
}

export default App;
