/**
 * Copyright (c) 2025 TDCAT.CN
 */

import router from '@ohos.router';
import logManager, { LogCategory, LogEventType } from '../common/logtext';
import settingsService from '../common/SettingsService';
import { DatabaseService } from '../common/DatabaseService';
import promptAction from '@ohos.promptAction';
import common from '@ohos.app.ability.common';
import fileIo from '@ohos.file.fs';

@Entry
@Component
@Preview
struct Login {
  @State message: string = '智能教室管理系统';
  @State username: string = ''; // 用户名
  @State password: string = ''; // 密码
  @State isLoading: boolean = false; // 加载状态
  @State errorMessage: string = ''; // 错误信息
  @State isAgreementChecked: boolean = false; // 是否同意条款
  @State isRememberPassword: boolean = false; // 是否记住密码
  
  // 获取数据库服务实例
  private dbService: DatabaseService = DatabaseService.getInstance();
  private userpassFilePath: string = '';
  
  // 登录验证方法
  private async handleLogin(): Promise<void> {
    this.isLoading = true;
    this.errorMessage = '';
    
    // 用户名不能为空
    if (!this.username || this.username.trim() === '') {
      this.errorMessage = '请输入账号';
      this.isLoading = false;
      return;
    }
    
    // 密码不能为空
    if (!this.password || this.password.trim() === '') {
      this.errorMessage = '请输入密码';
      this.isLoading = false;
      return;
    }
    
    // 必须同意条款才能登录
    if (!this.isAgreementChecked) {
      this.errorMessage = '请阅读并同意相关条款';
      this.isLoading = false;
      return;
    }
    
    try {
      // 使用异步验证方法
      const isValid = await this.dbService.validateUser(this.username, this.password);
      
      if (isValid) {
        // 设置当前用户
        settingsService.setCurrentAccount(this.username);
        
        // 如果勾选了记住密码，保存用户名密码到文件
        if (this.isRememberPassword) {
          this.saveUserCredentials();
        }
        
        // 记录登录日志
        logManager.info(LogCategory.USER, LogEventType.USER_LOGIN, `User logged in: ${this.username}`);
        
        // 跳转到过渡页面
        router.replaceUrl({
          //url: 'pages/TransitionPage'
          //取消过渡动画
          url: 'pages/HomePage'
        });
      } else {
        this.errorMessage = '账号或密码错误';
        logManager.info(LogCategory.USER, LogEventType.USER_LOGIN_FAIL, `Login failed: ${this.username}`);
      }
    } catch {
      this.errorMessage = '登录失败，请稍后重试';
      logManager.info(LogCategory.USER, LogEventType.USER_LOGIN_FAIL, '登录过程中出现错误');
    } finally {
      this.isLoading = false;
    }
  }

  // 保存用户凭证到文件
  private saveUserCredentials(): void {
    try {
      const credentials: string = JSON.stringify({
        username: this.username,
        password: this.password
      });
      
      // 写入文件前确保文件存在
      this.ensureFileExists();
      
      // 写入文件
      try {
        const file = fileIo.openSync(this.userpassFilePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
        
        // 将字符串转换为字节数组并写入
        const buffer = new ArrayBuffer(credentials.length * 2);
        const dataView = new DataView(buffer);
        for (let i = 0; i < credentials.length; i++) {
          dataView.setUint16(i * 2, credentials.charCodeAt(i), true);
        }
        
        fileIo.writeSync(file.fd, buffer);
        fileIo.closeSync(file.fd);
        logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "已保存用户凭证");
      } catch {
        logManager.error(LogCategory.SYSTEM, "写入凭证失败");
      }
    } catch {
      logManager.error(LogCategory.SYSTEM, "保存凭证失败");
    }
  }
  
  // 清除保存的用户凭证
  private clearUserCredentials(): void {
    try {
      if (fileIo.accessSync(this.userpassFilePath)) {
        try {
          // 清空文件内容
          const file = fileIo.openSync(this.userpassFilePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.TRUNC);
          fileIo.closeSync(file.fd);
          logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "已清除用户凭证");
        } catch {
          logManager.error(LogCategory.SYSTEM, "清除凭证失败");
        }
      }
    } catch {
      // 文件不存在，不需要清除
      logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "没有需要清除的凭证文件");
    }
  }
  
  // 读取用户凭证
  private loadUserCredentials(): void {
    try {
      if (fileIo.accessSync(this.userpassFilePath)) {
        try {
          const file = fileIo.openSync(this.userpassFilePath, fileIo.OpenMode.READ_ONLY);
          const fileSize = fileIo.statSync(this.userpassFilePath).size;
          
          if (fileSize > 0) {
            const buf = new ArrayBuffer(fileSize);
            fileIo.readSync(file.fd, buf);
            fileIo.closeSync(file.fd);
            
            // 手动将字节数组转换为字符串
            const dataView = new DataView(buf);
            let content = '';
            
            // 安全地读取字符
            for (let i = 0; i < Math.floor(fileSize / 2); i++) {
              content += String.fromCharCode(dataView.getUint16(i * 2, true));
            }
            
            if (content && content.length > 0) {
              try {
                // 解析JSON内容并添加显式类型标注
                const jsonText: string = content;
                // 使用Record<string, string>类型替代any
                const parsed: Record<string, string> = JSON.parse(jsonText);
                
                if (parsed && typeof parsed === 'object') {
                  // 直接访问并检查属性
                  if (parsed.username !== undefined && typeof parsed.username === 'string') {
                    this.username = parsed.username;
                  }
                  
                  if (parsed.password !== undefined && typeof parsed.password === 'string') {
                    this.password = parsed.password;
                  }
                  
                  this.isRememberPassword = true;
                  logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "已加载保存的凭证");
                }
              } catch {
                logManager.error(LogCategory.SYSTEM, "解析凭证失败");
              }
            } else {
              // 文件存在但内容为空
              logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "凭证文件存在但为空");
            }
          } else {
            fileIo.closeSync(file.fd);
            logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "凭证文件为空");
          }
        } catch {
          logManager.error(LogCategory.SYSTEM, "读取凭证文件失败");
        }
      } else {
        // 文件不存在
        logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "凭证文件不存在");
      }
    } catch {
      // 文件不存在或无法访问
      logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "未找到保存的凭证");
    }
  }
  
  // 检查是否启用记住密码但没有凭据
  private checkRememberPasswordStatus(): void {
    // 当用户勾选记住密码但没有已保存的凭据时显示提示
    if (this.isRememberPassword && (!this.username || !this.password)) {
      promptAction.showToast({
        message: '当前没有保存的密码',
        duration: 2000
      });
    }
  }
  
  // 确保文件存在，不存在则创建
  private ensureFileExists(): void {
    try {
      // 检查文件是否存在
      if (!fileIo.accessSync(this.userpassFilePath)) {
        // 创建空文件
        const file = fileIo.openSync(this.userpassFilePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY);
        fileIo.closeSync(file.fd);
        logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "已创建凭证文件");
      }
    } catch {
      // 文件不存在，创建新文件
      try {
        const file = fileIo.openSync(this.userpassFilePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY);
        fileIo.closeSync(file.fd);
        logManager.info(LogCategory.SYSTEM, LogEventType.SYSTEM_INFO, "已创建凭证文件");
      } catch {
        logManager.error(LogCategory.SYSTEM, "创建凭证文件失败");
      }
    }
  }
  
  build() {
    Stack() {
      // 原有登录页面内容
      Column({space: 20}) { // 增加行间距
        // 顶部标题和图标
        Column() {
          Image($r('app.media.logo'))
            .objectFit(ImageFit.Contain)
            .width('80%')
            .aspectRatio(1.5)
            .margin({ top: 40 })
            .borderRadius(8)

          // Text(this.message)
          //   .fontColor('#333333')
          //   .fontSize(28)
          //   .fontWeight(FontWeight.Bold)
          //   .margin({ top: 20, bottom: 30 })
        }
        .width('100%')
        .alignItems(HorizontalAlign.Center)

        // 登录表单
        Column({ space: 30 }) {
          // 账号输入框
          Column({ space: 8 }) {
            Text("账号")
              .fontSize(16)
              .fontColor('#666666')
              .alignSelf(ItemAlign.Start)
            
            TextInput({ placeholder: '请输入账号' })
              .type(InputType.Normal)
              .placeholderColor('#999999')
              .placeholderFont({ size: 16 })
              .caretColor('#2196F3')
              .width('100%')
              .height(50)
              .fontSize(16)
              .fontColor('#333333')
              .backgroundColor('#F5F5F5')
              .borderRadius(8)
              .padding({ left: 16, right: 16 })
              .onChange((value: string) => {
                this.username = value;
                this.errorMessage = ''; // 清除错误信息
              })
          }
          .width('100%')
          
          // 密码输入框
          Column({ space: 8 }) {
            Text("密码")
              .fontSize(16)
              .fontColor('#666666')
              .alignSelf(ItemAlign.Start)
            
            TextInput({ placeholder: '请输入密码' })
              .type(InputType.Password)
              .placeholderColor('#999999')
              .placeholderFont({ size: 16 })
              .caretColor('#2196F3')
              .width('100%')
              .height(50)
              .fontSize(16)
              .fontColor('#333333')
              .backgroundColor('#F5F5F5')
              .borderRadius(8)
              .padding({ left: 16, right: 16 })
              .onChange((value: string) => {
                this.password = value;
                this.errorMessage = ''; // 清除错误信息
              })
          }
          .width('100%')
          
          // 错误信息提示
          if (this.errorMessage !== '') {
            Text(this.errorMessage)
              .fontSize(14)
              .fontColor('#FF0000')
              .width('100%')
          }
          
          // 记住密码选项
          Row() {
            Checkbox()
              .select(this.isRememberPassword)
              .selectedColor('#2196F3')
              .width(20)
              .height(20)
              .margin({ right: 8 })
              .onChange((value: boolean) => {
                this.isRememberPassword = value;
                if (value) {
                  this.checkRememberPasswordStatus();
                } else if (this.username && this.password) {
                  // 用户取消勾选"记住密码"选项，询问是否清除已保存的密码
                  AlertDialog.show({
                    title: '提示',
                    message: '是否清除已保存的密码？',
                    primaryButton: {
                      value: '取消',
                      action: () => {
                        // 用户取消，恢复勾选状态
                        this.isRememberPassword = true;
                      }
                    },
                    secondaryButton: {
                      value: '确定',
                      action: () => {
                        // 用户确认，清除保存的密码
                        this.clearUserCredentials();
                      }
                    }
                  });
                }
              })
            
            Text('记住密码')
              .fontSize(14)
              .fontColor('#666666')
          }
          .width('100%')
          .margin({ bottom: 16 })
          .alignItems(VerticalAlign.Center)
          
          // 条款同意选项
          Row() {
            Checkbox()
              .select(this.isAgreementChecked)
              .selectedColor('#2196F3')
              .width(20)
              .height(20)
              .margin({ right: 8 })
              .onChange((value: boolean) => {
                this.isAgreementChecked = value;
                this.errorMessage = ''; // 清除错误信息
              })
            
            Text() {
              Span('我已阅读并同意')
                .fontSize(14)
                .fontColor('#666666')
              
              Span('《用户服务协议》')
                .fontSize(14)
                .fontColor('#2196F3')
                .fontWeight(FontWeight.Medium)
                .onClick(() => {
                  router.pushUrl({
                    url: 'pages/agreements/UserAgreement'
                  });
                })
              
              Span('、')
                .fontSize(14)
                .fontColor('#666666')
              
              Span('《隐私政策》')
                .fontSize(14)
                .fontColor('#2196F3')
                .fontWeight(FontWeight.Medium)
                .onClick(() => {
                  router.pushUrl({
                    url: 'pages/agreements/PrivacyPolicy'
                  });
                })
              
              Span('和')
                .fontSize(14)
                .fontColor('#666666')
              
              Span('《数据处理声明》')
                .fontSize(14)
                .fontColor('#2196F3')
                .fontWeight(FontWeight.Medium)
                .onClick(() => {
                  router.pushUrl({
                    url: 'pages/agreements/DataProcessingStatement'
                  });
                })
            }
            .width('90%')
            .textAlign(TextAlign.Start)
          }
          .width('100%')
          .margin({ top: 16, bottom: 16 })
          .alignItems(VerticalAlign.Center)
          
          // 忘记密码和注册按钮
          Row() {
            Text('忘记密码')
              .fontSize(14)
              .fontColor('#2196F3')
              .onClick(() => {
                AlertDialog.show({
                  message:"该功能尚未开发",
                    confirm:{
                    value:"确定",
                      action:()=>{}
                    }
                });
                //跳转忘记密码页面
    /*              router.pushUrl({
                    url: 'pages/forgot-password'
                  });*/
              })
            
            Blank()
            
            Text('注册账号')
              .fontSize(14)
              .fontColor('#2196F3')
              .onClick(() => {
                router.pushUrl({
                  url: 'pages/register'
                });
              })
          }
          .width('100%')
          .justifyContent(FlexAlign.SpaceBetween)
          .margin({ top: 10 })
          
          // 登录按钮
          Button('登录')
            .type(ButtonType.Capsule)
            .width('100%')
            .height(50)
            .fontSize(18)
            .fontWeight(FontWeight.Medium)
            .backgroundColor('#2196F3')
            .onClick(() => {
              this.handleLogin();
            })
            .margin({ top: 20 })
        }
        .width('100%')
        .padding({ left: 30, right: 30 })
      }
      .width('100%')
      .height('100%')
      
      // 浮动测试按钮
      Button({ type: ButtonType.Circle }) {
        Row() {
          Image($r('app.media.ic_test'))
            .width(24)
            .height(24)
            .margin({ right: 4 })
/*          Text('测试')
            .fontSize(16)
            .fontColor('#FFFFFF')*/
        }
      }
      .width(100)
      .height(40)
      .backgroundColor('#2196F3')
      .position({ x: '80%', y: 50 })
      .enabled(!this.isLoading)
      .onClick(() => {
        if (this.isLoading) return;
        this.isLoading = true;
        
        // 使用测试账号直接登录
        this.dbService.validateUser('teststudent21', '123456').then((success: boolean) => {
          if (success) {
            // 设置当前用户
            settingsService.setCurrentAccount('teststudent21');
            // 记录登录成功日志
            logManager.info(LogCategory.USER, LogEventType.USER_LOGIN, `Test login success: teststudent21`);
            // 跳转到主页
            router.pushUrl({
              url: 'pages/HomePage'
            });
          }
        }).catch(() => {
          // 避免使用错误对象，直接记录测试登录失败
          logManager.error(LogCategory.USER, '测试登录失败');
          promptAction.showToast({
            message: '测试登录失败',
            duration: 2000
          });
        }).finally(() => {
          this.isLoading = false;
        });
      })
      .shadow({
        radius: 8,
        color: 'rgba(0, 0, 0, 0.2)',
        offsetX: 2,
        offsetY: 4
      })
      .animation({
        duration: 250,
        curve: Curve.EaseInOut
      })
      .opacity(this.isLoading ? 0.6 : 1)
    }
    .width('100%')
    .height('100%')
  }
  
  // 页面生命周期方法
  onPageShow(): void {
    this.Log_LoginEvent('onPageShow');
  }

  onPageHide(): void {
    this.Log_LoginEvent('onPageHide');
  }

  onBackPress(): void {
    this.Log_LoginEvent('onBackPress');
  }

  aboutToAppear(): void {
    this.Log_LoginEvent('aboutToAppear');
    
    // 获取应用目录中的Userpass.txt文件路径 - 使用应用程序内部文件目录而非resources
    const context = getContext(this) as common.UIAbilityContext;
    this.userpassFilePath = context.filesDir + "/Userpass.txt";
    
    // 加载保存的用户凭证
    this.loadUserCredentials();
    
    // 检查是否有保存的凭据
    setTimeout(() => {
      if (this.isRememberPassword && (!this.username || !this.password)) {
        promptAction.showToast({
          message: '当前没有保存的密码',
          duration: 2000
        });
      }
    }, 500); // 短暂延迟确保加载完成
  }

  aboutToDisappear(): void {
    this.Log_LoginEvent('aboutToDisappear');
  }

  // 通用日志记录方法
  public Log_LoginEvent(eventName: string): void {
    // 根据事件名称选择合适的日志事件类型
    switch (eventName) {
      case 'aboutToAppear':
        logManager.info(LogCategory.USER, LogEventType.PAGE_APPEAR, 'LoginPage');
        break;
      case 'aboutToDisappear':
        logManager.info(LogCategory.USER, LogEventType.PAGE_DISAPPEAR, 'LoginPage');
        break;
      case 'onPageShow':
        logManager.info(LogCategory.USER, LogEventType.PAGE_SHOW, 'LoginPage');
        break;
      case 'onPageHide':
        logManager.info(LogCategory.USER, LogEventType.PAGE_HIDE, 'LoginPage');
        break;
      case 'onBackPress':
        logManager.info(LogCategory.USER, LogEventType.PAGE_BACK, 'LoginPage');
        break;
      default:
        logManager.info(LogCategory.USER, LogEventType.SYSTEM_INFO, `LoginPage: ${eventName}`);
    }
  }
}

export { Login }

