import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
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 {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  companyId = ""
  user: { loading: boolean, select: UserModel, dataList: { check: boolean, data: UserModel }[] } = { loading: false, select: new MyUserModel(), dataList: [] }
  search = ""

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

  changePassword = 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]; // ดึงส่วนที่เป็น Payload
    let base64 = base64Url.replace('-', '+').replace('_', '/'); // แก้ไข base64 ให้ถูกต้อง
    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 => ({ check: false, data: new MyUserModel(x) }))
        this.user.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.user.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  userListFilter() {
    return this.user.dataList.filter(x => {
      const data = x.data
      const match = data.usernameId.toLowerCase().includes(this.search.toLowerCase()) ||
        data.empId.toLowerCase().includes(this.search.toLowerCase()) ||
        data.employee.thFullName.toLowerCase().includes(this.search.toLowerCase())
      return match
    })
  }
  selectUser(data: UserModel) {
    this.user.select = new MyUserModel(data)
    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()
          this.searchChange()
        } 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()
      }
    })
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.userListFilter().length / 10) }, (_, i) => i + 1);
  }
  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',
    })
  }
}