import { HelperService } from "../../../service/helper.service";
import { SysDataService } from "../../../service/sys-data.service";
import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import { Headers, RequestOptions } from "@angular/http";
import { UserData } from "app/Data/UserData";
import { TableQueryData } from "../../../data/TableQueryData";
import { Sys002Service } from "app/views/sys/sys002/sys002.service";
import { Router } from "@angular/router";
import swal from "sweetalert2";

@Component({
  selector: "app-sys002",
  templateUrl: "./sys002.component.html"
})
export class Sys002Component implements OnInit {
  deleted = false;
  tableQueryData: TableQueryData;
  tableQuerySiteData: TableQueryData;
  IsAsc = true;
  id: number;
  userId = 3;
  item: string;
  currentPage = 0;
  pageCount = 0;
  pageLinkMarginCount = 2;
  pageLinks = [];
  userDataList = [];
  siteInformationList = [];
  errorMessage: String;
  userName: String;
  loginRole = localStorage.getItem("role");
  setRole = "1";
  loading = false;

  constructor(
    private sysDataService: SysDataService,
    private helperService: HelperService,
    private sys002Service: Sys002Service,
    private router: Router
  ) {}

  ngOnInit() {
    this.loading = true;
    this.tableQueryData = new TableQueryData();
    this.tableQueryData.CurrentPage = 0;
    this.tableQuerySiteData = new TableQueryData();
    this.tableQuerySiteData.CurrentPage = 0;
    this.getUserData(this.tableQueryData, this.id);
  }

  getUserData(tableQueryData: TableQueryData, id?: number): any {
    this.tableQueryData.CurrentPage = tableQueryData.Page
      ? tableQueryData.Page
      : 1;
    this.sysDataService.getUserPageData(tableQueryData, id).subscribe(res => {
      const result = res.json().Result;
      this.userDataList = result.Data;
      this.loading = false;
      if (tableQueryData.Page === 1 || !tableQueryData.Page) {
        this.pageCount = result.PageCount;
        this.getPageLinks();
      }
    }, error => (this.errorMessage = <any>error));
  }


  getSiteInformations(tableQueryData: TableQueryData): any {
    this.tableQueryData.CurrentPage = tableQueryData.Page
      ? tableQueryData.Page
      : 1;
    this.sysDataService.getSiteInformations(tableQueryData).subscribe(res => {
      const result = res.json().Result;
      this.siteInformationList = 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.getUserData(this.tableQueryData, this.id);
  }

  doSearch() {
    this.tableQueryData.Page = null;
    this.getUserData(this.tableQueryData, this.id);
  }

  clearSearch() {
    this.tableQueryData.Term = null;
    this.getUserData(this.tableQueryData, this.id);
  }

  order(item) {
    this.IsAsc = !this.IsAsc;
    this.item = item;
    this.tableQueryData.Order = item;
    this.tableQueryData.IsAsc = this.IsAsc.toString();
    this.getUserData(this.tableQueryData, this.id);
  }

  deleteUserData(userId: string): any {
    swal({
      title: "是否要刪除?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#70C2DA",
      cancelButtonColor: "#f86c6b",
      confirmButtonText: "是",
      cancelButtonText: "否"
    }).then(result => {
      if (result.value) {
        this.sysDataService.deleteUserData(userId).subscribe(res => {
          const result2 = res.json();
          if (result2.Success === true) {
            swal({
              type: "success",
              title: "刪除成功",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
            this.userDataList = this.userDataList.filter(u => {
              return u.Id !== userId;
            });
            this.getUserData(this.tableQueryData, this.id);
          } else {
            swal({
              type: "error",
              title: "刪除失敗",
              // text: "請檢查您輸入的資訊...",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
          }
        });
      }
    });
  }




  setUserStatus(user: any, status: number): any {
    swal({
      title: "是否要變更狀態?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#70C2DA",
      cancelButtonColor: "#f86c6b",
      confirmButtonText: "是",
      cancelButtonText: "否"
    }).then(result => {
      if (result.value) {
        this.sysDataService.putUserStatus(user.Id, status).subscribe(res => {
          const result2 = res.json();
          if (result2.Success === true) {
            swal({
              type: "success",
              title: "更新成功",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
            // this.userDataList = this.userDataList.filter(u => {
            //   return u.Id !== user.Id;
            // });
            this.getUserData(this.tableQueryData, this.id);
          } else {
            swal({
              type: "error",
              title: "更新失敗",
              // text: "請檢查您輸入的資訊...",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
          }
        });
      }
    });
  }


  setUserPassword(user: any): any {
    swal({
      title: "是否要初始化密碼?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#70C2DA",
      cancelButtonColor: "#f86c6b",
      confirmButtonText: "是",
      cancelButtonText: "否"
    }).then(result => {
      if (result.value) {
        this.sysDataService.putUserPasswordById(user.Id).subscribe(res => {
          const result2 = res.json();
          if (result2.Success === true) {
            swal({
              type: "success",
              title: "密碼初始化成功",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
            // this.userDataList = this.userDataList.filter(u => {
            //   return u.Id !== user.Id;
            // });
            this.getUserData(this.tableQueryData, this.id);
          } else {
            swal({
              type: "error",
              title: "密碼初始化失敗",
              // text: "請檢查您輸入的資訊...",
              showConfirmButton: true,
              confirmButtonColor: "#70C2DA"
            });
          }
        });
      }
    });
  }



  getGroupCodeText(id: number) {
    return this.helperService.getGroupCodeText(id);
  }

  getRoleCodeText(roleId: number) {
    return this.helperService.getRoleCodeText(roleId);
  }

  goUserDetail(user) {
    this.sys002Service.selectedUser = user;
    this.router.navigate(["sys/sys002-view-user"]);
  }

  goEditUser(user) {
    this.sys002Service.selectedUser = user;
    this.router.navigate(["/sys/sys002-set-user"]);
  }
}
