import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { MyUserModel, UserModel } from 'src/app/shared/model/user.model';
import { FileService } from 'src/app/shared/services/file.service';
import { UserService } from 'src/app/shared/services/user.service';
export interface DataPassword {
  usernameId: string,
  empId: string,
  companyId: string,
  oldPassword: string,
  newPassword: string,
}
@Component({
  selector: 'app-manage-user',
  templateUrl: './manage-user.component.html',
  styleUrls: ['./manage-user.component.scss']
})
export class ManageUserComponent {
  companyId = ""
  user: { loading: boolean, select: UserModel, dataList: UserModel[] } = { loading: false, select: new MyUserModel(), dataList: [] }
  search = ""

  userPassword: DataPassword = {
    usernameId: "",
    empId: "",
    companyId: "",
    oldPassword: "",
    newPassword: "",
  }

  changePassword = false

  columns: ColumnModel[] = [{
    field: "usernameId",
    headerText: "LoginName",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "empId",
    headerText: "EmployeeCode",
    type: "string"
  },
  {
    field: "employee.fname",
    headerText: "FirstName",
    type: "string"
  },
  {
    field: "employee.lname",
    headerText: "LastName",
    type: "string"
  },
  {
    field: "status",
    headerText: "Status",
    type: "string"
  }]
  searchSettings = {
    fields: ['usernameId', 'empId', 'fname', 'lname', 'status'],
    operator: 'contains',
    ignoreCase: false
  }
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private userService: UserService) {
    this.companyId = this.decodeJWT(sessionStorage.getItem("accessToken") || '').companyid
  }
  ngOnInit(): void {
    this.getUserList()
  }

  decodeJWT(token: string) {
    let base64Url = token.split('.')[1];
    let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(jsonPayload);
  }


  getUserList() {
    this.user.loading = true
    this.userService.getList("false").subscribe({
      next: response => {
        this.user.dataList = response.map(x => {
          return new MyUserModel({ ...x, status: x.status == '1' ? 'ใช้งาน' : 'ไม่ใช้งาน' })
        })
        this.user.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.user.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectUser(data: UserModel) {
    this.user.select = new MyUserModel({ ...data, companyId: data?.companyId || this.companyId, status: data.status == 'ใช้งาน' ? '1' : '0' })
    this.userPassword = {
      usernameId: this.user.select.usernameId,
      empId: this.user.select.empId,
      companyId: this.user.select.companyId,
      oldPassword: "",
      newPassword: "",
    }
  }

  updateUserPassword() {
    if (this.changePassword) {
      this.user.loading = true
      this.userService.changePassword(this.userPassword).subscribe({
        next: response => {
          if (response.success) {
            this.updateUser()
          } else {
            this.showAlert(response.message, 'error')
            this.user.loading = false
          }
          this.cdr.detectChanges()
        }, error: error => {
          this.showAlert(error.message, 'error')
          this.user.loading = false
          this.cdr.detectChanges()
        }
      })
    } else {
      this.updateUser()
    }
  }

  updateUser() {
    this.user.loading = true
    this.userService.post(new MyUserModel(this.user.select)).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getUserList()
        } else {
          this.showAlert(response.message, 'error')
          this.user.loading = false
        }
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.user.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  selectDataModal(target: { [key: string]: any }, field: string, data: any) {
    target[field] = JSON.parse(JSON.stringify(data))
  }
  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }
}