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 { EventTypeReportData } from 'app/data/EventTypeReportData';

@Component({
  selector: 'app-mro004',
  templateUrl: './mro004.component.html',
})
export class Mro004Component 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;
  ReportSiteEventTypes: any;
  areaArray: any;

  rowCount: number;
  colCount: number;

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

  ReportEventType1List: any;
  ReportEventType2List: any;
  ReportEventType34List: any;
  ReportEventType6List: any;

  eventTypeId: string;
  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;

    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.siteList = [];
    this.siteRows = [];
    this.Rows = [];

    this.ReportEventType1List = [];
    this.ReportEventType2List = [];
    this.ReportEventType34List = [];
    this.ReportEventType6List = [];

    this.eventTypeId = "";
    this.fileName = "";

  }


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

  getSiteInformationAll(eventTypeId): any {
    this.sysDataService.getSiteInformationAll().subscribe(res => {
      const result1 = res.json().Result;
      this.siteInformationList = result1;
      const result = [];
      this.siteList = [];
      this.siteRows = [];

      for (let index = 0; index < result1.length; index++) {
        const element = result1[index];

        if (eventTypeId === "34") {
          if (element.EventType === "3") {
            result.push(element);
          }
          if (element.EventType === "4") {
            result.push(element);
          }
        } else {
          if (element.EventType === eventTypeId) {
            result.push(element);
          }
        }
      }

      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.siteRows[this.siteRows.length] = this.Rows;
        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 eventTypeData = new EventTypeReportData();
    eventTypeData.StartDate = this.startDT.formatted;
    eventTypeData.EndDate = this.endDT.formatted;
    if (this.startDT1 === undefined) {
      this.startDT1 = 0;
    }
    if (this.endDT1 === undefined) {
      this.endDT1 = 24;
    }
    eventTypeData.StartTime = this.startDT1;
    eventTypeData.EndTime = this.endDT1;
    eventTypeData.Sites = [];


    if (this.siteInformationList === undefined) {



      swal({
        type: "error",
        title: "查詢失敗",
        text: "請選取違規類型...",
        showConfirmButton: false,
          timer: 2000,
      });

      this.loading = false;

    } else {


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

    if (eventTypeData.Sites.length === 0) {
      swal({
        type: "error",
        title: "查詢失敗",
        text: "請勾選站點...",
        showConfirmButton: false,
          timer: 2000,
      });
      this.loading = false;
    } else {
      switch (this.eventTypeId) {
        case "1":
          this.postReportEventType1(eventTypeData, "0");
          break;

        case "2":
          this.postReportEventType2(eventTypeData, "0");
          break;
        case "34":
          this.postReportEventType34(eventTypeData, "0");
          break;
        case "6":
          this.postReportEventType6(eventTypeData, "0");
          break;
        default:
          break;
      }

    }



  }



  }

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

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


    if (this.siteInformationList === undefined) {



      swal({
        type: "error",
        title: "查詢失敗",
        text: "請選取違規類型...",
        showConfirmButton: false,
          timer: 2000,
      });

      this.loading = false;

    } else {

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

      if (eventTypeData.Sites.length === 0) {
        swal({
          type: "error",
          title: "查詢失敗",
          text: "請勾選站點...",
          showConfirmButton: false,
            timer: 2000,
        });
        this.loading = false;
      } else {
        switch (this.eventTypeId) {
          case "1":
            this.postReportEventType1(eventTypeData, "1");
            break;
          case "2":
            this.postReportEventType2(eventTypeData, "1");
            break;
          case "34":
            this.postReportEventType34(eventTypeData, "1");
            break;
          case "6":
            this.postReportEventType6(eventTypeData, "1");
            break;
          default:
            break;
        }
      }
    }
  }


  postReportEventType1(eventTypeData: EventTypeReportData, method: string): any {
    this.boardDataService.postReportEventType1(method, eventTypeData).subscribe(res => {
      if (method === '0') {
        const result = res.json().Result;
        this.ReportEventType1List = 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));
  }

  postReportEventType2(eventTypeData: EventTypeReportData, method: string): any {
    this.boardDataService.postReportEventType2(method, eventTypeData).subscribe(res => {
      if (method === '0') {
        const result = res.json().Result;
        this.ReportEventType2List = 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));
  }


  postReportEventType34(eventTypeData: EventTypeReportData, method: string): any {
    this.boardDataService.postReportEventType34(method, eventTypeData).subscribe(res => {
      if (method === '0') {
        const result = res.json().Result;
        this.ReportEventType34List = 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));
  }


  postReportEventType6(eventTypeData: EventTypeReportData, method: string): any {
    this.boardDataService.postReportEventType6(method, eventTypeData).subscribe(res => {
      if (method === '0') {
        const result = res.json().Result;
        this.ReportEventType6List = 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));
  }



  onSelectEventTypeIdChange(value) {
    this.getSiteInformationAll(value);
  }


  postReportSiteEventTypes(siteEventTypesData: SiteEventTypesData): any {
    this.boardDataService.postReportSiteEventTypes("0", siteEventTypesData).subscribe(res => {
      const result = res.json().Result;
      this.ReportSiteEventTypes = result;
      this.loading = false;
    }, error => (this.errorMessage = <any>error));
  }



  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
      });
    }
  }

}
