import { Component } from '@angular/core';
import { CloudObject, CloudQuery, CloudUser } from '../../lib/ncloud';
import { Router } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { ModalController } from '@ionic/angular'; // 导入 ModalController
import { EditProfileComponent } from './edit-profile.component'; // 假设编辑资料组件名为 EditProfileComponent
import { AlertController } from '@ionic/angular';
import { UploadQualificationPage } from './upload-qualification.page';

@Component({
  selector: 'app-user-dashboard',
  templateUrl: 'user-dashboard.page.html',
  styleUrls: ['user-dashboard.page.scss'],
  imports: [IonicModule, CommonModule],
  standalone: true 
})
export class UserDashboardPage {
  user = new CloudUser();
  currentUser: any = {
    data: {
      avatar: 'assets/images/1.jpg' // 使用相对路径
    }
  };
     
  // 修改为CloudObject数组类型
  qualification: CloudObject[] = [];

  constructor(
    private router: Router, 
    private modalCtrl: ModalController,
    private alertCtrl: AlertController
  ) {
    this.getCurrentUser();
  }

  async getCurrentUser() {
    this.currentUser = await this.user.current();
    // 确保用户有默认头像
    if(!this.currentUser.data.avatar) {
      this.currentUser.data.avatar = 'assets/images/1.jpg';
    }
    const query = new CloudQuery('Qualification');
    this.qualification = await query.find();
  }

  async logout() {
    const success = await this.user.logout();
    if (success) {
      this.router.navigate(['/tabs/tab5']); 
    }
  }

  async goToEditProfile() {
    const modal = await this.modalCtrl.create({
      component: EditProfileComponent,
      componentProps: {
        currentUser: this.currentUser
      }
    });

    modal.onDidDismiss().then(async (data) => {
      if (data.data) {
        // 更新用户信息
        this.user.set(data.data);
        await this.user.save();
        this.currentUser = await this.user.current();
      }
    });

    return await modal.present();
  }

  async ngOnInit() {
    const query = new CloudQuery('Qualification');
    this.qualification = await query.find();
    console.log('从数据库加载的资质数据:', this.qualification); // 添加调试日志
  }

  goToUploadQualification() {
    this.router.navigate(['/tabs/tab5/upload-qualification']);
  }

  async uploadAvatar() {
    if (!this.user.sessionToken) {
      alert('请先登录');
      return;
    }
  
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    
    input.onchange = async (e: any) => {
      const file = e.target.files[0];
      if (file) {
        try {
          const formData = new FormData();
          formData.append('file', file);
          
          // 添加文件名参数
          const response = await fetch(`http://dev.fmode.cn:1337/parse/files/${file.name}`, {
            method: 'POST',
            headers: {
              'X-Parse-Application-Id': 'dev',
              'X-Parse-Session-Token': this.user.sessionToken as string
            },
            body: file  // 直接上传文件对象
          });
          
          if (!response.ok) {
            throw new Error(`上传失败: ${response.status}`);
          }
          
          const result = await response.json();
          if (result.url) {
            // 更新用户头像URL
            this.currentUser.data.avatar = result.url;
            this.user.set({ avatar: result.url });
            await this.user.save();
            this.currentUser = await this.user.current();
          }
        } catch (error) {
          console.error('上传头像失败:', error);
          let errorMessage = '上传失败';
          if (error instanceof Error) {
            errorMessage += `: ${error.message}`;
          }
          alert(errorMessage);
        }
      }
    };
    input.click();
  }

  goToAIAgent() {
    this.router.navigate(['/ai-agent']);
  }
  
  async showWithdrawAlert() {
    const alert = await this.alertCtrl.create({
      header: '提示',
      message: '暂未开放提现通道',
      buttons: ['确定']
    });
    await alert.present();
  }
}