import { ChangeDetectorRef, Component } from '@angular/core';
import { ConfigService } from '@ks89/angular-modal-gallery/lib/services/config.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
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 = ['menu.Organization', 'menu.AccessPermissions']

  search = ""

  currentModal: 'add' | 'edit' | 'delete' | 'updateMenu' = "add"

  setMenuPage = false
  configPermission: { loading: boolean, select: ConfigPermissionModel, dataList: ConfigPermissionModel[] } = { loading: false, select: new MyConfigPermissionModel(), dataList: [] }
  menuItems: MenuBodyModel[] = []
  menuItemsShow: Map<string, boolean> = new Map();
  companyId = ""
  user_level = ""

  columns: ColumnModel[] = [{
    field: "userLevel",
    headerText: "Level",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "DescriptionThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "DescriptionEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['userLevel', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private navServices: NavService,
    private configPermissionService: ConfigPermissionService) {
    this.navServices.itemsBack.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];
    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);
  }
  getConfigList() {
    this.configPermission.loading = true
    this.configPermission.dataList = []
    this.selectedItems.data.clear()
    this.configPermissionService.getList().subscribe({
      next: response => {
        this.configPermission.dataList = response.map(x => {
          this.selectedItems.data.set(x.userLevel, false)
          return new MyConfigPermissionModel(x)
        })
        this.selectedItems.key = 'userLevel'
        this.selectedItems.count = 0
        this.configPermission.loading = false
        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()
      }
    })
  }


  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, false)
    })
    this.cdr.detectChanges()
  }
  toggleMenuItemsShow(key: string) {
    const currentValue = this.menuItemsShow.get(key) || false;
    this.menuItemsShow.set(key, !currentValue);
    this.cdr.detectChanges()
  }


  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'): {
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        deleteBody = this.configPermission.dataList.filter(x => selectedKeys.includes(x.userLevel) && this.selectedItems.data.get(x.userLevel)).map(x => new MyConfigPermissionModel(x))
        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()
    })
  }

  checkPrimary() {
    return this.configPermission.dataList.find(x => x.userLevel == this.configPermission.select.userLevel)
  }

  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.configPermission.dataList.filter(x => selectedKeys.includes(x.userLevel) && this.selectedItems.data.get(x.userLevel)).length
    return num
  }

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }
}
