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 { ReasonData } from "app/data/ReasonData";

@Component({
  selector: "app-set002-set-reason",
  templateUrl: "./set002-set-reason.component.html"
})
export class Set002SetReasonComponent implements OnInit {
  errorMessage: String;
  data: any;
  reasonData: ReasonData;

  selectedItem: any;
  itemId: number;

  selectEventTypeId: any;

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

  ngOnInit() {
    this.reasonData = new ReasonData();
    this.route.data.subscribe((data: { selectedItem: any }) => {
      this.selectedItem = data.selectedItem;
    });
    this.getEventTypeId();
  }

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

  doEditReason() {
    this.setDataService.putReasonData(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/set002"]);
          }
        });
      } else {
        swal({
          type: "error",
          title: "修改失敗",
          text: "請檢查您輸入的資訊...",
          showConfirmButton: true
        });
      }
    });
  }

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