import { SetDataService } from "../../../service/set-data.service";
import { Router } from "@angular/router";
import swal from "sweetalert2";

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { SiteInformationData } from "app/data/SiteInformationData";

@Component({
  selector: "app-set001-set-site",
  templateUrl: "./set001-set-site.component.html"
})
export class Set001SetSiteComponent implements OnInit {
  errorMessage: String;
  data: any;
  siteInformationData: SiteInformationData;

  selectedItem: any;
  itemId: number;
  EventTypeList: any;
  companyAllInfo: any;

  constructor(
    private setDataService: SetDataService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    this.siteInformationData = new SiteInformationData();
    this.route.data.subscribe((data: { selectedItem: any }) => {
      this.selectedItem = data.selectedItem;
    });

    this.EventTypeList = [];
    this.getEventTypeId();
    this.companyAllInfo = [];
    this.getCompanyAllInfo();
  }

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

  doEditSite() {
    this.setDataService.putSiteData(this.selectedItem).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "修改成功",
          text: "轉跳回檢視頁面...",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.router.navigate(["set/set001"]);
          }
        });
      } else {
        swal({
          type: "error",
          title: "修改失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
      }
    });
  }

  backPreviousPage() {
    this.router.navigateByUrl("/set/set001");
  }

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