import { Component, OnInit } from '@angular/core';
import { CloudObject, CloudQuery,CloudUser } from 'src/lib/ncloud';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-thanks-cloud',
  templateUrl: './thanks-cloud.page.html',
  styleUrls: ['./thanks-cloud.page.scss'],
  standalone: false,
})
export class ThanksCloudPage implements OnInit {

  constructor(
    //private parseService: ParseService
    private alertController: AlertController
  ) { 
    this.checkLoginAndLoadData();
  }
  currentUser: CloudUser | null = null;
  thanksList: CloudObject[]=[];

  async loadThanksType(){

    let query=new CloudQuery("ThanksType")
    this.thanksList=await query.find();
  } 

  ngOnInit() {
    //this.checkLoginAndLoadData();
  }

    async checkLoginAndLoadData() {
    // 获取当前用户
    this.currentUser = await CloudUser.current();
    if (this.currentUser) {
      await this.loadThanksList();
    } else {
      // 如果用户未登录，可以跳转到登录页面或显示登录提示
      console.warn('用户未登录');
      this.showLoginAlert();
    }
  }

  async showLoginAlert() {
    const alert = await this.alertController.create({
      header: '未登录',
      message: '请先登录才能查看和创建感恩清单',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '去登录',
          handler: () => {
            // 这里可以导航到登录页面
            // this.router.navigate(['/login']);
          }
        }
      ]
    });
    await alert.present();
  }

  async loadThanksList() {
    if (!this.currentUser) return;

    // 创建查询，只获取当前用户的感恩清单
    let query = new CloudQuery("ThanksType");
    query.equalTo("user", {
      __type: "Pointer",
      className: "_User",
      objectId: this.currentUser.id
    });
    query.include("user"); // 包含用户信息
    
    this.thanksList = await query.find();
  }
  
  async importThanks(){
  
  }
  
  async addNewThanks(){
 
    if (!this.currentUser) {
      this.showLoginAlert();
      return;
    }
      const alert = await this.alertController.create({
      header: '添加感恩清单',
      inputs: [
        {
          name: 'content',
          type: 'textarea',
          placeholder: '感恩内容'
        },
        {
          name: 'weather',
          type: 'text',
          placeholder: '天气 (如: 晴)'
        },
        {
          name: 'mood',
          type: 'text',
          placeholder: '心情表情 (如: 😊)'
        },
        {
          name: 'tags',
          type: 'text',
          placeholder: '标签 (用逗号分隔, 如: 情感分析,生活仪式感)'
        },
        {
          name: 'reflection',
          type: 'textarea',
          placeholder: '反思记录'
        },
        {
          name: 'actionStep',
          type: 'textarea',
          placeholder: '行动计划'
        },
        {
          name: 'emotionalImpact',
          type: 'text',
          placeholder: '情感影响 (如: 幸福感 + 2)'
        },
        {
          name: 'emotionalJournal',
          type: 'textarea',
          placeholder: '情绪日记'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
          return true; // 明确返回 true 表示取消操作
        }
        },
        {
          text: '保存',
          handler: async (data) => {
            if (!data.content) {
              return false; // 阻止关闭
            }
            
            // 获取当前日期时间信息
            const now = new Date();
            const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()];
            const date = now.getDate();
            const hours = now.getHours().toString().padStart(2, '0');
            const minutes = now.getMinutes().toString().padStart(2, '0');
            const time = `${hours}:${minutes}`;
            
            // 处理标签
            const tags = data.tags ? data.tags.split(',').map((tag: string) => tag.trim()) : [];
            
            // 创建新的感恩清单对象
            const newThanks = new CloudObject("ThanksType");
            newThanks.set({
              Tid: Date.now(), // 使用时间戳作为临时ID
              date: date,
              weekday: weekday,
              time: time,
              content: data.content,
              weather: data.weather || '晴',
              mood: data.mood || '😊',
              tags: tags,
              reflection: data.reflection || '',
              actionStep: data.actionStep || '',
              emotionalImpact: data.emotionalImpact || '',
              emotionalJournal: data.emotionalJournal || '',
              // 关联当前用户
              user: {
                __type: "Pointer",
                className: "_User",
                objectId: this.currentUser?.id
              }
            });
            
            try {
              // 保存到数据库
              await newThanks.save();
              
              // 重新加载列表
              await this.loadThanksType();
              
              // 显示成功提示
              const successAlert = await this.alertController.create({
                header: '成功',
                message: '感恩清单已添加',
                buttons: ['确定']
              });
              await successAlert.present();
              
            } catch (error) {
              console.error('保存失败:', error);
              const errorAlert = await this.alertController.create({
                header: '错误',
                message: '保存失败，请重试',
                buttons: ['确定']
              });
              await errorAlert.present();
            }
            return true; // 明确返回 true 表示操作完成
          }
        }
      ]
    });

    await alert.present();
  }  
}
