import { BoardDataService } from 'app/service/board-data.service';
import { SysDataService } from './../../../service/sys-data.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MroDataService } from 'app/service/mro-data.service';
import { SetDataService } from 'app/service/set-data.service';
import { ActivatedRoute } from '@angular/router';
import { IMyDpOptions, IMyDateModel } from 'mydatepicker';
import { TableQueryData } from 'app/data/TableQueryData';
import { ApiTableData } from 'app/data/ApiTableData';
import swal from 'sweetalert2';
import { SiteEventTypesData } from 'app/data/SiteEventTypesData';
import { MalfunctionData } from 'app/data/MalfunctionData';

@Component({
  selector: 'app-mro006',
  templateUrl: './mro006.component.html',
})
export class Mro006Component implements OnInit {

  loading = false;
  errorMessage: String;
  tableQueryData: TableQueryData;
  apiDataList = [];
  currentPage = 0;
  pageCount = 0;
  pageLinks = [];
  pageLinkMarginCount = 2;
  tycgTableName: string;
  apiTableData: ApiTableData;
  IsAsc = true;
  item: string;

  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: '今天',
  };

  startDT: any;
  endDT: any;
  startDT1: number;
  endDT1: number;

  EventTypeList: any;
  siteInformationList: any;
  ReportMalfunctionList: any;
  areaArray: any;

  rowCount: number;
  colCount: number;

  siteList: any;
  siteRows: any;
  Rows: any;

  fileName: string;
  urlExport: any;


  constructor(
    private mroDataService: MroDataService,
    private setDataService: SetDataService,
    private sysDataService: SysDataService,
    private boardDataService: BoardDataService
    ) {}

  ngOnInit() {

    this.tycgTableName = "";
    this.tableQueryData = new TableQueryData();
    this.tableQueryData.CurrentPage = 0;
    this.loading = false;

    const currentdate = new Date();
    const startdatetime = currentdate.getFullYear() + "/"
                    + (currentdate.getMonth() + 1) + "/"
                    + currentdate.getDate();

    const enddatetime = currentdate.getFullYear() + "/"
                    + (currentdate.getMonth() + 1) + "/"
                    + currentdate.getDate();

    this.startDT = {formatted: startdatetime};
    this.endDT = {formatted: enddatetime};

    this.getEventTypeId();
    this.getSiteInformationAll();

    this.siteList = [];
    this.siteRows = [];
    this.Rows = [];
    this.ReportMalfunctionList = [];

    this.fileName = "";

  }


  getEventTypeId() {
    this.setDataService.getEventTypeId().subscribe(res => {
      const result = res.json().Result;
      this.EventTypeList = result;
    }, error => (this.errorMessage = <any>error));
  }

  getSiteInformationAll(): any {
    this.sysDataService.getSiteInformationAll().subscribe(res => {
      const result = res.json().Result;
      this.siteInformationList = result;

      var allArea = result.map(function(item) {
        return item.Area;
    });
      this.areaArray = allArea.filter(function(element, index, arr) {
        return arr.indexOf(element) === index;
    });


    for (let index = 0; index < this.areaArray.length; index++) {
      const element = this.areaArray[index];
      this.Rows = [];
      for (let index1 = 0; index1 < result.length; index1++) {
        const element1 = result[index1];
        if (element1.Area === element) {
          this.Rows.push(element1);
        }
      }

      if (index !== (this.areaArray.length - 1)) {

        if (this.siteRows.length < 3) {
          this.siteRows[this.siteRows.length] = this.Rows;
        } else {
          this.siteList[this.siteList.length] = this.siteRows;
          this.siteRows = [];
        }
      } else {
        this.siteList[this.siteList.length] = this.siteRows;
      }
    }



    this.rowCount = this.areaArray / 3;
    const remainder = this.areaArray % 3;
    if (remainder > 0) {
      this.rowCount++;
    }
    }, error => (this.errorMessage = <any>error));
  }

  selectALL(isChecked, item, i, j) {
    for (let index = 0; index < this.siteList[i][j].length; index++) {
      const element = this.siteList[i][j];
      element[index].isChecked = isChecked;
    }
  }

  doSearch() {
    this.loading = true;
    const malfunctionData = new MalfunctionData();
    malfunctionData.StartDate = this.startDT.formatted;
    malfunctionData.EndDate = this.endDT.formatted;

    if (this.startDT1 === undefined) {
      this.startDT1 = 0;
    }
    if (this.endDT1 === undefined) {
      this.endDT1 = 23;
    }
    malfunctionData.StartTime = this.startDT1;
    malfunctionData.EndTime = this.endDT1;
    malfunctionData.Sites = [];


    // for (let index = 0; index < this.EventTypeList.length; index++) {
    //   const element = this.EventTypeList[index];
    //   if (element.isChecked) {
    //     siteEventTypesData.EventTypes.push(element.Id.toString());
    //   }
    // }


    for (let index = 0; index < this.siteInformationList.length; index++) {
      const element = this.siteInformationList[index];
      if (element.isChecked) {
        malfunctionData.Sites.push(element.SiteID.toString());
      }
    }


    if (malfunctionData.Sites.length === 0) {
      swal({
        type: "error",
        title: "查詢失敗",
        text: "請勾選站點...",
        showConfirmButton: false,
          timer: 2000,
      });
      this.loading = false;

    } else {
      this.postReportMalfunction(malfunctionData, "0");
    }
  }


  doSearchExport() {
    this.loading = true;
    const malfunctionData = new MalfunctionData();
    malfunctionData.StartDate = this.startDT.formatted;
    malfunctionData.EndDate = this.endDT.formatted;

    if (this.startDT1 === undefined) {
      this.startDT1 = 0;
    }
    if (this.endDT1 === undefined) {
      this.endDT1 = 24;
    }
    malfunctionData.StartTime = this.startDT1;
    malfunctionData.EndTime = this.endDT1;
    malfunctionData.Sites = [];


    for (let index = 0; index < this.siteInformationList.length; index++) {
      const element = this.siteInformationList[index];
      if (element.isChecked) {
        malfunctionData.Sites.push(element.SiteID.toString());
      }
    }

    if (malfunctionData.Sites.length === 0) {
      swal({
        type: "error",
        title: "查詢失敗",
        text: "請勾選站點...",
        showConfirmButton: false,
          timer: 2000,
      });
      this.loading = false;

    } else {
      this.postReportMalfunction(malfunctionData, "1");
    }


  }


  postReportMalfunction(malfunctionData: MalfunctionData, method: string): any {
    this.boardDataService.postReportMalfunction(method, malfunctionData).subscribe(res => {
      // const result = res.json().Result;

      if (method === '0') {
        const result = res.json().Result;
        this.ReportMalfunctionList = result;
        this.loading = false;
      } else {
        this.urlExport = res;
        const link = document.createElement("a");
          link.href = this.urlExport._body;
          this.fileName = this.urlExport._body.substring(this.urlExport._body.lastIndexOf('/') + 1);
          link.download = this.fileName;
          link.click();
          this.loading = false;
      }


    }, error => (this.errorMessage = <any>error));
  }







  // getAPITableDataList(tableQueryData: TableQueryData, tycgTableName?: string): any {
  //   this.loading = true;
  //   this.tableQueryData.CurrentPage = tableQueryData.Page
  //     ? tableQueryData.Page
  //     : 1;
  //   this.mroDataService.getAPITableDataList(tableQueryData, tycgTableName).subscribe(res => {
  //     const result = res.json().Result;
  //     this.apiDataList = result.Data;
  //     this.loading = false;
  //     if (tableQueryData.Page === 1 || !tableQueryData.Page) {
  //       this.pageCount = result.PageCount;
  //       this.getPageLinks();
  //     }
  //   }, error => (this.errorMessage = <any>error));
  // }

  // onPageChange(e: Event, page) {
  //   e.preventDefault();
  //   this.tableQueryData.CurrentPage = page;
  //   this.tableQueryData.Page = this.tableQueryData.CurrentPage;
  //   this.getPageLinks();
  //   this.getAPITableDataList(this.tableQueryData, this.tycgTableName);
  // }



  getPageLinks() {
    this.pageLinks = [];
    let firstPageNumber =
      this.tableQueryData.CurrentPage - this.pageLinkMarginCount;
    let lastPageNumber =
      this.tableQueryData.CurrentPage + this.pageLinkMarginCount;
    if (firstPageNumber < 1) {
      firstPageNumber = 1;
    }
    if (lastPageNumber > this.pageCount) {
      lastPageNumber = this.pageCount;
    }
    if (firstPageNumber > 1) {
      const isCurrentPage = firstPageNumber === this.tableQueryData.CurrentPage;
      this.pageLinks.push({
        text: "第一頁",
        pageNo: 1,
        isCurrent: isCurrentPage
      });
    }
    for (let i = firstPageNumber; i <= lastPageNumber; i++) {
      const isCurrentPage = i === this.tableQueryData.CurrentPage;
      this.pageLinks.push({ text: i, pageNo: i, isCurrent: isCurrentPage });
    }
    if (lastPageNumber < this.pageCount) {
      const isCurrentPage = lastPageNumber === this.tableQueryData.CurrentPage;
      this.pageLinks.push({
        text: "最後頁(共 " + this.pageCount + " 頁)",
        pageNo: this.pageCount,
        isCurrent: isCurrentPage
      });
    }
  }

  // order(item) {
  //   this.IsAsc = !this.IsAsc;
  //   this.item = item;
  //   this.tableQueryData.Order = item;
  //   this.tableQueryData.IsAsc = this.IsAsc.toString();
  //   this.getAPITableDataList(this.tableQueryData, this.tycgTableName);
  // }



}
