import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: false,
})
export class Tab2Page {
  taskList: any[] = [];
  currentUser: any = {};
  currentStatus: string = 'inProgress';

  constructor(private router: Router) {
    this.initUser();
    this.loadTasks('inProgress');
  }

  async initUser() {
    const user = new CloudUser();
    const currentUser = await user.current();
    this.currentUser = {
      username: currentUser?.get('username') || '邻助星',
      avatar: currentUser?.get('avatar') || 'assets/images/1.jpg'
    };
  }

  navigateTo(status: string) {
    this.currentStatus = status;
    this.loadTasks(status);
    this.router.navigate(['/tab2', status]);
  }

  navigateToCreate() {
    this.router.navigate(['/create-request']); // 请根据实际路由调整
  }

  async loadTasks(status: string) {
    if (status === 'inProgress') {
        let query = new CloudQuery("Inprogress");
        const results = await query.find();
        
        this.taskList = results.map(item => ({
            id: item.id,
            userName: '邻助星',  // 固定用户名
            userAvatar: this.currentUser.avatar,
            description: item.get('description'),
            points: item.get('points'),
            time: item.get('time') || item.createdAt,
            type: item.get('type')
        }));
    } else if (status === 'completed') {
        let query = new CloudQuery("Completed");
        const results = await query.find();
        
        this.taskList = results.map(item => ({
            id: item.id,
            userName: '邻助星',  // 固定用户名
            userAvatar: this.currentUser.avatar,
            description: item.get('description'),
            points: item.get('points'),
            startTime: item.get('startTime'),
            endTime: item.get('endTime'),
            type: item.get('type')
        }));
    } else if (status === 'pending') {
        let query = new CloudQuery("PendingRequests");
        const results = await query.find();
        
        this.taskList = results.map(item => ({
            id: item.id,
            userName: this.currentUser.username || '',
            userAvatar: this.currentUser.avatar || '',
            title: item.get('title') || '',
            description: `${item.get('title') || ''}\n${item.get('topic') || ''}`,
            points: item.get('points') || 0,
            time: item.get('time') || item.createdAt || '',
            type: item.get('type') || 'normal',
            topic: item.get('topic') || '',
            status: item.get('type') === 'urgent' ? '紧急' : '普通'
        }));
    } else {
        this.taskList = [];
    }
}

  importTestData = async () => {
    const testData = [
      {
        userName: '张阿姨',
        userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
        description: '需要帮忙修理水龙头',
        type: 'normal',
        time: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)),
        points: 10,
        status: 'pending'
      },
      {
        userName: '李大爷',
        userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
        description: '求购降压药',
        type: 'emergency',
        time: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)),
        points: 20,
        status: 'completed'
      },
      {
        userName: '王阿姨',
        userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
        description: '需要家政清洁',
        type: 'normal',
        time: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)),
        points: 15,
        status: 'inProgress'
      }
    ];
    
    for (const data of testData) {
      const obj = new CloudObject("Inprogress");
      obj.set(data);
      await obj.save();
    }
    
    this.loadTasks(this.currentStatus);
  }

  completeTask = async (task: any) => {
    try {
      const obj = new CloudObject("Inprogress");
      obj.id = task.id;
      await obj.destroy();
  
      const completedTask = new CloudObject("Completed");
      completedTask.set({
        userName: task.userName,
        userAvatar: task.userAvatar,
        description: task.description,
        points: task.points,
        startTime: task.time,
        endTime: new Date(),
        type: task.type
      });
      await completedTask.save();
  
      this.loadTasks('inProgress');
    } catch (error) {
      console.error('完成任务出错:', error);
    }
  }

  startChat(item: any) {
    this.router.navigate(['/chat', item.userName]); // 修改为直接传递用户名参数
  }
}

  


