import { hilog } from '@kit.PerformanceAnalysisKit';
import prompt from '@ohos.promptAction';
import http from '@ohos.net.http';

// User model for storing user information from database
export class UserModel {
  account: string = '';
  nickname: string = '';
  email: string = '';
  phone: string = '';
  photo: string = '';
  category: string = '';
  
  constructor(account: string = '', 
              nickname: string = '', 
              email: string = '', 
              phone: string = '',
              photo: string = '',
              category: string = '') {
    this.account = account;
    this.nickname = nickname;
    this.email = email;
    this.phone = phone;
    this.photo = photo || 'http://139.155.155.67:2342/images/default_avatar.png'; // Default photo URL
    this.category = category;
  }
}

// API响应接口定义
export interface ApiResponse {
  success: boolean;
  message?: string;
  user?: UserInfo;
}

// User info returned from API
export interface UserInfo {
  account: string;
  nickname: string;
  email: string;
  phone: string;
  photo?: string;
  category: string;
}

// API服务配置
export interface ApiConfig {
  baseUrl: string;
  timeout: number;
}

// 定义API服务配置
const API_CONFIG: ApiConfig = {
  // 修改为用户实际使用的服务器地址
  baseUrl: 'http://139.155.155.67:2342/api',
  timeout: 10000  // 10秒超时
};

// 修正JSON响应类型处理
export type JsonResponse = string | object | ArrayBuffer;

// 真实API实现 - 连接到后端服务
export class DatabaseService {
  private static instance: DatabaseService;
  // 缓存用户数据，减少API调用
  private userCache: Map<string, UserModel> = new Map();
  // 缓存验证结果
  private authCache: Map<string, boolean> = new Map(); 
  
  // Callbacks for user data changes
  private userDataChangeCallbacks: (() => void)[] = [];
  
  private constructor() {
    // 初始化缓存
    hilog.info(0, 'ClassMG', 'Database Service Initialized');
  }
  
  public static getInstance(): DatabaseService {
    if (!DatabaseService.instance) {
      DatabaseService.instance = new DatabaseService();
    }
    return DatabaseService.instance;
  }
  
  // 创建HTTP请求客户端
  private createHttpClient(): http.HttpRequest {
    let httpRequest = http.createHttp();
    httpRequest.on('headersReceive', (header) => {
      hilog.debug(0, 'ClassMG', `Headers received: ${JSON.stringify(header)}`);
    });
    return httpRequest;
  }
  
  // 执行登录验证
  public async validateUser(account: string, password: string): Promise<boolean> {
    try {
      // 生成缓存键
      const cacheKey = `${account}:${password}`;
      
      // 检查缓存
      if (this.authCache.has(cacheKey)) {
        const cachedResult = this.authCache.get(cacheKey);
        return cachedResult === true; // 确保返回布尔值
      }
      
      // 创建HTTP客户端
      const httpRequest = this.createHttpClient();
      
      // 准备登录数据
      let loginData = {} as Record<string, string>;
      loginData.account = account;
      loginData.password = password;
      
      // 发送登录请求
      const response = await httpRequest.request(
        `${API_CONFIG.baseUrl}/login`,
        {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json'
          },
          extraData: JSON.stringify(loginData),
          connectTimeout: API_CONFIG.timeout,
          readTimeout: API_CONFIG.timeout
        }
      );
      
      // 释放HTTP客户端
      httpRequest.destroy();
      
      // 检查响应
      if (response.responseCode === 200) {
        // 使用显式类型转换处理JSON结果
        const jsonString: string = response.result ? response.result.toString() : '{}';
        try {
          const result: ApiResponse = JSON.parse(jsonString) as ApiResponse;
          
          // 缓存结果
          const isValid = result.success === true;
          this.authCache.set(cacheKey, isValid);
          
          // 如果登录成功且有用户数据，缓存用户信息
          if (isValid && result.user) {
            const user = new UserModel(
              result.user.account,
              result.user.nickname,
              result.user.email,
              result.user.phone,
              result.user.photo,
              result.user.category
            );
            this.userCache.set(account, user);
          }
          
          return isValid;
        } catch (parseError) {
          const errorMsg: string = parseError instanceof Error ? parseError.message : String(parseError);
          hilog.error(0, 'ClassMG', `Error parsing JSON response: ${errorMsg}`);
        }
      }
      
      // 默认返回false
      return false;
    } catch (error) {
      hilog.error(0, 'ClassMG', `Error validating user: ${error instanceof Error ? error.message : String(error)}`);
      
      // 临时降级到模拟验证 - 仅用于开发/测试
      if (account === '2' || account === '9222' || account === '0') {
        return password === '1';
      }
      
      return false;
    }
  }
  
  // 获取用户类别
  public getUserCategory(account: string): string {
    // 检查缓存
    if (this.userCache.has(account)) {
      const user = this.userCache.get(account);
      return user ? user.category : '';
    }
    
    // 降级逻辑 - 当API不可用时
    if (account.includes('2')) {
      return 'student';
    } else if (account.includes('0')) {
      return 'teacher';
    }
    
    return '';
  }
  
  // 获取用户昵称
  public getUserNickname(account: string): string {
    // 检查缓存
    if (this.userCache.has(account)) {
      const user = this.userCache.get(account);
      return user ? user.nickname : '';
    }
    
    // 默认值 - 仅用于开发/测试
    if (account === '2') return '张三';
    if (account === '9222') return '李华';
    if (account === '0') return '教师demo';
    
    return '';
  }
  
  // 异步获取用户信息
  public async getUserByAccountAsync(account: string): Promise<UserModel | null> {
    try {
      // 检查缓存
      if (this.userCache.has(account)) {
        const cachedUser = this.userCache.get(account);
        return cachedUser || null;
      }
      
      // 创建HTTP客户端
      const httpRequest = this.createHttpClient();
      
      // 发送获取用户信息请求
      const response = await httpRequest.request(
        `${API_CONFIG.baseUrl}/user/${account}`,
        {
          method: http.RequestMethod.GET,
          connectTimeout: API_CONFIG.timeout,
          readTimeout: API_CONFIG.timeout
        }
      );
      
      // 释放HTTP客户端
      httpRequest.destroy();
      
      // 检查响应
      if (response.responseCode === 200) {
        // 使用显式类型转换处理JSON结果
        const jsonString: string = response.result ? response.result.toString() : '{}';
        try {
          const result: ApiResponse = JSON.parse(jsonString) as ApiResponse;
          
          if (result.success && result.user) {
            const user = new UserModel(
              result.user.account,
              result.user.nickname,
              result.user.email,
              result.user.phone,
              result.user.photo,
              result.user.category
            );
            
            // 更新缓存
            this.userCache.set(account, user);
            
            return user;
          }
        } catch (parseError) {
          const errorMsg: string = parseError instanceof Error ? parseError.message : String(parseError);
          hilog.error(0, 'ClassMG', `Error parsing JSON response: ${errorMsg}`);
        }
      }
      
      return null;
    } catch (error) {
      hilog.error(0, 'ClassMG', `Error getting user: ${error instanceof Error ? error.message : String(error)}`);
      
      // 降级到模拟数据 - 仅用于开发/测试
      if (account === '2') {
        return new UserModel('2', '张三', 'student@qq.com', '17267383831', '', 'student');
      } else if (account === '9222') {
        return new UserModel('9222', '李华', 'student123@qq.com', '12345678901', '', 'student');
      } else if (account === '0') {
        return new UserModel('0', '教师demo', 'teach@qq.com', '', '', 'teacher');
      }
      
      return null;
    }
  }
  
  // 为了兼容性保留的同步方法 - 使用缓存
  public getUserByAccount(account: string): UserModel | null {
    // 检查缓存
    if (this.userCache.has(account)) {
      const cachedUser = this.userCache.get(account);
      return cachedUser || null;
    }
    
    // 如果缓存中没有，返回默认模拟数据
    if (account === '2') {
      return new UserModel('2', '张三', 'student@qq.com', '17267383831', '', 'student');
    } else if (account === '9222') {
      return new UserModel('9222', '李华', 'student123@qq.com', '12345678901', '', 'student');
    } else if (account === '0') {
      return new UserModel('0', '教师demo', 'teach@qq.com', '', '', 'teacher');
    }
    
    // 触发异步加载并返回null
    this.getUserByAccountAsync(account)
      .then((user: UserModel | null) => {
        if (user) {
          this.notifyUserDataChange();
        }
      })
      .catch((error: Error | string | Object) => {
        const errorMsg: string = error instanceof Error ? error.message : String(error);
        hilog.error(0, 'ClassMG', `Error in async user fetch: ${errorMsg}`);
      });
    
    return null;
  }
  
  // 更新用户邮箱 - 连接API
  public async updateUserEmail(account: string, newEmail: string): Promise<boolean> {
    try {
      // 验证邮箱格式
      if (!this.validateEmailFormat(newEmail)) {
        return false;
      }
      
      // 创建HTTP客户端
      const httpRequest = this.createHttpClient();
      
      // 准备更新数据
      let updateData = {} as Record<string, string>;
      updateData.email = newEmail;
      
      // 发送更新请求
      const response = await httpRequest.request(
        `${API_CONFIG.baseUrl}/user/${account}/email`,
        {
          method: http.RequestMethod.PUT,
          header: {
            'Content-Type': 'application/json'
          },
          extraData: JSON.stringify(updateData),
          connectTimeout: API_CONFIG.timeout,
          readTimeout: API_CONFIG.timeout
        }
      );
      
      // 释放HTTP客户端
      httpRequest.destroy();
      
      // 检查响应
      if (response.responseCode === 200) {
        // 使用显式类型转换处理JSON结果
        const jsonString: string = response.result ? response.result.toString() : '{}';
        try {
          const result: ApiResponse = JSON.parse(jsonString) as ApiResponse;
          
          if (result.success) {
            // 更新本地缓存
            if (this.userCache.has(account)) {
              const user = this.userCache.get(account);
              if (user) {
                user.email = newEmail;
                this.userCache.set(account, user);
              }
            }
            
            // 通知更新
            this.notifyUserDataChange();
            
            return true;
          }
        } catch (parseError) {
          const errorMsg: string = parseError instanceof Error ? parseError.message : String(parseError);
          hilog.error(0, 'ClassMG', `Error parsing JSON response: ${errorMsg}`);
        }
      }
      
      return false;
    } catch (error) {
      const errorMessage: string = error instanceof Error ? error.message : String(error);
      hilog.error(0, 'ClassMG', `Error updating user email: ${errorMessage}`);
      
      // 降级到本地更新 - 仅用于开发/测试
      if (this.userCache.has(account)) {
        const user = this.userCache.get(account);
        if (user) {
          user.email = newEmail;
          this.userCache.set(account, user);
          this.notifyUserDataChange();
          return true;
        }
      }
      
      return false;
    }
  }
  
  // 注册数据变化回调
  public registerUserDataChangeCallback(callback: () => void): void {
    this.userDataChangeCallbacks.push(callback);
  }
  
  // 通知所有回调
  private notifyUserDataChange(): void {
    this.userDataChangeCallbacks.forEach(callback => {
      callback();
    });
  }
  
  // 验证邮箱格式
  public validateEmailFormat(email: string): boolean {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }
  
  // 清除缓存
  public clearCache(): void {
    this.userCache.clear();
    this.authCache.clear();
  }
} 