import { of } from 'rxjs/observable/of';
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { MroDataService } from "app/service/mro-data.service";
import { HelperService } from "app/service/helper.service";
import { SetDataService } from "app/service/set-data.service";
import { TableQueryData } from "app/data/TableQueryData";
import { ActivatedRoute } from "@angular/router";
import { Chart } from 'chart.js';
import { IMyDpOptions } from "mydatepicker";
import { AnnounceData } from "app/data/AnnounceData";
import { BoardDataService } from "app/service/board-data.service";
import { EventData } from "app/data/EventData";
import { EventCountIntervalData } from "app/data/EventCountIntervalData";
import { SysDataService } from "app/service/sys-data.service";

@Component({
  templateUrl: "dashboard.component.html"
})
export class DashboardComponent implements OnInit {
  pageAnnounceCount = 0;
  pageEventCount = 0;
  pageAnnounceLinks = [];
  pageEventLinks = [];
  pageAnnounceLinkMarginCount = 2;
  pageEventLinkMarginCount = 2;
  errorMessage: string;
  myDate: any;
  loadingAnnounce = false;
  loadingEvent = false;
  loadingEventCount = false;
  loadingMalfunction = false;
  loadingEventYear = false;
  loginUser = localStorage.getItem("name");
  loginPassword = localStorage.getItem("password");
  IsAscAnnounce = true;
  itemAnnounce: string;
  IsAscEvent = true;
  itemEvent: string;
  id = 4;
  myPieChart: any;
  ctx: any;
  canvas: any;

  announcePageList = [];
  eventPageList = [];

  public warningModal;
  public announceModal;
  startDT: any;
  endDT: any;
  public myDatePickerOptions: IMyDpOptions = {
    dateFormat: 'yyyy/mm/dd',
    editableDateField: false,
    openSelectorOnInputClick: true,
    dayLabels: {
      su: '日',
      mo: '一',
      tu: '二',
      we: '三',
      th: '四',
      fr: '五',
      sa: '六',
    },
    monthLabels: {
      1: '一月',
      2: '二月',
      3: '三月',
      4: '四月',
      5: '五月',
      6: '六月',
      7: '七月',
      8: '八月',
      9: '九月',
      10: '十月',
      11: '十一月',
      12: '十二月',
    },
    todayBtnTxt: '今天',
  };
  announceData: any;
  tableQueryAnnounceData: TableQueryData;

  eventData: any;
  tableQueryEventData: TableQueryData;

  eventCountByThisMonth: any;
  eventCountByThisYear: any;
  eventCountByInterval: EventCountIntervalData;
  eventCountByIntervalData: any;

  siteInformationList = [];
  siteMalfunctionList = [];
  warningModalList = [];
  announceModalData: AnnounceData;

  constructor(
    private mroDataService: MroDataService,
    private helperService: HelperService,
    private boardDataService: BoardDataService,
    private sysDataService: SysDataService,
    private router: Router
  ) {}

  ngOnInit() {

    this.announceModalData = new AnnounceData();

    this.loadingEvent = false;
    this.loadingEventCount = true;
    this.loadingMalfunction = true;
    this.loadingEventYear = true;
    this.loadingAnnounce = true;
    var currentdate = new Date();
var datetime = currentdate.getFullYear() + "/"
                + (currentdate.getMonth() + 1) + "/"
                + currentdate.getDate();

                var datetime_yesterday = currentdate.getFullYear() + "/"
                + (currentdate.getMonth() + 1) + "/"
                + (currentdate.getDate() - 1);

    this.myDate = datetime;
    this.endDT = {formatted: datetime};
    this.startDT = {formatted: datetime_yesterday};

    this.eventData = new EventData();
    this.tableQueryEventData = new TableQueryData();
    this.tableQueryEventData.CurrentPage = 0;

    this.announceData = new AnnounceData();
    this.tableQueryAnnounceData = new TableQueryData();
    this.tableQueryAnnounceData.CurrentPage = 0;
    this.getAnnounceData(this.tableQueryAnnounceData);
    this.getEventCountByThisYear();
    this.getEventCountByThisMonth();

    this.eventCountByInterval = new EventCountIntervalData();
    this.eventCountByIntervalData = [];

    this.getEventCountByInterval(datetime_yesterday.toString(), this.myDate.toString());
    this.getSiteMalfunctionInformation();
    if (this.loginPassword === "1") {
      this.router.navigate(["sys/sys001"]);
    }
  }

  getSiteMalfunctionInformation(): any {
    this.loadingMalfunction = true;
    this.boardDataService.getSiteMalfunctionInformation().subscribe(res => {
      const result = res.json().Result;
      this.siteMalfunctionList = result;
      this.loadingMalfunction = false;
    }, error => (this.errorMessage = <any>error));
  }


  setWarningModal(item, model) {
    model.show();
    this.warningModalList = item.Malfunction;

  }

  setAnnounceModal(item, model) {
    model.show();
    this.announceModalData = item;

  }



  getEventCountByThisYear() {
    this.loadingEventYear = true;
    this.boardDataService.getEventCountByThisYear().subscribe(res => {
      this.loadingEventYear = false;
      const result = res.json().Result;
      this.eventCountByThisYear = result;
    }, error => (this.errorMessage = <any>error));
  }

  getEventCountByThisMonth() {
    this.loadingEventYear = true;
    this.boardDataService.getEventCountByThisMonth().subscribe(res => {
      this.loadingEventYear = false;
      const result = res.json().Result;
      this.eventCountByThisMonth = result;
    }, error => (this.errorMessage = <any>error));
  }


  getEventCountByInterval(startDatetime: string, endDatetime: string) {
    this.loadingEventCount = true;
    this.eventCountByIntervalData = [];
    this.boardDataService.getEventCountByInterval(startDatetime, endDatetime).subscribe(res => {
      this.loadingEventCount = false;
      const result = res.json().Result;
      this.eventCountByInterval = result;
      this.eventCountByIntervalData.push(this.eventCountByInterval.PunishedCount);
      this.eventCountByIntervalData.push(this.eventCountByInterval.CheckPunishedCount);
      this.eventCountByIntervalData.push(this.eventCountByInterval.RejectedCount);
      this.eventCountByIntervalData.push(this.eventCountByInterval.NoStatusCount);
      this.eventCountByIntervalData.push(this.eventCountByInterval.NoPunishedCount);
      this.doughnutChart();
    }, error => (this.errorMessage = <any>error));
  }


  getAnnounceData(tableQueryData: TableQueryData): any {
    this.tableQueryAnnounceData.CurrentPage = tableQueryData.Page
      ? tableQueryData.Page
      : 1;
      this.loadingAnnounce = true;
    this.boardDataService.getAnnouncePageList(tableQueryData).subscribe(res => {
      const result = res.json().Result;
      this.announcePageList = result.Data;
      this.loadingAnnounce = false;
      if (tableQueryData.Page === 1 || !tableQueryData.Page) {
        this.pageAnnounceCount = result.PageCount;
        this.getAnnouncePageLinks();
      }
    }, error => (this.errorMessage = <any>error));
  }


  getEventData(tableQueryData: TableQueryData): any {
    this.tableQueryEventData.CurrentPage = tableQueryData.Page
      ? tableQueryData.Page
      : 1;
      this.loadingEvent = true;
    this.boardDataService.getEventPageList(tableQueryData).subscribe(res => {
      const result = res.json().Result;
      this.eventPageList = result.Data;
      this.loadingEvent = false;
      if (tableQueryData.Page === 1 || !tableQueryData.Page) {
        this.pageEventCount = result.PageCount;
        this.getEventPageLinks();
      }
    }, error => (this.errorMessage = <any>error));
  }



  doughnutChart() {
    try {
      this.canvas = document.getElementById('myChart');
    this.ctx = this.canvas.getContext('2d');
    this.myPieChart = new Chart(this.ctx, {
      type: 'pie',
      data : {
        labels: ['已開單', '裁決中', '已駁回', '未處理', '不開單'],
        datasets: [{
            // 預設資料
            data: this.eventCountByIntervalData,
            backgroundColor: [
            // 資料顏色
                "#00DB00",
                "#FF0000",
                "#2828FF",
                "#F28500"
            ],
        }],
      }
    });
    } catch (error) {

    }

}

  orderAnnounce(item) {
    this.IsAscAnnounce = !this.IsAscAnnounce;
    this.itemAnnounce = item;
    this.tableQueryAnnounceData.Order = item;
    this.tableQueryAnnounceData.IsAsc = this.IsAscAnnounce.toString();
    this.getAnnounceData(this.tableQueryAnnounceData);
  }

  orderEvent(item) {
    this.IsAscEvent = !this.IsAscEvent;
    this.itemEvent = item;
    this.tableQueryEventData.Order = item;
    this.tableQueryEventData.IsAsc = this.IsAscEvent.toString();
    this.getEventData(this.tableQueryEventData);
  }

  getAnnouncePageLinks() {
    this.pageAnnounceLinks = [];
    let firstPageNumber =
      this.tableQueryAnnounceData.CurrentPage - this.pageAnnounceLinkMarginCount;
    let lastPageNumber =
      this.tableQueryAnnounceData.CurrentPage + this.pageAnnounceLinkMarginCount;
    if (firstPageNumber < 1) {
      firstPageNumber = 1;
    }
    if (lastPageNumber > this.pageAnnounceCount) {
      lastPageNumber = this.pageAnnounceCount;
    }
    if (firstPageNumber > 1) {
      const isCurrentPage = firstPageNumber === this.tableQueryAnnounceData.CurrentPage;
      this.pageAnnounceLinks.push({
        text: "第一頁",
        pageNo: 1,
        isCurrent: isCurrentPage
      });
    }
    for (let i = firstPageNumber; i <= lastPageNumber; i++) {
      const isCurrentPage = i === this.tableQueryAnnounceData.CurrentPage;
      this.pageAnnounceLinks.push({ text: i, pageNo: i, isCurrent: isCurrentPage });
    }
    if (lastPageNumber < this.pageAnnounceCount) {
      const isCurrentPage = lastPageNumber === this.tableQueryAnnounceData.CurrentPage;
      this.pageAnnounceLinks.push({
        text: "最後頁(共 " + this.pageAnnounceCount + " 頁)",
        pageNo: this.pageAnnounceCount,
        isCurrent: isCurrentPage
      });
    }
  }

  getEventPageLinks() {
    this.pageEventLinks = [];
    let firstPageNumber =
      this.tableQueryEventData.CurrentPage - this.pageEventLinkMarginCount;
    let lastPageNumber =
      this.tableQueryEventData.CurrentPage + this.pageEventLinkMarginCount;
    if (firstPageNumber < 1) {
      firstPageNumber = 1;
    }
    if (lastPageNumber > this.pageEventCount) {
      lastPageNumber = this.pageEventCount;
    }
    if (firstPageNumber > 1) {
      const isCurrentPage = firstPageNumber === this.tableQueryEventData.CurrentPage;
      this.pageEventLinks.push({
        text: "第一頁",
        pageNo: 1,
        isCurrent: isCurrentPage
      });
    }
    for (let i = firstPageNumber; i <= lastPageNumber; i++) {
      const isCurrentPage = i === this.tableQueryEventData.CurrentPage;
      this.pageEventLinks.push({ text: i, pageNo: i, isCurrent: isCurrentPage });
    }
    if (lastPageNumber < this.pageEventCount) {
      const isCurrentPage = lastPageNumber === this.tableQueryEventData.CurrentPage;
      this.pageEventLinks.push({
        text: "最後頁(共 " + this.pageEventCount + " 頁)",
        pageNo: this.pageEventCount,
        isCurrent: isCurrentPage
      });
    }
  }

  onAnnouncePageChange(e: Event, page) {
    e.preventDefault();
    this.tableQueryAnnounceData.CurrentPage = page;
    this.tableQueryAnnounceData.Page = this.tableQueryAnnounceData.CurrentPage;
    this.getAnnouncePageLinks();
    this.getAnnounceData(this.tableQueryAnnounceData);
  }

  onEventPageChange(e: Event, page) {
    e.preventDefault();
    this.tableQueryEventData.CurrentPage = page;
    this.tableQueryEventData.Page = this.tableQueryEventData.CurrentPage;
    this.getEventPageLinks();
    this.getEventData(this.tableQueryEventData);
  }

  doAnnounceSearch() {
    this.tableQueryAnnounceData.Page = null;
    this.getAnnounceData(this.tableQueryAnnounceData);
  }

  doEventSearch() {
    this.tableQueryEventData.Page = null;
    this.getEventData(this.tableQueryEventData);
  }

  clearAnnounceSearch() {
    this.tableQueryAnnounceData.Term = null;
    this.getAnnounceData(this.tableQueryAnnounceData);
  }

  clearEventSearch() {
    this.eventPageList = [];
    this.tableQueryEventData = new TableQueryData();
  }
}
