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

@Component({
  selector: 'app-bounty-store',
  templateUrl: 'bounty-store.page.html',
  styleUrls: ['bounty-store.page.scss']
})
export class BountyStorePage implements OnInit {
  currentBounty: number = 1000; // 初始化账户余额
  totalSpent: number = 0; // 初始化累计支出
  username: string = ''; // 当前用户的用户名
  historyId: number = 1; // 初始化historyId
  expenseRecord: number = 0; // 初始化expenseRecord

  constructor(private alertController: AlertController) {}

  async ngOnInit() {
    //检测登录状况
    this.loadUserData();
    //刷新数据
    this.loadAccountData();
  }

  ionViewDidEnter() {
    //检测登录状况
    this.loadUserData();
    //刷新数据
    this.loadAccountData();
  }

  async loadUserData() {
    const currentUser = Parse.User.current();
    if (currentUser) {
      this.username = currentUser.getUsername()!;
    } else {
      this.username = '未登录';
    }
  }

  async loadAccountData() {
    try {
      const query = new Parse.Query('account_history');
      query.equalTo('username', this.username);
      query.ascending('historyId');
      const accountHistory = await query.find();

      if (accountHistory.length > 0) {
        const latestHistory = accountHistory[accountHistory.length - 1];
        this.currentBounty = latestHistory.get('account');
        this.historyId = latestHistory.get('historyId') + 1;

        this.totalSpent = accountHistory
          .filter(history => history.get('type') === 'expense')
          .reduce((total, history) => total + history.get('amount'), 0);
        
        this.expenseRecord = this.totalSpent; // 初始化expenseRecord为累计支出
      } else {
        await this.createInitialAccount();
      }
    } catch (error) {
      console.error('Error loading account data', error);
    }
  }

  async createInitialAccount() {
    const AccountHistory = Parse.Object.extend('account_history');
    const accountHistory = new AccountHistory();

    accountHistory.set('username', this.username);
    accountHistory.set('amount', 1000);
    accountHistory.set('type', 'initial');
    accountHistory.set('remark', '初始账户');
    accountHistory.set('account', 1000);
    accountHistory.set('historyId', 1);
    accountHistory.set('expenseRecord', 0); // 初始化expenseRecord为0

    try {
      await accountHistory.save();
    } catch (error) {
      console.error('Error creating initial account', error);
    }
  }

  async openPopup(activity: string) {
    const alert = await this.alertController.create({
      header: '消费详情',
      inputs: [
        {
          name: 'amount',
          type: 'number',
          placeholder: '消费金额（元）'
        },
        {
          name: 'note',
          type: 'text',
          placeholder: '备注信息'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确认',
          handler: async (data: any) => {
            const amount = parseFloat(data.amount);
            if (!isNaN(amount) && amount > 0) {
              await this.updateAccountHistory(amount, data.note);
            }
          }
        }
      ]
    });

    await alert.present();
  }

  async updateAccountHistory(amount: number, note: string) {
    const AccountHistory = Parse.Object.extend('account_history');
    const accountHistory = new AccountHistory();

    accountHistory.set('username', this.username);
    accountHistory.set('amount', amount);
    accountHistory.set('type', 'expense');
    accountHistory.set('remark', note);
    accountHistory.set('account', this.currentBounty - amount);
    accountHistory.set('historyId', this.historyId);
    accountHistory.set('expenseRecord', this.expenseRecord + amount); // 更新expenseRecord

    try {
      await accountHistory.save();
      this.currentBounty -= amount;
      this.totalSpent += amount;
      this.expenseRecord += amount; // 更新本地的expenseRecord
      this.historyId += 1; // Increment historyId for the next entry
    } catch (error) {
      console.error('Error updating account history', error);
    }
  }
}
