import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { ModalController } from '@ionic/angular';
import { CloudObject, CloudQuery } from '../../lib/ncloud';
import { UserDashboardPage } from './user-dashboard.page';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-upload-qualification',
  templateUrl: 'upload-qualification.page.html',
  styleUrls: ['upload-qualification.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule]
})
export class UploadQualificationPage {
  qualificationTypes = ['家政', '看护', '管道', '水电', '家教'];
  selectedType = '';
  certFile: File | null = null;
  certTime = '';

  constructor(
    public router: Router, // 改为 public 以便模板访问
    private modalCtrl: ModalController
  ) {}

  onFileChange(event: any) {
    this.certFile = event.target.files[0];
  }

  async submitQualification() {
    if (!this.selectedType || !this.certTime) {
      alert('请选择资质类型并输入证书获取时间');
      return;
    }

    const qualification = {
      type: this.selectedType,
      uploadTime: new Date().toISOString().split('T')[0],
      certTime: this.certTime,
      status: this.certFile ? '已通过' : '未上传' // 根据是否上传文件设置状态
    };

    try {
      const qualObj = new CloudObject('Qualification');
      await qualObj.set(qualification);
      await qualObj.save();
      
      // 使用query重新获取最新数据
      const query = new CloudQuery('Qualification');
      const updatedQualifications = await query.find();
      
      // 传递整个更新后的列表
      this.router.navigate(['/tabs/tab5/user-dashboard'], {
        state: { qualifications: updatedQualifications }
      });
    } catch (error) {
      console.error('保存失败:', error);
      alert('提交失败，请重试');
    }
  }

  goBack() {
    this.router.navigate(['/tabs/tab5/user-dashboard']);
  }
}