import { LoginService } from "../../../service/login.service";
import { Component, OnInit, Input } from "@angular/core";
import { SysDataService } from "app/service/sys-data.service";
import { UserData } from "../../../data/UserData";
import swal from "sweetalert2";
import { Router } from "@angular/router";
import { NgModel } from "@angular/forms";

@Component({
  selector: "app-sys001",
  templateUrl: "./sys001.component.html"
})
export class Sys001Component implements OnInit {
  @Input("fieldMatches") fieldMatches: NgModel;
  userData: UserData;
  errorMessage: string;
  constructor(
    private sysDataService: SysDataService,
    private loginService: LoginService,
    private router: Router
  ) {}

  ngOnInit() {
    this.userData = new UserData();
  }

  putUserPassword(id: string) {
    this.sysDataService.putUserPassword(this.userData).subscribe(res => {
      const result = res.json();
      if (result.Success === true) {
        swal({
          type: "success",
          title: "修改成功",
          text: "請用新密碼重新登入",
          showConfirmButton: false,
          timer: 1000,
          onOpen: () => {
            swal.showLoading();
          },
          onClose: () => {
            this.loginService.logout();
            this.router.navigate(["/login"]);
          }
        });
        localStorage.removeItem("token");
        localStorage.removeItem("role");
        localStorage.removeItem("id");
        localStorage.removeItem("password");
      } else {
        swal({
          type: "error",
          title: "修改失敗",
          text: "請檢查您輸入的密碼",
          showConfirmButton: true,
          confirmButtonColor: "#70C2DA"
        });
      }
    }, 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;
            }
      });
    });
  }
}
