import { Component, OnInit } from '@angular/core';
import { AlertController, NavController } from '@ionic/angular';
import { Router } from '@angular/router';
import * as Parse from 'parse';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
  initial: number = 0;
  current: number = 0;
  target: number = 0;
  reward: number = 0;
  username: string = ''; // 当前用户的用户名
  blueColor: boolean = false;
  taskCompleted: boolean = false; // 任务完成标志

  constructor(
    private alertController: AlertController,
    private router: Router,
    private navCtrl: NavController,
  ) {}

  ngOnInit() {
    this.loadUserData();
  }

  ionViewDidEnter() {
    this.loadUserData();
  }

  async loadUserData() {
    const currentUser = Parse.User.current();
    if (currentUser) {
      this.username = currentUser.getUsername()!;
      this.loadData();
    } else {
      this.username = '未登录';
      this.loadData();
    }
    console.log("tab1:" + this.username);
  }

  async loadData() {
    try {
      const query = new Parse.Query('weight_status');
      query.equalTo('username', this.username); // 查找当前用户的数据
      const weightStatus = await query.first();
      if (weightStatus) {
        this.initial = weightStatus.get('initial') || 0;
        this.current = weightStatus.get('current') || 0;
        this.target = weightStatus.get('target') || 0;
        this.reward = this.calculateReward(this.initial, this.target);

        // 检查任务是否完成
        if (this.current === this.target && this.initial !== this.target) {
          await this.completeTask(weightStatus);
        } else if (this.current === this.initial && this.current === this.target) {
          this.taskCompleted = true; // 设置任务完成标志
        } else {
          this.taskCompleted = false; // 重置任务完成标志
        }
      } else {
        // 没有找到用户数据时，将所有体重数据重置为0
        this.initial = 0;
        this.current = 0;
        this.target = 0;
        this.reward = 0;
      }
    } catch (error) {
      console.error('Error loading data', error);
      // 出现错误时，将所有体重数据重置为0
      this.initial = 0;
      this.current = 0;
      this.target = 0;
      this.reward = 0;
    }
  }

  async completeTask(weightStatus: Parse.Object) {
    // 更新 weight_status 数据库中的初始体重和目标体重
    weightStatus.set('initial', this.current);
    weightStatus.set('target', this.current);
    await weightStatus.save();

    // 记录完成任务的赏金到 account_history 数据库
    const AccountHistory = Parse.Object.extend('account_history');
    const accountHistory = new AccountHistory();

    const historyQuery = new Parse.Query('account_history');
    historyQuery.equalTo('username', this.username);
    const latestHistory = await historyQuery.descending('historyId').first();
    const historyId = latestHistory ? latestHistory.get('historyId') + 1 : 1;
    const currentBounty = latestHistory ? latestHistory.get('account') : 1000;
    const rewardAmount = this.calculateReward(this.initial, this.target);

    accountHistory.set('username', this.username);
    accountHistory.set('amount', rewardAmount);
    accountHistory.set('type', 'income');
    accountHistory.set('remark', '完成任务');
    accountHistory.set('account', currentBounty + rewardAmount);
    accountHistory.set('historyId', historyId);
    accountHistory.set('expenseRecord', latestHistory ? latestHistory.get('expenseRecord') : 0); // 保留现有的支出记录

    await accountHistory.save();
    await this.loadUserData();
    // 显示任务完成消息
    this.taskCompleted = true;
  }

  calculateReward(initial: number, target: number): number {
    return (initial - target) * 10;
  }

  async openEditModal() {
    if (this.username == '未登录') {
      // 如果用户未登录，则显示登录提示
      this.presentLoginAlert();
      return;
    }

    const alert = await this.alertController.create({
      header: '编辑体重信息',
      subHeader: '请根据您的需求编辑以下信息',
      inputs: [
        {
          name: 'initial',
          type: 'number',
          placeholder: '初始',
          value: this.initial.toString()
        },
        {
          name: 'current',
          type: 'number',
          placeholder: '当前',
          value: this.current.toString()
        },
        {
          name: 'target',
          type: 'number',
          placeholder: '目标',
          value: this.target.toString()
        },
        {
          name: 'reward',
          type: 'number',
          placeholder: '赏金',
          value: this.reward.toString(),
          disabled: true // 禁用输入框，显示但不能编辑
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '保存',
          handler: async (data) => {
            try {
              const query = new Parse.Query('weight_status');
              query.equalTo('username', this.username); // 查找当前用户的数据
              let weightStatus = await query.first();
              if (!weightStatus) {
                weightStatus = new Parse.Object('weight_status');
              }
              const rewardValue = this.calculateReward(Number(data.initial), Number(data.target));
              weightStatus.set('username', this.username);
              weightStatus.set('initial', Number(data.initial));
              weightStatus.set('current', Number(data.current));
              weightStatus.set('target', Number(data.target));
              weightStatus.set('reward', rewardValue);
              await weightStatus.save();
              this.loadData(); // 更新本地数据
            } catch (error) {
              console.error('Error updating data', error);
            }
          }
        }
      ]
    });

    await alert.present();
  }

  async presentLoginAlert() {
    const alert = await this.alertController.create({
      header: '未登录',
      message: '请先登录以继续操作',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '去登录',
          handler: () => {
            this.navCtrl.navigateForward('/user/login');
          }
        }
      ]
    });

    await alert.present();
  }

  toggleButtonColor(habit: string) {
    this.blueColor = !this.blueColor;
  }

  //每日习惯按钮颜色变化
  buttons = [
    { text: '足量饮水', color: 'light', icon: 'water' },
    { text: '干净饮食', color: 'light', icon: 'nutrition' },
    { text: '健康作息', color: 'light', icon: 'bed' },
    { text: '有氧', color: 'light', icon: 'bicycle' },
    { text: '力量', color: 'light', icon: 'barbell' },
    { text: '拉伸', color: 'light', icon: 'body' }
  ];

  habitText = '今日习惯待保持';

  onButtonClick(index: number) {
    const button = this.buttons[index];
    switch(button.color) {
      case 'light':
        button.color = 'success';
        break;
      case 'success':
        button.color = 'danger';
        break;
      case 'danger':
        button.color = 'light';
        break;
    }
  
    this.checkHabitText();
  }
  
  checkHabitText() {
    if (this.buttons.every(btn => btn.color === 'success')) {
      this.habitText = '你成功保持了良好的习惯';
    } else if (this.buttons.some(btn => btn.color === 'danger')) {
      this.habitText = '今日好习惯保持失败，再接再厉';
    } else {
      this.habitText = '今日习惯待保持';
    }
  }
  
  get allButtonsSuccess() {
    return this.buttons.every(btn => btn.color === 'success');
  }
  
  get anyButtonFailure() {
    return this.buttons.some(btn => btn.color === 'danger');
  }

  navigateToTreePage() {
    this.router.navigate(['/tabs/timer']);
  }
}
