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

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);


  // 页面加载时自动触发免登
  useEffect(() => {
    // alert('免登useEffect已执行');
    const urlParams = new URLSearchParams(window.location.search);
    const corpId = urlParams.get('corpid');
    const clientId = import.meta.env.VITE_CLIENT_ID;
    if (!corpId || !clientId) {
      console.error('缺少必要参数');
      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);
            alert(data.data)
            setShowUserInfo(true);
          } else {
            alert('获取用户信息失败: ' + (data.message || '未知错误'));
          }
        } catch (error) {
          console.error('获取用户信息失败：', error);
        }
      },
      onFail: (err: never) => {
        console.error('获取授权码失败：', err);
      }
    });
  }, []);

  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 handleFileInfoSubmit = async () => {
    if (!userInfo) return;
    try {
      const formData = new FormData();
      formData.append('userId', userInfo.userid);
      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);
        return;
      }else{
        alert('上传成功，已像'+userInfo.name+'发送了图片类型的工作通知，请及时查收！');
      }
    } catch (e) {
      alert('请求失败: ' + (e instanceof Error ? e.message : e));
    } finally {
      //setFileInfoLoading(false);
    }
  };
  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">
          <button
              type="button"
              onClick={handleFileInfoSubmit}
              style={{
                padding: '18px 48px',
                borderRadius: 32,
                background: 'linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)',
                color: '#fff',
                border: 'none',
                fontSize: 22,
                fontWeight: 600,
                letterSpacing: 2,
                boxShadow: '0 4px 16px rgba(24,144,255,0.18)',
                cursor: 'pointer',
                transition: 'all 0.2s, transform 0.2s',
                marginTop: 12,
                marginBottom: 18,
                outline: 'none',
              }}
              onMouseOver={e => {
                e.currentTarget.style.background = 'linear-gradient(90deg, #40a9ff 0%, #1890ff 100%)';
                e.currentTarget.style.transform = 'scale(1.04)';
              }}
              onMouseOut={e => {
                e.currentTarget.style.background = 'linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)';
                e.currentTarget.style.transform = 'scale(1)';
              }}
          >
            上传文件
          </button>

          {showUserInfo && userInfo ? (null) : (
              <div style={{ textAlign: 'center', marginTop: 80, color: '#888' }}>
                <span>正在自动登录，请稍候...</span>
              </div>
          )}
        </div>
      </div>
  );
}

export default App;
