import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../../services/common.modules';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { ActivatedRoute, Router } from '@angular/router';
import Parse from 'parse';
import { TextbookComponent } from '../../../../app/textbook/textbook.component';
import { textbookServer } from '../../../../services/textbook';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ReviewDetailsComponent } from '../../components/review-details/review-details.component'

@Component({
  selector: 'app-review-edit',
  templateUrl: './review-edit.component.html',
  styleUrls: ['./review-edit.component.scss'],
  imports: [
    CommonModule,
    NzSpaceModule,
    CommonCompModule,
    NzTabsModule,
    TextbookComponent,
    NzRadioModule,
    NzCheckboxModule,
    ReviewDetailsComponent
  ],
  standalone: true,
})
export class ReviewEditComponent implements OnInit {
  @ViewChild('textbook') textbook: TextbookComponent | any;
  id: string | null = ''; //评审组id
  eduProcess?: Parse.Object;
  expertGroup?: Parse.Object;
  setOfCheckedTextbookAll = new Set<string>(); //所有已选择教材
  setOfCheckedProfileAll = new Set<string>(); //所有已选择评委
  get checkProfileListLeng(): number {
    return Array.from(this.setOfCheckedProfileAll).length;
  }
  radio: string = 'all';
  radioReview: string = 'all';
  active:number = 0
  filterObj: any = {
    showMore: true, //显示更多字段
    isCheck: true,
    // noStared: true,
    status: ['200'],
    notContained: [], //排除id
    showText: true,
    btns: {
    },
  };
  modalValue: string = '';
  profilList: Array<Parse.Object> = [];
  loading = false;
  showTextbook:boolean = false

  allTextbook:Array<any> = [] //已选择教材列表
  showAll:boolean = false

  reviewFilterObj:any = {
    contained: [],
  }

  constructor(
    private activeRoute: ActivatedRoute,
    public tbookSer: textbookServer,
    private message: NzMessageService,
    private modal: NzModalService,
    private router: Router
  ) {}

  ngOnInit() {
    this.activeRoute.paramMap.subscribe((params) => {
      this.id = params.get('id');
      this.refresh();
    });
  }
  async refresh() {
    let query = new Parse.Query('ExpertGroup');
    query.include('eduProcess');
    query.equalTo('objectId', this.id);
    query.notEqualTo('isDeleted', true);
    let res = await query.first();
    if (res?.id) {
      this.expertGroup = res;
      this.eduProcess = res?.get('eduProcess');

      this.expertGroup.get('textbookList')?.forEach((item: any) => {
        this.setOfCheckedTextbookAll.add(item.id || item.objectId);
      });
      this.expertGroup.get('reviewList')?.forEach((item: any) => {
        this.setOfCheckedProfileAll.add(item.id || item.objectId);
      });
      //赋值给评审详情组建
      this.reviewFilterObj.contained = Array.from(this.setOfCheckedTextbookAll)
      await this.getExpertGroup()
      this.radio = res?.get('checkTextbook') ?? 'all';
      this.getProfile()
      this.getTextName()
      this.radioReview = res?.get('checkReview') ?? 'all';
      this.showTextbook = true
    }
  }
  //获取所有已选择教材名称展示
  async getTextName(){
    let query = new Parse.Query('EduTextbook');
    query.notEqualTo('isDeleted', true);
    query.containedIn('objectId', Array.from(this.setOfCheckedTextbookAll));
    query.select('title')
    let r = await query.find()
    this.allTextbook = r
  }
  //重置
  reset() {
    this.refresh();
  }
  back() {
    history.back();
  }
  async onchangeTextbook($event: string) {
    console.log($event);
    // if ($event == 'free') {
    //   await this.getExpertGroup()
    // }
    this.radio = $event;
  }

  //获取所有已被其他评审组选择过教材
  async getExpertGroup(){
    let query = new Parse.Query('ExpertGroup');
    query.include('eduProcess');
    query.notEqualTo('isDeleted', true);
    query.notEqualTo('objectId', this.expertGroup?.id);
    query.select('textbookList');
    let res = await query.find();
    res.forEach((item) => {
      item.get('textbookList')?.forEach((obj: any) => {
        this.filterObj.notContained.push(obj.id || obj.objectId);
      });
    });
  }
  async onchangeReview($event: any) {
    console.log($event);
    if ($event == 'free') {
      this.getProfile();
    }
    this.radioReview = $event;
  }
  /* 获取评委专家 */
  async getProfile() {
    this.profilList = [];
    this.loading = true;
    let queryParams: any = {
      where: {
        $or: [
          {
            user: {
              $inQuery: {
                where: {
                  $or: [
                    {
                      name: { $regex: `.*${this.modalValue}.*` },
                    },
                    {
                      username: { $regex: `.*${this.modalValue}.*` },
                    },
                    {
                      phone: { $regex: `.*${this.modalValue}.*` },
                    },
                    {
                      email: { $regex: `.*${this.modalValue}.*` },
                    },
                  ],
                },
                className: '_User',
              },
            },
          },
        ],
      },
    };
    let childrens = await this.tbookSer.getChild(
      this.tbookSer.profile.user.department?.objectId
    );
    queryParams['where']['$or'][0]['user']['$inQuery']['where']['department'] =
      {
        $in: childrens,
      };
    let query = Parse.Query.fromJSON('Profile', queryParams);
    query.include('user');
    query.notEqualTo('isDeleted', true);
    query.notEqualTo('identity', '国家级管理员');
    query.descending('createdAt');
    query.containedIn('identity', ['评审专家']);
    let r = await query.find();
    this.profilList = r;
    console.log(this.profilList);
    this.loading = false;
  }
  updateAllChecked($event: any): void {
    console.log($event);
    this.setOfCheckedProfileAll.has($event.id)
      ? this.setOfCheckedProfileAll.delete($event.id)
      : this.setOfCheckedProfileAll.add($event.id);
  }
  updateCheck(){
    console.log(this.textbook.setOfCheckedId);
    this.setOfCheckedTextbookAll = this.textbook.setOfCheckedId
    this.getTextName()
  }
  /* 保存 */
  async onSave(type: string) {
    if (type == 'eduTextbook') {
      let fileds: any = [];
      if(this.radio == 'all'){
       let list = await this.textbook.getTextbook('',{excel:true,id:true})
       list.forEach((item:any) => {
        fileds.push({
          __type: 'Pointer',
          className: 'EduTextbook',
          objectId: item.id,
        });
       });
      }else{
        Array.from(this.textbook.setOfCheckedId).forEach((item) => {
          fileds.push({
            __type: 'Pointer',
            className: 'EduTextbook',
            objectId: item,
          });
        });
      }
      this.expertGroup?.set('textbookList', fileds);
      this.expertGroup?.set('checkTextbook', this.radio);
    } else {
      let fileds: any = [];
      Array.from(this.setOfCheckedProfileAll).forEach((item) => {
        fileds.push({
          __type: 'Pointer',
          className: 'Profile',
          objectId: item,
        });
      });
      this.expertGroup?.set('reviewList', fileds);
      this.expertGroup?.set('checkReview', this.radioReview);
    }
    await this.expertGroup?.save();
    this.reviewFilterObj.contained = Array.from(this.setOfCheckedTextbookAll)
    this.message.success('设置成功');
    // this.refresh()
  }
}
