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

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

  EventTypeList: any;
  siteInformationList: any;
  ReportSiteEventTypes: ReportSiteEventTypesData;
  areaArray: any;

  rowCount: number;
  colCount: number;

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

  fileName: string;
  urlExport: any;

  isChecked: any;


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

  ngOnInit() {

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

    const currentdate = new Date();
    const startdatetime = currentdate.getFullYear() + "/"
                    + (currentdate.getMonth() + 1) + "/"
                    + currentdate.getDate(); // + " "
                    // + "00" + ":"
                    // + "00" + ":"
                    // + "00";
    const enddatetime = currentdate.getFullYear() + "/"
                    + (currentdate.getMonth() + 1) + "/"
                    + currentdate.getDate(); // + " "
                    // + "23" + ":"
                    // + "59" + ":"
                    // + "59";


    // var startdatetime =  "2021/03/01";
    // var enddatetime =  "2021/03/01";

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


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

    this.siteList = [];
    this.siteRows = [];
    this.Rows = [];
    this.ReportSiteEventTypes = new ReportSiteEventTypesData;
    this.ReportSiteEventTypes.eachEventTypesSiteViewModel = [];
    this.ReportSiteEventTypes.eachSiteEventTypesViewModel = [];

    this.fileName = "";
  }


  getEventTypeId() {
    this.setDataService.getEventTypeId().subscribe(res => {
      const result = res.json().Result;
      this.EventTypeList = result;
      for (let index = 0; index < this.EventTypeList.length; index++) {
        const element = this.EventTypeList[index];
        if (element.EventType === "99") {
          this.EventTypeList.splice(index, 1);
        }
      }
    }, 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];
      // if (((index) % 3) === 0) {
      //   this.Rows = [];
      // }

      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.tableQueryData.Page = null;
    // if (this.tycgTableName === null || this.tycgTableName === "" || this.tycgTableName === "undefined") {
    //   swal({
    //     type: "error",
    //     title: "API 表格名稱錯誤",
    //     text: "請檢查表格名稱...",
    //     showConfirmButton: true
    //   });
    //   return;
    // }


    this.loading = true;
    const siteEventTypesData = new SiteEventTypesData();
    siteEventTypesData.Sites = [];
    siteEventTypesData.EventTypes = [];
    if (this.startDT1 === undefined) {
      this.startDT1 = "00:00"
    }
    if (this.endDT1 === undefined) {
      this.endDT1 = "23:59"
    }
    siteEventTypesData.StartTime = this.startDT.formatted + " " + this.startDT1;
    siteEventTypesData.EndTime = this.endDT.formatted + " " + this.endDT1;

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

    if (siteEventTypesData.EventTypes.length === 0) {

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

    }


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

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

    this.postReportSiteEventTypes(siteEventTypesData, "0");
  }



  doSearchExport() {
    this.loading = true;
    const siteEventTypesData = new SiteEventTypesData();
    siteEventTypesData.Sites = [];
    siteEventTypesData.EventTypes = [];
    siteEventTypesData.StartTime = this.startDT.formatted + " " + this.startDT1;
    siteEventTypesData.EndTime = this.endDT.formatted + " " + this.endDT1;

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


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


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

    if (siteEventTypesData.Sites.length === 0) {
      swal({
        type: "error",
        title: "匯出失敗",
        text: "請勾選站點...",
        showConfirmButton: false,
          timer: 2000,
      });
    }

    this.postReportSiteEventTypes(siteEventTypesData, "1");
  }


  postReportSiteEventTypes(siteEventTypesData: SiteEventTypesData, method: string): any {
    this.boardDataService.postReportSiteEventTypes(method, siteEventTypesData).subscribe(res => {
      // const result = res.json().Result;

      if (method === '0') {
        const result = res.json().Result;
        this.ReportSiteEventTypes = 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);
  // }



}
