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

import router from '@ohos.router';
import prompt from '@ohos.promptAction';
import { DatabaseService, RegisterUserData } from '../common/DatabaseService';
import logManager, { LogCategory, LogEventType } from '../common/logtext';

@Entry
@Component
struct Register {
  @State message: string = '注册新账号';
  @State username: string = ''; // 账号
  @State password: string = ''; // 密码
  @State confirmPassword: string = ''; // 确认密码
  @State nickname: string = ''; // 昵称
  @State email: string = ''; // 邮箱
  @State phone: string = ''; // 手机号
  @State photo: string = ''; // 用户照片
  @State isLoading: boolean = false; // 加载状态
  @State errorMessage: string = ''; // 错误信息
  @State isAgreementChecked: boolean = false; // 是否同意条款
  
  // 获取数据库服务实例
  private dbService: DatabaseService = DatabaseService.getInstance();
  
  // 验证输入
  private validateInput(): boolean {
    // 验证账号
    if (!this.username || this.username.trim() === '') {
      this.errorMessage = '请输入账号';
      return false;
    }
    if (this.username.length < 4) {
      this.errorMessage = '账号长度不能少于4位';
      return false;
    }
    
    // 验证密码
    if (!this.password || this.password.trim() === '') {
      this.errorMessage = '请输入密码';
      return false;
    }
    if (this.password.length < 6) {
      this.errorMessage = '密码长度不能少于6位';
      return false;
    }
    
    // 验证确认密码
    if (this.password !== this.confirmPassword) {
      this.errorMessage = '两次输入的密码不一致';
      return false;
    }
    
    // 验证邮箱
    if (!this.email || this.email.trim() === '') {
      this.errorMessage = '请输入邮箱';
      return false;
    }
    if (!this.dbService.validateEmailFormat(this.email)) {
      this.errorMessage = '请输入有效的邮箱地址';
      return false;
    }
    
    // 验证手机号（如果填写）
    if (this.phone && !/^1[3-9]\d{9}$/.test(this.phone)) {
      this.errorMessage = '请输入有效的手机号';
      return false;
    }
    
    // 验证条款
    if (!this.isAgreementChecked) {
      this.errorMessage = '请阅读并同意相关条款';
      return false;
    }
    
    return true;
  }
  
  // 处理注册
  private async handleRegister(): Promise<void> {
    if (!this.validateInput()) {
      return;
    }
    
    this.isLoading = true;
    this.errorMessage = '';
    
    try {
      // 准备注册数据
      const userData: RegisterUserData = {
        account: this.username,
        password: this.password,
        nickname: this.nickname || this.username,
        email: this.email,
        phone: this.phone,
        photo: this.photo || 'http://139.155.155.67:2342/images/default_avatar.png'
      };
      
      // 发送注册请求
      const success = await this.dbService.registerUser(userData);
      if (success) {
        logManager.info(LogCategory.USER, LogEventType.USER_REGISTER, `User registered: ${this.username}`);
        prompt.showToast({
          message: '注册成功',
          duration: 2000
        });
        router.back();
      } else {
        this.errorMessage = '注册失败，请稍后重试';
      }
    } catch {
      this.errorMessage = '注册失败，请稍后重试';
      logManager.error(LogCategory.USER, 'Register error occurred');
    } finally {
      this.isLoading = false;
    }
  }
  
  build() {
    Column() {
      // 顶部导航栏
      Row() {
        Image($r('app.media.back'))
          .width(24)
          .height(24)
          .margin({ right: 16 })
          .onClick(() => {
            router.back();
          })
        
        Text(this.message)
          .fontSize(24)
          .fontWeight(FontWeight.Bold)
          .fontColor('#333333')
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .padding({ top: 16, bottom: 16, left: 16, right: 16 })

      // 主滚动内容
      Scroll() {
        Column({ space: 20 }) {
          // 用户照片上传区域
          Column() {
            Image(this.photo || $r('app.media.default_avatar'))
              .width(100)
              .height(100)
              .borderRadius(50)
              .margin({ top: 10, bottom: 10 })
              .onClick(() => {
                prompt.showToast({
                  message: '照片上传功能开发中',
                  duration: 2000
                });
              })
            
            Text("点击更换头像")
              .fontSize(14)
              .fontColor('#666666')
          }
          .width('100%')
          .justifyContent(FlexAlign.Center)
          .alignItems(HorizontalAlign.Center)
          
          // 表单区域
          Column({ space: 16 }) {
            // 账号输入框
            Column({ space: 4 }) {
              Row() {
                Text("账号")
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                Text("*")
                  .fontSize(16)
                  .fontColor('#FF0000')
              }
              .width('100%')
              .justifyContent(FlexAlign.Start)
              
              TextInput({ placeholder: '请输入账号（至少4位）' })
                .type(InputType.Normal)
                .placeholderColor('#BBBBBB')
                .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: 4 }) {
              Row() {
                Text("密码")
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                Text("*")
                  .fontSize(16)
                  .fontColor('#FF0000')
              }
              .width('100%')
              .justifyContent(FlexAlign.Start)
              
              TextInput({ placeholder: '请输入密码（至少6位）' })
                .type(InputType.Password)
                .placeholderColor('#BBBBBB')
                .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%')
            
            // 确认密码输入框
            Column({ space: 4 }) {
              Row() {
                Text("确认密码")
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                Text("*")
                  .fontSize(16)
                  .fontColor('#FF0000')
              }
              .width('100%')
              .justifyContent(FlexAlign.Start)
              
              TextInput({ placeholder: '请再次输入密码' })
                .type(InputType.Password)
                .placeholderColor('#BBBBBB')
                .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.confirmPassword = value;
                  this.errorMessage = '';
                })
            }
            .width('100%')
            
            // 昵称输入框
            Column({ space: 4 }) {
              Row() {
                Text("昵称")
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                Text("（选填）")
                  .fontSize(16)
                  .fontColor('#666666')
              }
              .width('100%')
              .justifyContent(FlexAlign.Start)
              
              TextInput({ placeholder: '请输入昵称' })
                .type(InputType.Normal)
                .placeholderColor('#BBBBBB')
                .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.nickname = value;
                  this.errorMessage = '';
                })
            }
            .width('100%')

            // 邮箱输入框
            Column({ space: 4 }) {
              Row() {
                Text("邮箱")
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                Text("*")
                  .fontSize(16)
                  .fontColor('#FF0000')
              }
              .width('100%')
              .justifyContent(FlexAlign.Start)
              
              TextInput({ placeholder: '请输入邮箱' })
                .type(InputType.Email)
                .placeholderColor('#BBBBBB')
                .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.email = value;
                  this.errorMessage = '';
                })
            }
            .width('100%')
            
            // 手机号输入框
            Column({ space: 4 }) {
              Row() {
                Text("手机号")
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                Text("（选填）")
                  .fontSize(16)
                  .fontColor('#666666')
              }
              .width('100%')
              .justifyContent(FlexAlign.Start)
              
              TextInput({ placeholder: '请输入手机号' })
                .type(InputType.Number)
                .placeholderColor('#BBBBBB')
                .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.phone = value;
                  this.errorMessage = '';
                })
            }
            .width('100%')
            
            // 错误信息提示
            if (this.errorMessage !== '') {
              Text(this.errorMessage)
                .fontSize(14)
                .fontColor('#FF0000')
                .width('100%')
                .backgroundColor('#FFF0F0')
                .padding(8)
                .borderRadius(4)
            }
            
            // 条款同意选项
            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%')
            .alignItems(VerticalAlign.Center)
            .margin({ top: 10, bottom: 10 })
            
            // 提交按钮
            Button() {
              if (this.isLoading) {
                Row() {
                  LoadingProgress()
                    .width(24)
                    .height(24)
                    .color(Color.White)
                  Text('注册中...')
                    .fontSize(18)
                    .fontWeight(FontWeight.Medium)
                    .fontColor(Color.White)
                    .margin({ left: 12 })
                }
              } else {
                Text('注册账号')
                  .fontSize(18)
                  .fontWeight(FontWeight.Medium)
                  .fontColor(Color.White)
              }
            }
            .type(ButtonType.Capsule)
            .width('100%')
            .height(50)
            .backgroundColor('#2196F3')
            .enabled(!this.isLoading)
            .stateEffect(true)
            .onClick(() => {
              this.handleRegister();
            })
            .margin({ top: 10, bottom: 20 })
          }
          .width('100%')
          .padding(16)
          .backgroundColor(Color.White)
          .borderRadius(16)
        }
        .width('100%')
        .padding({ left: 16, right: 16, bottom: 30 })
      }
      .width('100%')
      .layoutWeight(1)
      .scrollBar(BarState.Off)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F0F5FF')
  }
} 