import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NbDialogService, NbToastrService } from '@nebular/theme';
import { Contribution } from '../../entity/contribution.model';
import { AuthService } from '../../services/auth.service';
import { ContributionService } from '../../services/crudServices/contribution.service';
import { PastoralDomainService } from '../../services/crudServices/pastoral-domain.service';
import { LineService } from '../../services/line.service';
import { MsgBoxService } from '../../services/msg-box.service';
import { SessionService } from '../../services/session.service';
import { StateService } from '../../services/state.service';
import { MyAppBase } from '../MyAppBase';
import { AddContributionDlgComponent } from './add-contribution-dlg/add-contribution-dlg.component';
import { first } from 'rxjs/operators';
import { FancySettings } from '../../ui/fancy-table/fancy-settings.model';
import { ObjectUtils } from '../../utilities/object-utils';
import { NumberUtils } from '../../utilities/number-utils';
import { StringUtils } from '../../utilities/string-utils';

@Component({
  selector: 'ngx-finance',
  templateUrl: './finance.component.html',
  styleUrls: ['./finance.component.scss']
})
export class FinanceComponent extends MyAppBase {

  contributions: Contribution[];
  summary: Contribution[];
  //#region Table Setting
  contributionSettings = <FancySettings<Contribution>>{
    contextMenuItems: [
      // {
      //   id: 'add',
      //   enabled: true,
      //   title: 'Add New',
      //   icon: 'plus-circle-outline',
      //   callback: (datum, element) => {
      //     this.openEditingDialog(true);
      //   },
      // },
      // {
      //   id: 'edit',
      //   enabled: true,
      //   title: 'Edit',
      //   icon: 'edit',
      //   callback: (datum, element) => {
      //     this.openEditingDialog(false);
      //   },
      // },
      {
        enabled: true,
        id: 'delete',
        title: 'Delete',
        icon: 'trash-2-outline',
        callback: (datum, element) => {
          this.contributionService.delete(datum.id).pipe(first()).subscribe(result => {

          });
        },
      }],
    onContextMenuOpening: (datum, menuItems) => {
      menuItems.find(i => i.id == 'delete').visible = !!datum;
      //menuItems.find(i => i.id == 'edit').visible = !!datum;
      return datum;
    },
    columns: [
      {
        name: 'time',
        title: 'Time',
        type: 'date',
        widthPx: 120,
        //valuePrepareFunction: (item) => ,
      },
      {
        name: 'contributor',
        title: 'Contributor',
        type: 'text',
        widthPx: 150,
        //valuePrepareFunction: (item) => ,
      },
      {
        name: 'amount',
        title: 'Amount',
        type: 'text',
        widthPx: 100,
        class: 'text-right',
        footerClass: 'text-right',
        valuePrepareFunction: getAmountDisplay,
      },
      {
        name: 'comment',
        title: 'Comment',
        type: 'text',
        widthPx: 200,
        //valuePrepareFunction: (item) => ,
      },

    ],
    showFooter: true
  };
  //#endregion

  constructor(
    private contributionService: ContributionService,
    private messageService: MsgBoxService,
    private toastrService: NbToastrService,
    private sessionService: SessionService,
    private lineService: LineService,
    private cdRef: ChangeDetectorRef,
    private authService: AuthService,
    private dlgService: NbDialogService,
    protected stateService: StateService,
    protected route: ActivatedRoute,
    protected pastoralDomainService: PastoralDomainService
  ) {
    super(stateService, route, pastoralDomainService);
  }

  pageOnInit(): void {
    this.initializeData();
  }

  addContribution() {
    this.dlgService.open(AddContributionDlgComponent, {
      context: {

      }
    }).onClose.pipe(first()).subscribe(result => {
      if (result) {
        result.groupId = this.currentDomain.id;
        this.isLoading = true;
        this.contributionService.createOrUpdate(result).pipe(first()).subscribe(result => {
          this.refreshData();
        });
      }
    });
  }

  private refreshData() {
    this.isLoading = true;
    this.pastoralDomainService.initialize().pipe(first()).subscribe(result => {
      this.initializeData();
    });
  }
  private initializeData() {
    this.contributions = ObjectUtils.CloneValue(this.currentDomain.contributions);
    this.summary = [];

    let totalComment = '';

    let totalAmount = this.contributions.map(d => d.amount).reduce((a, b) => a + b, 0);
    //Append Cost
    if (this.currentDomain.happinessWeeks) {

      for (let i = 0; i < this.currentDomain.happinessWeeks.length; i++) {
        const week = this.currentDomain.happinessWeeks[i];
        let weekCost = 0;
        for (let j = 0; j < week.costs.length; j++) {
          const weekCostItem = week.costs[j];
          this.contributions.push(
            {
              time: week.date,
              contributor: `W${i + 1} - ${weekCostItem.tasker}`,
              amount: -1 * weekCostItem.amount,
              comment: weekCostItem.content
            } as Contribution);
          weekCost += weekCostItem.amount;
        }

        if (weekCost > 0) {

          this.contributions.push(
            {
              time: week.date,
              contributor: `${week.topic} - Sub Total`,
              amount: 0,
              comment: '$ ' + NumberUtils.FormatCurrency(weekCost)
            } as Contribution);
        }
      }
      let remainWeeks = this.currentDomain.happinessWeeks.filter(w => w.date >= new Date()).length;

      totalAmount = this.contributions.map(d => d.amount).reduce((a, b) => a + b, 0);
      totalComment = StringUtils.getHtmlBadge(`剩餘每周(${remainWeeks}) 預算: $${NumberUtils.FormatCurrency(totalAmount / remainWeeks)}`, 'info');
    }



    this.summary.push(
      {
        time: null,
        contributor: `Summary`,
        amount: totalAmount,
        comment: totalComment
      } as Contribution);
    this.isLoading = false;

  }
}
function getAmountDisplay(item: Contribution): string {

  if (item.amount != 0) {
    return StringUtils.getHtmlBadge(NumberUtils.FormatCurrency(item.amount), item.amount > 0 ? 'success' : 'warning');
  }

  return "---------------";
}

