import { SysDataService } from 'app/service/sys-data.service';
import { AfterViewInit, Component, OnInit, ViewChildren } from "@angular/core";
import { DataTableDirective } from "angular-datatables";
import { Subject } from "rxjs/Subject";
import { Http, Response } from "@angular/http";
import { SetDataService } from "app/service/set-data.service";
import { Set001Service } from "app/views/set/set001/set001.service";
import { Router } from "@angular/router";
import { ActivatedRoute } from "@angular/router";
import { HelperService } from "app/service/helper.service";
import swal from "sweetalert2";
import { AnnounceData } from "app/data/AnnounceData";
import { BoardDataService } from "app/service/board-data.service";
import { TableQueryData } from "app/data/TableQueryData";
import { IMyDpOptions } from "mydatepicker";
import { ALLOW_MULTIPLE_PLATFORMS } from '@angular/core/src/application_ref';
import { PunishQueryData } from 'app/data/PunishQueryData';
import { saveAs } from 'file-saver';

@Component({
  selector: "app-board001",
  templateUrl: "./punish.component.html"
})
export class PunishComponent implements OnInit {
  _imageURL = "https://172.16.1.49:8443/IVSImages/";
  _videoURL = "https://172.16.1.49:8443/IVSVideos/";
  renewalPageList = [];
  tableQueryData: TableQueryData;
  IsAsc = true;
  status = false;
  loginRole = localStorage.getItem("role");
  setRole = "1";
  loading = true;
  pageCount = 0;
  pageLinkMarginCount = 2;
  pageLinks = [];
  item: string;
  errorMessage: string;

  announceData: AnnounceData;
  announcePageList = [];
  punishEventList = [];
  siteInformationList = [];


  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;
  stationData: any;
  punishTime: any;
  punishQueryData: PunishQueryData;
  readyPunishEvent: any;
  displayReadyPunishEvent = false;
  LawsCodeData: string;
  Nopunish: any;
  reasonPageList: any;
  NotPunishReasonData: any;
  PunishView: any;
  PunishEdit: any;
  selectPunishEventList: any;
  isChecked: any;
  fileName: string;
  urlExport: any;

  constructor(
    private boardDataService: BoardDataService,
    private sysDataService: SysDataService,
    private setDataService: SetDataService,
    private helperService: HelperService,
    private route: ActivatedRoute,
    private router: Router,
    private http: Http
  ) {}

  ngOnInit() {
    this.loading = false;
    this.announceData = new AnnounceData();
    this.tableQueryData = new TableQueryData();
    this.tableQueryData.CurrentPage = 0;
    this.getAnnounceData(this.tableQueryData);
    this.punishTime = "ALL";
    this.punishQueryData = new PunishQueryData();
    this.punishQueryData.site = "ALL";
    this.punishQueryData.status = "ALL";
    this.punishQueryData.time = "ALL";
    this.punishQueryData.speed = "ALL";
    this.punishQueryData.method = "0";
    this.displayReadyPunishEvent = false;
    this.LawsCodeData = "";
    this.reasonPageList = [];
    this.NotPunishReasonData = "";
    this.PunishView = {};
    this.PunishEdit = {};
    this.selectPunishEventList = [];
    this.fileName = "";

    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.getPunishEvent("1", startdatetime, enddatetime, this.punishQueryData.site, this.punishQueryData.status, this.punishQueryData.time, this.punishQueryData.speed, this.punishQueryData.method);
    this.getUserSiteInfo("1");
  }


  getUserSiteInfo(eventType: string): any {
    this.sysDataService.getUserSiteInfo().subscribe(res => {
      const result = res.json().result;
      console.log(result)
      this.siteInformationList = result.filter(i => i.EventType === eventType);
      console.log(this.siteInformationList)
    }, error => (this.errorMessage = <any>error));
  }


  getPunishEvent(eventType: string, startTime: string, endTime: string, site: string, status: string, time: string, speed: string, method: string): any {

    this.boardDataService.getPunishEvent(eventType, startTime, endTime, site, status, time, speed, method).subscribe(res => {
      if (method === '0') {
        const result = res.json().Result;
        this.punishEventList = result;
        this.loading = false;
      }
    }, error => {
      this.errorMessage = <any>error._body;
      swal({
        type: "error",
        title: "錯誤訊息",
        text: JSON.parse(this.errorMessage).Message,
        showConfirmButton: false,
        timer: 2000,
            onOpen: () => {

            },
            onClose: () => {
              this.loading = false;
            }
      });
    });
  }


  getPunishEventExport(eventType: string, site: string, status: string, time: string, speed: string, method: string): any {

    this.loading = true;
    const startTime = this.startDT.formatted + " " + this.startDT1;
    const endTime = this.endDT.formatted + " " + this.endDT1;
    if (site === null || site === undefined) {
      site = "ALL";
    }
    if (status === null || status === undefined) {
      status = "ALL";
    }
    if (time === null || time === undefined) {
      time = "ALL";
    }
    if (speed === null || speed === undefined) {
      speed = "ALL";
    }
    if (method === null || method === undefined) {
      method = "0";
    }

    this.boardDataService.getPunishEventExport(eventType, startTime, endTime, site, status, time, speed, method).subscribe(res => {
      if (method === '0') {
        const result = res.json().Result;
        this.punishEventList = 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._body;
      swal({
        type: "error",
        title: "錯誤訊息",
        text: JSON.parse(this.errorMessage).Message,
        showConfirmButton: false,
        timer: 2000,
            onOpen: () => {

            },
            onClose: () => {
              this.loading = false;
            }
      });
    });
  }


  selectPunishEvent(punishEvent) {
    console.log(punishEvent);
    const lawsCheck = this.goPunishEvent(punishEvent);
    if (lawsCheck === 0) {
      return;
    }
    if (this.selectPunishEventList.length > 0) {
      for (let index = 0; index < this.selectPunishEventList.length; index++) {
        const element = this.selectPunishEventList[index];
        if (element.Id === punishEvent.Id) {
          this.selectPunishEventList.splice(index, 1);
          return;
        } else {
          if (punishEvent.Laws === null) {
            punishEvent.isChecked = false;
            swal({
              type: "error",
              title: "無法規資料",
              text: "請檢查法規資訊...",
              showConfirmButton: true,
              timer: 2000,
              onClose: () => {


              }
            });
            return;
          }

          if (element.Laws[0].lawsCode === punishEvent.Laws[0].lawsCode) {
            this.selectPunishEventList.push(punishEvent);
            return;
          } else {

            swal({
              type: "error",
              title: "勾選失敗",
              text: "請檢查法規資訊...",
              showConfirmButton: true,
              timer: 2000,
              onClose: () => {
                punishEvent.isChecked = false;
              }
            });
            return;
          }
        }
      }
    } else {
      this.selectPunishEventList.push(punishEvent);
    }
  }


  getEventById(id: string): any {
    this.boardDataService.getEventById(id).subscribe(res => {
      const result = res.json().Result;
      this.showUpdatedItem(result);
    }, error => (this.errorMessage = <any>error));
  }


  showUpdatedItem(newItem) {
    const updateItem = this.punishEventList.find(this.findIndexToUpdate, newItem.Id);
    const index = this.punishEventList.indexOf(updateItem);
    this.punishEventList[index].Status = newItem.Status;
    this.punishEventList[index].Ps = newItem.Ps;
    this.punishEventList[index].isChecked = false;
  }

  findIndexToUpdate(newItem) {
        return newItem.Id === this;
  }


  doCheckPunish(eventType, eventId, law) {
    this.boardDataService.putCheckPunish(eventId, law).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "開單成功",
          text: "更新頁面...",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.displayReadyPunishEvent = false;
            this.doSearch(eventType, this.punishQueryData.site, this.punishQueryData.status, this.punishQueryData.time, this.punishQueryData.speed, '0');
          }
        });
      } else {
        swal({
          type: "error",
          title: "開單失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
      }
    });
  }

  doCancel(eventType, eventId) {
    this.boardDataService.putCancel(eventId).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "取消成功",
          text: "更新頁面...",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.displayReadyPunishEvent = false;
            this.doSearch(eventType, this.punishQueryData.site, this.punishQueryData.status, this.punishQueryData.time, this.punishQueryData.speed, '0');
          }
        });
      } else {
        swal({
          type: "error",
          title: "取消失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
      }
    });
  }

  doNopunish(eventType, eventId, reason, model) {
    this.boardDataService.putNopunish(eventId, reason).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "不開單成功",
          text: "更新頁面...",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.displayReadyPunishEvent = false;
            model.hide();
            this.doSearch(eventType, this.punishQueryData.site, this.punishQueryData.status, this.punishQueryData.time, this.punishQueryData.speed, '0');
          }
        });
      } else {
        swal({
          type: "error",
          title: "不開單失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
        model.hide();
      }
    });
  }



  doEventVehicle(eventType, eventId, vehicleType, vehicleNumber, model) {
    this.boardDataService.putEventVehicle(eventId, vehicleType, vehicleNumber).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "車輛資訊更新成功",
          text: "更新頁面...",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.displayReadyPunishEvent = false;
            model.hide();
            this.doSearch(eventType, this.punishQueryData.site, this.punishQueryData.status, this.punishQueryData.time, this.punishQueryData.speed, '0');
          }
        });
      } else {
        swal({
          type: "error",
          title: "車輛資訊更新失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
        model.hide();
      }
    });
  }






  doMuticheckPunish(selectPunishEventList) {
    let eventIdList = [];
    const law = selectPunishEventList[0].Laws[0].lawsCode;
    for (let index = 0; index < selectPunishEventList.length; index++) {
      const element = selectPunishEventList[index];
      eventIdList.push(element.Id);
    }



    this.boardDataService.putMuticheckPunish(law, eventIdList).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "批次開單成功",
          text: "更新頁面...",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.doSearch('1', this.punishQueryData.site, this.punishQueryData.status, this.punishQueryData.time, this.punishQueryData.speed, '0');
          }
        });
      } else {
        swal({
          type: "error",
          title: "批次開單失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
      }
    });

  }



  getNotPunishReasonAll() {
    this.boardDataService.getNotPunishReasonAll().subscribe(res => {
      const result = res.json().Result;
      this.reasonPageList = result;
    }, error => (this.errorMessage = <any>error));
  }





  warningModalShow(eventType, item, model) {
    model.show();
    this.Nopunish = item;
    this.Nopunish.eventType = eventType;
    this.getNotPunishReasonAll();

  }

  viewModalShow(eventType, item, model) {
    model.show();
    this.PunishView = item;
    this.PunishView.eventType = eventType;
  }

  editModalShow(eventType, item, model) {
    model.show();
    this.PunishEdit = item;
    this.PunishEdit.eventType = eventType;
  }





  getReasonData(tableQueryData: TableQueryData): any {
    this.tableQueryData.CurrentPage = tableQueryData.Page
      ? tableQueryData.Page
      : 1;
    this.setDataService.getReasonPageList(tableQueryData).subscribe(res => {
      const result = res.json().Result;
      this.reasonPageList = result.Data;
      this.loading = false;
      if (tableQueryData.Page === 1 || !tableQueryData.Page) {
        this.pageCount = result.PageCount;
        this.getPageLinks();
      }
    }, error => (this.errorMessage = <any>error));
  }





  goPunishEvent(punishEvent) {
    if (punishEvent.Laws === null) {
      punishEvent.isChecked = false;
      swal({
        type: "error",
        title: "無法規資料",
        text: "請檢查法規資訊...",
        showConfirmButton: true,
        timer: 2000,
        onClose: () => {
        }
      });
      return 0;
    } else {
      this.displayReadyPunishEvent = true;
      this.readyPunishEvent = punishEvent;
      for (let i = 0; i < this.readyPunishEvent.Laws.length; i++) {
        if (i === 0) {
          this.readyPunishEvent.Laws[i].isSelected = true;
        } else {
          this.readyPunishEvent.Laws[i].isSelected = false;
        }
      }
      this.LawsCodeData = this.readyPunishEvent.Laws[0].lawsCode;
      return 1;
    }
  }


  print() {
    document.body.innerHTML = document.getElementById('printDiv').innerHTML;
    window.print();
  }

  camera() {
    // window.open('http://3.36.48.96/localImage/', 'Image');
    window.open(this._imageURL + this.readyPunishEvent.SiteId + "/" + this.readyPunishEvent.EventID + "/", 'Image');

  }

  video() {
    // window.open('http://3.36.48.96/localVideo/', 'Video');
    window.open(this._videoURL + this.readyPunishEvent.SiteId + "/" + this.readyPunishEvent.EventID + "/", 'Video');
  }


  tabSelected($event) {
    console.log($event);
    this.displayReadyPunishEvent = false;
    this.punishEventList = [];
    if ($event.heading === '區間測速') {
      this.punishQueryData.speed = "40";
    } else {
      this.punishQueryData.speed = "ALL";
    }

    switch ($event.heading) {
      case "違規停車":
        this.getUserSiteInfo("1");
        break;
      case "區間測速":
        this.getUserSiteInfo("2");
        break;
      case "未依標線行駛_路口淨空_闖紅燈":
        this.getUserSiteInfo("3");
        break;
      case "未保持路口淨空":
        this.getUserSiteInfo("4");
        break;
      case "大貨車禁行":
        this.getUserSiteInfo("6");
        break;
    }
  }



  getAnnounceData(tableQueryData: TableQueryData): any {
    this.tableQueryData.CurrentPage = tableQueryData.Page
      ? tableQueryData.Page
      : 1;
    this.boardDataService.getAnnouncePageList(tableQueryData).subscribe(res => {
      const result = res.json().Result;
      this.announcePageList = result.Data;
      this.loading = false;
      if (tableQueryData.Page === 1 || !tableQueryData.Page) {
        this.pageCount = result.PageCount;
        this.getPageLinks();
      }
    }, 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
      });
    }
  }

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

  doSearch(eventType, site, status, time, speed, method) {
    this.selectPunishEventList = [];
    this.loading = true;

    const startTime = this.startDT.formatted + " " + this.startDT1;
    const endTime = this.endDT.formatted + " " + this.endDT1;
    if (site === null || site === undefined) {
      site = "ALL";
    }
    if (status === null || status === undefined) {
      status = "ALL";
    }
    if (time === null || time === undefined) {
      time = "ALL";
    }
    if (speed === null || speed === undefined) {
      speed = "ALL";
    }
    if (method === null || method === undefined) {
      method = "0";
    }
    this.getPunishEvent(eventType, startTime, endTime, site, status, time, speed, method);

  }

  clearSearch() {
    this.tableQueryData.Term = null;
    this.getAnnounceData(this.tableQueryData);
  }

  order(item) {
    this.IsAsc = !this.IsAsc;
    this.item = item;
    this.tableQueryData.Order = item;
    this.tableQueryData.IsAsc = this.IsAsc.toString();
    this.getAnnounceData(this.tableQueryData);
  }

  deleteAnnounceData(id): any {
    swal({
      title: "是否要刪除?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#70C2DA",
      cancelButtonColor: "#f86c6b",
      confirmButtonText: "是",
      cancelButtonText: "否"
    }).then(result => {
      if (result.value) {
        this.boardDataService.deleteAnnounceData(id).subscribe(res => {
          const result2 = res.json();
          if (result2.Success === true) {
            this.renewalPageList = this.renewalPageList.filter(u => {
              return u.Id !== id;
            });
            this.getAnnounceData(this.tableQueryData);
            this.getPageLinks();
            swal({
              type: "success",
              title: "刪除成功",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA",
              timer: 1000,
              onOpen: () => {
                swal.showLoading();
              },
              onClose: () => {}
            });
          } else {
            swal({
              type: "error",
              title: "刪除失敗",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
          }
        });
      }
    });
  }


  goDetail(item) {
    this.router.navigate(["board/board001-view-board"]);
  }

  goEdit(item) {
    this.router.navigate(["board/board001-set-board"]);
  }

}
