import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Route, Router, RouterOutlet } from '@angular/router';
import { CompTableListComponent } from '../../../app/comp-table/comp-table-list/comp-table-list.component';
import _Role from '../../../schemas/_Role';
// import { TranslateService } from '@ngx-translate/core';
import * as Parse from 'parse';
import { CommonModule } from '@angular/common';
import { Department } from '../../../schemas/Department';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import { CommonCompModule } from '../../../services/common.modules';
import { NzModalModule } from 'ng-zorro-antd/modal';
import {
  NzFormatEmitEvent,
  NzTreeModule,
  NzTreeNode,
} from 'ng-zorro-antd/tree';
import {
  NzContextMenuService,
  NzDropdownMenuComponent,
} from 'ng-zorro-antd/dropdown';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzMessageService } from 'ng-zorro-antd/message';
import { textbookServer } from '../../../services/textbook';
interface nodes {
  title: string;
  key: string;
  isLeaf?: boolean;
  isParent?: boolean;
  children?: Array<any>;
}
interface depart {
  name: string;
  id?: string;
  code?: string;
  desc?: string;
  parent?: object | any;
  branch: string;
}
@Component({
  selector: 'app-page-role',
  templateUrl: './page-role.component.html',
  styleUrls: ['./page-role.component.scss'],
  imports: [
    CommonModule,
    CommonCompModule,
    RouterOutlet,
    CompTableListComponent,
    NzSpaceModule,
    NzPageHeaderModule,
    NzBreadCrumbModule,
    NzTreeModule,
    NzCheckboxModule,
    NzEmptyModule,
    NzModalModule,
    NzRadioModule,
  ],
  standalone: true,
})
export class PageRoleComponent implements OnInit {
  @ViewChild(CompTableListComponent) list: CompTableListComponent | undefined;

  // _Role = _Role
  Department = Department;
  user: Parse.User | undefined;
  className: string | undefined;
  queryParams: any | undefined;
  fieldsArray: Array<any> | undefined;
  searchValue: string = ''; //搜索内容
  nodes: Array<nodes | any> = [];
  currentDepart: nodes | any = null;

  profiles: Array<any> = [];
  checkedShowFilter: boolean = false;

  checkedAll: boolean = false; //全选
  indeterminate = false;
  loading = false;

  isVisible: boolean = false;
  activatedNode: NzTreeNode | any; //当前选择节点
  editType: string = 'add'; //弹窗类型
  activeDepart?: Parse.Object; //当前编辑部门
  editObject: depart = {
    name: '',
    code: '',
    desc: '',
    parent: {},
    branch: '',
  };
  parentMap: Array<any> = [];
  parentList: Array<any> = [];

  constructor(
    public tbookSer: textbookServer,
    private route: Router,
    private activeRoute: ActivatedRoute,
    private nzContextMenuService: NzContextMenuService,
    private message: NzMessageService,
  ) {
    this.user = Parse.User.current();
    this.className = this.Department.className;
    this.fieldsArray = this.Department.fieldsArray;
    this.queryParams = {
      where: {
        // user:this.user?.toPointer(),
        isDeleted: { $ne: true },
      },
    };
  }

  ngOnInit(): void {
    this.activeRoute.paramMap.subscribe(async (params) => {
      // let isDeleted = params.get('isDeleted');
      // if (isDeleted) {
      //   this.queryParams.where['isDeleted'] = { $eq: true };
      // } else {
      //   this.queryParams.where['isDeleted'] = { $ne: true };
      // }
      // this.list?.ngOnInit();
      if(!this.tbookSer.profile.user.department?.objectId){
        this.message.warning('权限不足')
        history.back()
        return
      }
      this.nodes = [{
        title: this.tbookSer.profile.user.department.name,
        key: this.tbookSer.profile.user.department?.objectId,
        children: [...await this.getDepart(this.tbookSer.profile.user.department?.objectId)],
        isParent: false,
        isLeaf: false,
      }];
    });
  }
  async getDepart(
    parent?: string,
    searchValue?: string
  ): Promise<Array<nodes>> {
    let nodes: any = [];
    let query = new Parse.Query('Department');
    query.equalTo('parent', parent ? parent : undefined);
    searchValue && query.contains('name', searchValue);
    query.notEqualTo('isDeleted', true);
    query.select('code', 'name', 'branch', 'parent','type');
    query.descending('createdAt');
    query.limit(2000);
    let res = await query.find();
    res.forEach((item) => {
      nodes.push({
        title: item.get('name'),
        key: item.id,
        children: [],
        isParent: item.get('type') =='单位' ? true : false, //是否是最下级
        isLeaf: false,
      });
    });
    return nodes;
  }
  //添加成员
  addMember() {
    this.message.warning('权限灰度中')
  }
  //展开/合并
  async nzEvent(event: NzFormatEmitEvent): Promise<void> {
    console.log(event);
    let node: any = event.node;
    if (event.eventName === 'expand') {
      if (node.origin.isParent) {
        node.addChildren([]);
        return;
      }
      if (node?._children.length <= 0) {
        let data = await this.getDepart(node.key);
        node.addChildren(data);
      }
      console.log(this.nodes);
    } else {
      // if (node.origin.isParent) {
        this.currentDepart = node.origin;
        this.getProfile();
      // }
    }
  }
  async getProfile() {
    this.profiles = [];
    this.loading = true;
    let queryParams = {
      where : {
        "$or": [{
          "user": {
            "$inQuery": {
              "where": {
                "$or": [{
                    "department": { "$eq": this.currentDepart.key}
                  },
                ]
              },
              "className": "_User"
            }
          }
        }]
      }
    }
    let query = Parse.Query.fromJSON('Profile',queryParams);
    query.include('user');
    query.notEqualTo('identity', '国家级管理员');
    let r = await query.find();
    let profiles: any[] = [];
    r.forEach((item) => {
      let _item = item.toJSON();
      _item['checked'] = false;
      profiles.push(_item);
    });
    this.profiles = profiles;
    this.loading = false;
  }
  //搜索触发
  onSearch(event: NzFormatEmitEvent) {
    console.log(event);
  }
  contextMenu(
    $event: MouseEvent,
    menu: NzDropdownMenuComponent,
    node?: any
  ): void {
    console.log(node);
    this.activatedNode = node;
    this.nzContextMenuService.create($event, menu);
  }
  //删除部门
  onDelDepart() {
    this.message.warning('权限灰度中')
  }

  onAllChecked(checked: boolean): void {
    console.log(checked);
    this.profiles = this.profiles.map((item) => {
      item.checked = checked;
      return item;
    });
    this.checkedAll = checked;
  }
  onItemChecked(id: string, e: boolean) {
    let checkedAll = true;
    this.profiles = this.profiles.map((item) => {
      if (id == item.objectId) item.checked = e;
      if (!item.checked) checkedAll = false;
      return item;
    });
    this.checkedAll = checkedAll;
  }
  //新建打开弹窗
  async showModalDepart(type: string) {
    if (type == 'edit') {
      let query = new Parse.Query('Department');
      let r = await query.get(this.activatedNode?.key);
      this.activeDepart = r;
      this.parentMap = this.formatNode(this.activatedNode);
      if(this.activatedNode?.parentNode?.origin.key){
        this.parentList = await this.getDepart(this.activatedNode.parentNode.origin.key);
      }
    }else{
      this.parentList = await this.getDepart(this.tbookSer.profile.user.department?.objectId)
    }
    this.editType = type;
    this.isVisible = true;
  }
  //格式化链
  formatNode(node: NzTreeNode): Array<any> {
    let arr = [];
    if (node.parentNode?.origin.title) {
      arr.push({
        title: node.parentNode?.origin.title,
        key: node.parentNode?.origin.key,
      });
      arr.unshift(...this.formatNode(node.parentNode));
    }
    return arr;
  }
  async onPre(key?:any,index?:number){
    if(!key){
      // this.parentList = await this.getDepart();
      // this.parentMap = []
      return
    }
    // if(index == this.parentMap.length-1) return
    if(index !== 0 && !index) this.parentMap.splice(index || 0+1)
    this.parentList = await this.getDepart(key);
  }
  //选择所属类别下级列表
  async onCheckedDepart(e: any, checked?: boolean) {
    console.log(e);
    if (checked) {
      this.editObject = {
        name: e.title,
        code: '',
        desc: '',
        parent: e,
        branch: '',
      };
      return;
    }
    this.parentMap.push({
      title: e.title,
      key: e.key,
    });
    this.parentList = await this.getDepart(e?.key);
  }
  handleOk(): void {
    this.message.warning('权限灰度中')
    this.isVisible = false;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
    this.activatedNode = undefined;
    this.parentMap = [];
    this.activeDepart = undefined
  }

  /* 组织 */
  showModalOrganize(){
    this.message.warning('权限灰度中')
  }
  goDateil(id:string){
    this.route.navigate([
      '/nav-admin/manage/user/edit',
      { id:id },
    ])
  }
}
