import { Component, Input,Output,EventEmitter, ChangeDetectorRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import Parse from "parse";
// import { ClusterService } from '../cluster.service';
import { ParseDataService } from '../parse-data.service';
// import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { CommonModule } from '@angular/common';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzPaginationModule } from 'ng-zorro-antd/pagination';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzResultModule } from 'ng-zorro-antd/result';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { UtilnowPipe } from '../../../pipes/utilnow.pipe';
import { NzTableModule } from 'ng-zorro-antd/table';
import { confirmDialog, openObjectEditDialog } from '../../../schemas/func-parse';
import { MatIconModule } from '@angular/material/icon';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { Router } from '@angular/router';
import { ChangeDetectionStrategy } from '@angular/compiler';

interface SchemaFiled{
  key:string,
  name:string,
  type:string,
  showName?:string,
  require?:boolean, // 是否必填
  isHeader?:boolean, // 是否表头显示 
}
@Component({
  selector: 'comp-table-list',
  templateUrl: './comp-table-list.component.html',
  styleUrls: ['./comp-table-list.component.scss'],
  standalone:true,
  imports:[CommonModule,
    UtilnowPipe,
    // TranslateModule,
    NzPaginationModule,NzEmptyModule,NzTableModule,NzResultModule,NzIconModule,
    MatButtonModule,MatCheckboxModule,MatSlideToggleModule,MatIconModule,NzModalModule
  ],
  providers:[]
})
export class CompTableListComponent {

  @Input()
  schema:any
  @Input()
  fieldsArray:Array<any>|undefined
  @Input()
  className:string|undefined
  @Input()
  queryParams:any = {}
  @Input()
  showMode:"list"|"grid" = "list"

  clearPosition(){
    this.positionMap = {}
    this.refresh();
  }
  positionMap:any = {}

  headerArray:Array<SchemaFiled>|undefined
  currentLang:string= "cn"
  constructor(
    private parseData:ParseDataService,
    // private clusterServ:ClusterService,
    private dialog:MatDialog,
    private router:Router,
    // public translate:TranslateService
    private modal: NzModalService,
    private cdRef:ChangeDetectorRef
  ){
    this.currentLang = "cn"// this.translate.getDefaultLang();
  }
  ngOnInit(){
    this.headerArray = this.fieldsArray?.filter(item=>item.isHeader==true)
    this.refresh();
  }

  createObject(){
    openObjectEditDialog(this.dialog,this.schema,undefined,()=>{
      this.refresh();
    })
  }

  batchHandle(button:any){
    // console.log(this.currentLang,'888888888888888888')
    button?.handle({
      // clusterServ:this.clusterServ,
      className:this.className,
      queryParams:this.queryParams,
      dialog:this.dialog
    },this.currentLang)
  }

  @Input()
  onButtonHandleCallBack:Function|undefined
  buttonHandle(button:any,object:any){
    let that = this
    if(button?.handle){
      button?.handle({object:object,dialog:this.dialog,router:this.router,modal:this.modal,callback:this.onButtonHandleCallBack},that.currentLang)
    }
  }
  refresh(page?:number){
    if(page){this.pageIndex=page}
    this.loadData(true)
    this.loadData()
  }
  list:Parse.Object[] = []
  pageTotal = 100;
  pageSize = 12;
  pageIndex = 1; // 从第1页开始计数
  onPageIndexChange(pageIndex:any){
    this.pageIndex = pageIndex
    this.refresh();
  }
  isLoading:boolean = false;
  async loadData(isCount:boolean=false){
    if(!this.className) return 
    let query = Parse.Query.fromJSON(this.className,this.queryParams)

    let positionList = Object.keys(this.positionMap).filter(p=>this.positionMap[p]);
    if(positionList?.length){
      query.containedIn("position",positionList)
    }

    if(this.schema?.include){
      query.include(...this.schema?.include)
    }
    query.notEqualTo("isDeleted",true)
    query.addDescending("updatedAt")
    query.skip((this.pageIndex - 1)* this.pageSize)
    query.limit(this.pageSize)
    if(isCount){
      this.pageTotal = await query.count();
      return
    }
    this.isLoading = true;
    this.list = await query.find();
    await this.fixPointerName()
    this.isLoading = false;
  }
  async fixPointerName(){
    let pointerColumns = this.fieldsArray?.filter(item=>item?.type=="Pointer")
    this.list.forEach(item=>{
      pointerColumns?.forEach(pitem=>{
        let pointer = item.get(pitem?.key)
        let id = pointer?.objectId || pointer?.id
        if(id){
          this.pointerMap[id] = pointer
        }
      })
    })
    await this.parseData.cachePointerList(Object.values(this.pointerMap))
    Object.keys(this.pointerMap).forEach(async id=>{
      let obj = this.parseData.ParseObjectCacheMap[id]
      let fieldList = this.fieldsArray?.filter(item=>item?.targetClass==obj?.className)
      fieldList?.forEach(async field=>{
        this.pointerShowMap[id+field?.showName] = await this.parseData.showNameByObj(obj,field?.showName)
        // console.log(id+field?.showName)
        // console.log(this.pointerShowMap[id+field?.showName] )
        // console.log(this.pointerShowMap )
        // this.cdRef.detectChanges()
      })
    })
  }
  pointerMap:any = {}
  pointerShowMap:any = {}

  /**
   * 行内字段处理
   */
   toggleFiled(object:any,key:any){
    object.set(key,!object.get(key))
    object.save();
   }


  /**
   * 行选择处理逻辑
   */
  checked = false;
  indeterminate = false;
  setOfCheckedId = new Set<string>();

  updateCheckedSet(id: string, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onCurrentPageDataChange(event:any): void {
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.list // .filter(({ disabled }) => !disabled);
    this.checked = listOfEnabledData.every(({ id }) => this.setOfCheckedId.has(id));
    this.indeterminate = listOfEnabledData.some(({ id }) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: string, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(checked: boolean): void {
    this.list
      // .filter(({ disabled }) => !disabled)
      .forEach(({ id }) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }
  /**
   * 选择快捷功能：批量处理
   */
  // 批量删除
   deleteSelected(){
    confirmDialog(this.dialog,{
      title:"批量删除",
      message:"删除后数据不可恢复，请谨慎操作",
      danger:true,
      handleOK:async ()=>{
        let selectedList = this.list.filter(item=>this.setOfCheckedId.has(item?.id))
        let deletePromiseList = selectedList.map(item=>{
          return new Promise((resolve=>{
            item.set("isDeleted",true);
            item.save();
          }))
        })
        try{
          await Promise.all(deletePromiseList)
        }catch(err){}
        this.refresh();
      }
    })
   }
}
