import { Component, Input, OnInit } 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 { CompTableListComponent } from '../../../app/comp-table/comp-table-list/comp-table-list.component';
import { ProcessCreateComponent } from './process-create/process-create.component';
import { TextbookComponent } from '../../../app/textbook/textbook.component';
import { textbookServer } from '../../../services/textbook';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import * as compute from '../../../services/compute';
import { NzModalService } from 'ng-zorro-antd/modal';
@Component({
  selector: 'app-page-process',
  templateUrl: './page-process.component.html',
  styleUrls: ['./page-process.component.scss'],
  imports: [
    CommonModule,
    NzSpaceModule,
    CommonCompModule,
    NzTabsModule,
    ProcessCreateComponent,
    CompTableListComponent,
    TextbookComponent,
    DatePipe,
  ],
  standalone: true,
  providers: [DatePipe],
})
export class PageProcessComponent implements OnInit {
  active: number = 0;
  eduProcess: Parse.Object | undefined;

  user: Parse.User | undefined;
  //待审核
  beforeFilterObj: any = {
    showMore: true, //显示更多字段
    isCheck: true,
    noStared: true,
    status: ['200'],
    btns: {
      // reject: true, //退回教材
      // star: true, //移除推荐
      export: true,
    },
  };
  //已加入推荐
  afterFilterObj: any = {
    showMore: true, //显示更多字段
    isCheck: true,
    status: ['200', '201', '400'],
    btns: {
      // verify:true,
      // remove: true, //移除推荐
      export: true,
    },
  };
  activity?: Parse.Object;
  get authCompute(): boolean {
    return (
      this.activity?.get('startDate') < new Date() &&
      (!this.activity?.get('deadline') ||
        this.activity?.get('deadline') > new Date())
    );
  }
  constructor(
    private activeRoute: ActivatedRoute,
    public tbookSer: textbookServer,
    private router: Router,
    private msg: NzMessageService,
    private modal: NzModalService
  ) {
    this.user = Parse.User.current();
  }

  ngOnInit() {
    this.activeRoute.paramMap.subscribe(async (params) => {
      let id = params.get('id');
      if (id) {
        let query = new Parse.Query('EduProcess');
        query.include('branch', 'department');
        query.equalTo('objectId', id);
        query.notEqualTo('isDeleted', true);
        let res = await query.first();
        if (res?.id) {
          let vrifly = await this.tbookSer.getEduProcess(
            res.get('department').id
          );
          if (vrifly) {
            this.beforeFilterObj.btns = {
              reject: true, //退回教材
              star: true, //移除推荐
              export: true,
            };
            this.afterFilterObj.btns = {
              verify: true,
              remove: true, //移除推荐
              export: true,
            };
          }
        }
        this.eduProcess = res;
        this.getActivity();
        this.getExpertGroup();
      }
    });
  }
  async getActivity() {
    let query = new Parse.Query('Activity');
    query.notEqualTo('isDeleted', true);
    query.equalTo('eduProcess', this.eduProcess?.id);
    this.activity = await query.first();
    //如果已到期，退回遴选中状态
    if (
      this.activity?.get('deadline') < new Date() &&
      this.eduProcess?.get('status') == '201'
    ) {
      this.eduProcess?.set('status', '200');
      await this.eduProcess.save();
    }
  }
  /**评审组 */
  expertGroupLength: Number = 0;
  async getExpertGroup() {
    let query = new Parse.Query('ExpertGroup');
    query.equalTo('eduProcess', this.eduProcess?.id);
    query.notEqualTo('isDeleted', true);
    query.descending('updatedAt'); //大到小
    this.expertGroupLength = await query.count();
  }
  onCreateProcess() {
    this.router.navigate([
      '/nav-admin/manage/process/create',
      { cid: this.eduProcess?.id },
    ]);
  }
  toUrl(url: string, params?: object) {
    if (params) {
      this.router.navigate([url, params]);
    } else {
      this.router.navigate([url]);
    }
  }
  /* 开始活动 */
  async startActivity() {
    console.log(this.activity);
    if (!this.activity?.id || !this.activity?.get('startDate')) {
      this.msg.error('请先创建活动或设置活动开始时间');
      return;
    }
    if (this.activity?.get('deadline') < new Date()) {
      this.msg.error('评审活动时间已结束');
      return;
    }
    this?.eduProcess?.set('status', '201');
    await this.eduProcess?.save();
    this.msg.success('活动已启动');
    this.ngOnInit();
  }
  /* 计算平均分 */
  isLoading: boolean = false;
  async onCompute() {
    if (this.isLoading) return;
    this.isLoading = true;
    try {
      let queryExpertGroup = new Parse.Query('ExpertGroup');
      queryExpertGroup.notEqualTo('isDeleted', true);
      queryExpertGroup.equalTo('eduProcess', this.eduProcess?.id);
      // queryExpertGroup.select('textbookList')
      queryExpertGroup.include('textbookList');
      let expertGroupList = await queryExpertGroup.find();
      for (let index = 0; index < expertGroupList.length; index++) {
        const item = expertGroupList[index];
        if (!item?.get('textbookList')?.length) continue;
        for (let j = 0; j < item?.get('textbookList').length; j++) {
          const book: Parse.Object = item?.get('textbookList')[j];
          let obj = await this.getEduReview(book.id);
          console.log(obj);
          // console.log(book?.get('title') + '平均分' + num);
          if (obj.count) {
            if (
              item?.get('calculation') == 'truncatedMean' &&
              obj.sort.length > 3
            ) {
              let cut = compute.addNum(
                obj.sort[0],
                obj.sort[obj.sort.length - 1]
              );
              obj.total = compute.subtraction(obj.total, cut);
              book.set('score', compute.accDiv(obj.total, obj.count - 2));
            } else {
              book.set('score', compute.accDiv(obj.total, obj.count));
            }
            await book.save();
          }
        }
      }
      this.msg.success('计算完成');
    } catch (err) {
      this.msg.error('计算错误');
    }
    this.isLoading = false;
  }
  async getEduReview(
    bookid: string
  ): Promise<{ total: number; count: number; sort: Array<any> }> {
    let score = 0,
      count = 0,
      arrScore: Array<any> = [];
    let queryExpertGroup = new Parse.Query('EduReview');
    queryExpertGroup.notEqualTo('isDeleted', true);
    queryExpertGroup.equalTo('verify', true);
    queryExpertGroup.equalTo('eduTextbook', bookid);
    queryExpertGroup.exists('score');
    count = await queryExpertGroup.count();
    let r = await queryExpertGroup.find();
    r?.forEach((item) => {
      // console.log(item.get('score'));
      score = compute.addNum(score, item.get('score'));
      arrScore.push(item?.get('score'));
    });
    return {
      total: score,
      count: count,
      sort: arrScore.sort(),
    };
  }
  //结束
  onCease() {
    if (this.eduProcess?.get('status') != '201') {
      this.msg.warning('当前流程非评审中');
      return;
    }
    if (this.activity?.get('deadline') > new Date()) {
      this.modal.confirm({
        nzTitle: '结束评审活动',
        nzContent: '当前评审活动结束时间暂未到期，是否结束评审活动？',
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOnOk: async () => {
          this.activity?.set('deadline', new Date());
          this.activity?.save();
          this.eduProcess?.set('status', '200');
          this.eduProcess?.save();
          this.msg.success('已结束');
        },
        nzCancelText: '取消',
        nzOnCancel: () => console.log('Cancel'),
      });
    } else {
      this.eduProcess?.set('status', '200');
      this.eduProcess?.save();
      this.msg.success('已结束');
    }
  }
  back() {
    history.back();
  }
}
