import { ChangeDetectorRef, Component } from '@angular/core';
import { ConfigService } from '@ks89/angular-modal-gallery/lib/services/config.service';
import { ToastrService } from 'ngx-toastr';
import { ConfigPermissionModel, MenuBodyModel, MyConfigPermissionModel, MyMenuBodyModel } from 'src/app/shared/model/config-permission.model';
import { ConfigPermissionService } from 'src/app/shared/services/config-permission.service';
import { NavService } from 'src/app/shared/services/navservice';
@Component({
  selector: 'app-role-permission-config',
  templateUrl: './role-permission-config.component.html',
  styleUrls: ['./role-permission-config.component.scss']
})
export class RolePermissionConfigComponent {
  pathTitle = ['การจัดการข้อมูลองค์กร', 'กำหนดสิทธิการเข้าใช้งาน']
  pageSize = 10
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  currentModal: 'add' | 'edit' | 'delete' | 'updateMenu' = "add"

  setMenuPage = false
  configPermission: { loading: boolean, select: ConfigPermissionModel, dataList: { check: boolean, data: ConfigPermissionModel }[] } = { loading: false, select: new MyConfigPermissionModel(), dataList: [] }
  menuItems: MenuBodyModel[] = []
  menuItemsShow: Map<string, boolean> = new Map();
  companyId = ""
  user_level = ""
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private navServices: NavService,
    private configPermissionService: ConfigPermissionService) {
    this.navServices.items.subscribe((items) => {
      this.menuItems = items.map(x => new MyMenuBodyModel(x as any))
    });
    this.companyId = this.decodeJWT(sessionStorage.getItem("accessToken") || '').companyid
    this.user_level = this.decodeJWT(sessionStorage.getItem("accessToken") || '').user_level
  }
  ngOnInit(): void {
    this.getConfigList()
  }
  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);
  }
  getConfigList() {
    this.configPermission.loading = true
    this.configPermission.dataList = []
    this.configPermissionService.getList().subscribe({
      next: response => {
        this.configPermission.dataList = response.map(x => ({ check: false, data: new MyConfigPermissionModel(x) }))
        this.configPermission.loading = false
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.searchChange()
        if (this.currentModal == 'updateMenu' && (this.configPermission.select.userLevel == this.user_level)) {
          window.location.reload();
        }
        this.cdr.detectChanges()
      }, error: error => {
        this.configPermission.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  configPermissionListFilter() {
    return this.configPermission.dataList.filter(x => {
      const data = x.data
      return data.userLevel.toLowerCase().includes(this.search.toLowerCase()) ||
        data.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
        data.edesc.toLowerCase().includes(this.search.toLowerCase())
    })
  }
  selectConfigPermission(data?: ConfigPermissionModel) {
    this.configPermission.select = new MyConfigPermissionModel(data)
    const menuBody: MenuBodyModel[] = JSON.parse(JSON.stringify(this.configPermission.select.menuBody))
    this.configPermission.select.menuBody = this.menuItems.map(x => new MyMenuBodyModel(x))
    this.clearDataMenu()
    this.configPermission.select.menuBody.forEach(x => {
      const configMenu = menuBody.find(y => y.id == x.id)
      if (configMenu) {
        x.show = configMenu.show
        x.children?.forEach(y => {
          const configChildren = configMenu.children.find(z => z.id == y.id)
          if (configChildren) {
            y.show = configChildren.show
          }
        })
      }
    })
    this.configPermission.select.menuBody.forEach(x => {
      this.menuItemsShow.set(x.path + x.title, true)
    })
    this.cdr.detectChanges()
  }
  toggleMenuItemsShow(key: string) {
    const currentValue = this.menuItemsShow.get(key) || false;
    this.menuItemsShow.set(key, !currentValue);
    this.cdr.detectChanges()
  }

  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.configPermissionListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck()
  }

  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.configPermissionListFilter().forEach(x => x.check = selectAll);
    this.dataListCheck();
  }

  dataListCheck() {
    const dataCheck = this.configPermissionListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
    this.numDataListChecked = this.configPermission.dataList.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }

  clearData() {
    if (this.currentModal == 'add') {
      this.selectConfigPermission()
    } else {
      this.selectConfigPermission(new MyConfigPermissionModel({ userLevel: this.configPermission.select.userLevel }))
    }
  }

  updateConfigPermission(typeApi: 'post' | 'delete') {
    this.configPermission.loading = true
    let postBody: ConfigPermissionModel = new MyConfigPermissionModel()
    let deleteBody: ConfigPermissionModel[] = []
    switch (this.currentModal) {
      case ('delete'): {
        deleteBody = this.configPermission.dataList.filter(x => x.check).map(x => new MyConfigPermissionModel(x.data))
        break;
      }
      default: {
        postBody = new MyConfigPermissionModel(this.configPermission.select)
      }
    }
    const api = {
      post: this.configPermissionService.post(postBody),
      delete: this.configPermissionService.delete(deleteBody)
    }
    api[typeApi].subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getConfigList()
        } else {
          this.showAlert(response.message, 'error')
          this.configPermission.loading = false
        }
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.configPermission.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }

  clearDataMenu() {
    this.configPermission.select.menuBody.forEach(x => {
      x.show = true
      x.children?.forEach(y => {
        y.show = false
      })
      this.cdr.detectChanges()
    })
  }
}