import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
import { CompTableListComponent } from '../../../app/comp-table/comp-table-list/comp-table-list.component';
// import _User from '../../../schemas/_User';
import * as Parse from 'parse';
import { CommonModule } from '@angular/common';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../services/common.modules';
// import { Profile } from '../../../schemas/Profile-list';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzModalService } from 'ng-zorro-antd/modal';
import { textbookServer } from '../../../services/textbook';
@Component({
  selector: 'app-page-user',
  templateUrl: './page-user.component.html',
  styleUrls: ['./page-user.component.scss'],
  imports: [
    CommonModule,
    RouterOutlet,
    NzSpaceModule,
    NzPageHeaderModule,
    CompTableListComponent,
    NzBreadCrumbModule,
    CommonCompModule,
    NzEmptyModule,
  ],
  standalone: true,
})
export class PageUserComponent implements OnInit {
  @ViewChild(CompTableListComponent) list: CompTableListComponent | undefined;

  // _User = _User;
  // ProfileList = Profile;
  // className: string | undefined;
  // queryParams: any | undefined;
  // fieldsArray: Array<any> | undefined;
  user: Parse.User | undefined;
  profiles: Array<any> = [];
  profileLength:number = 0 //总数据
  pageSize:number = 10
  pageIndex:number = 1
  checkedAll: boolean = false; //全选
  indeterminate = false;
  loading = false;
  searchValue: string = ''; //搜索内容
  setOfCheckedId = new Set<string>();

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

  ngOnInit(): void {
    this.activeRoute.paramMap.subscribe(async (params) => {
      this.getProfile()
    });
  }
  async getProfile() {
    this.profiles = [];
    this.loading = true;
    let queryParams:any = {
      where : {
        "$or": [{
          "user": {
            "$inQuery": {
              "where": {
                "$or": [{
                  "name": { "$regex": `.*${this.searchValue}.*`},
                  },
                ],
              },
              "className": "_User"
            }
          }
        }]
      }
    }
    if(this.tbookSer.profile.identity != '国家级管理员' && this.tbookSer.profile.user.department){
      this.tbookSer.profile.user.department
      queryParams['where']['$or'][0]['user']['$inQuery']['where']['department'] = {
        "$eq": this.tbookSer.profile.user.department?.objectId
      }
    }
    let query = Parse.Query.fromJSON('Profile',queryParams);
    query.include('user');
    query.notEqualTo('identity', '国家级管理员');
    this.profileLength = await query.count()
    query.limit(this.pageSize)
    query.skip((this.pageIndex - 1) * this.pageSize)
    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;
  }
  createUser() {}
  onItemChecked(id: string,user:string, e: boolean) {
    if(e){
      this.setOfCheckedId.add(user)
    }else{
      this.setOfCheckedId.delete(user)
    }
    this.checkedAll = this.profiles.every((item) => this.setOfCheckedId.has(item.user.objectId))
  }
  onAllChecked(checked: boolean): void {
    this.profiles.forEach((item) => {
      if(checked){
        this.setOfCheckedId.add(item.user.objectId)
      }else{
        this.setOfCheckedId.delete(item.user.objectId)
      }
    });
    this.checkedAll = checked;
  }
  async updateUser(data:any, type: string) {
    console.log(type);
    this.modal.confirm({
      nzTitle: '操作提示',
      nzContent: `确定${type}吗？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: type == '删除' ? true : false,
      nzOnOk:async () => {
        let query = new Parse.Query('_User')
        query.equalTo('objectId',data.user.objectId)
        let r = await query.first()
        if(r?.id){
          switch (type) {
            case '通过认证':
              r?.set('accountState', '已认证');
              break;
            case '禁用':
              r?.set('accountState', '已禁用');
              break;
            case '删除':
              r?.set('isDeleted', true);
              break;
          }
          await r?.save();
        }
        this.getProfile();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
    
  }

  deleteSelected(){
    this.modal.confirm({
      nzTitle: '批量删除',
      nzContent: `删除后数据不可恢复，请谨慎操作`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk:async () => {
        let selectedList = this.profiles.filter((item:any)=>this.setOfCheckedId.has(item?.id))
        let deletePromiseList = selectedList.map((item:any)=>{
          return new Promise((resolve=>{
            item.set("isDeleted",true);
            item.save();
          }))
        })
        try{
          await Promise.all(deletePromiseList)
        }
        catch(err){

        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
   }
   goDateil(id:string){
    this.route.navigate([
      '/nav-admin/manage/user/edit',
      { id:id },
    ])
  }
}
