import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { ActivatedRoute, RouterOutlet, Router } from '@angular/router';
// import { CompTableListComponent } from '../../../app/comp-table/comp-table-list/comp-table-list.component';
import { EduTextbook } from '../../../schemas/EduTextbook';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import * as Parse from 'parse';
import { CommonModule } from '@angular/common';
import { textbookServer } from '../../../services/textbook';
import { TextbookComponent } from '../../../app/textbook/textbook.component';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../services/common.modules';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzModalService } from 'ng-zorro-antd/modal';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'app-approve',
  imports: [
    CommonModule,
    RouterOutlet,
    TextbookComponent,
    // CompTableListComponent,
    NzPageHeaderModule,
    CommonCompModule,
    NzBreadCrumbModule,
    NzSpaceModule,
    NzTabsModule,
    NzInputNumberModule,
  ],
  standalone: true,
  templateUrl: './approve.component.html',
  styleUrls: ['./approve.component.scss'],
})
export class ApproveComponent implements OnInit {
  // @ViewChild(CompTableListComponent) list: CompTableListComponent | undefined;
  @ViewChild('textbook') textbook: TextbookComponent | any;
  eduProcess?: Parse.Object;

  active: number = 0;
  user: Parse.User | undefined;

  //待评分
  beforeFilterObj: any = {
    showMore: true, //显示更多字段
    isCheck: true,
    status: ['200'],
    contained: [],
    btns: {
      // export: true,
      eduReivew: true,
      mark: true,
    },
  };
  //已评审
  afterFilterObj: any = {
    showMore: true, //显示更多字段
    isCheck: false,
    status: ['200','201','300','400'],
    contained: [],
    btns: {
      eduReivew: true,
      // export: true,
    },
  };
  showText: boolean = false;
  mrakVisible: boolean = false;
  editTextbook: string | any; //评分教材
  eduReview?: Parse.Object; //评审记录
  score?: number; //填写评分
  scoreMap: any = {};
  activity?: Parse.Object;
  get authCompute(): boolean {
    return (
      this.activity?.get('startDate') < new Date() &&
      (!this.activity?.get('deadline') ||
        this.activity?.get('deadline') > new Date())
    );
  }
  get isStart(): boolean {
    return (
      !this.activity?.get('startDate') ||
      this.activity?.get('startDate') > new Date()
    );
  }
  get isEnd(): boolean {
    return (
      this.eduProcess?.get('status') != '201' ||
      this.activity?.get('deadline') < new Date()
    );
  }

  constructor(
    private message: NzMessageService,
    public tbookSer: textbookServer,
    private modal: NzModalService,
    private sanitizer: DomSanitizer
  ) {
    this.user = Parse.User.current();
  }

  async ngOnInit() {
    await this.getEduReview();
    await this.getExpertGroup();
    this.getActivity();
  }
  //获取评审记录
  async getEduReview() {
    let query = new Parse.Query('EduReview');
    query.notEqualTo('isDeleted', true);
    query.equalTo('profile', this.tbookSer.profile?.objectId);
    query.select('score', 'num', 'verify', 'eduTextbook');
    query.limit(1000);
    let r = await query.find();
    r.forEach((item) => {
      this.scoreMap[item?.get('eduTextbook').id] = {
        status: item?.get('verify')
          ? '已评审'
          : item?.get('num')
          ? '已保存'
          : '未评审',
        score: item?.get('score') ?? item?.get('num') ?? '-',
      };
    });
    console.log(this.scoreMap);
  }
  async getExpertGroup() {
    let query = new Parse.Query('ExpertGroup');
    query.notEqualTo('isDeleted', true);
    query.containedIn('reviewList', [
      {
        __type: 'Pointer',
        className: 'Profile',
        objectId: this.tbookSer.profile?.objectId,
      },
    ]);
    query.include('eduProcess');
    query.select('textbookList', 'reviewDetails', 'eduProcess');
    let r = await query.find();
    console.log(r);
    r.forEach((item) => {
      item.get('textbookList')?.forEach((obj: any) => {
        this.beforeFilterObj.contained.push(obj.id || obj.objectId);
      });
    });
    this.beforeFilterObj.contained;
    this.showText = true;
    this.eduProcess = r[0]?.get('eduProcess');
  }
  srcUrl: any;
  async getActivity() {
    let query = new Parse.Query('Activity');
    query.notEqualTo('isDeleted', true);
    query.equalTo('eduProcess', this.eduProcess?.id);
    this.activity = await query.first();
    let url = this.activity?.get('reviewDetails')?.url?.replaceAll('http://', 'https://');
    console.log(url);
    if(url){
      this.srcUrl = this.sanitizer.bypassSecurityTrustResourceUrl(
        url + '#toolbar=0'
      );
    }
  }
  openUrl(){
    let url = this.activity?.get('reviewDetails')?.url?.replaceAll('http://', 'https://');
    window.open(url)
    
    // const a = document.createElement('a'); // 创建一个&lt;a&gt;元素
    // a.href = url; // 设置链接的href属性为要下载的文件的URL
    // a.download = '报送流程'; // 设置下载文件的名称
    // document.body.appendChild(a); // 将&lt;a&gt;元素添加到文档中
    // a.click(); // 模拟点击&lt;a&gt;元素
    // document.body.removeChild(a); // 下载后移除&lt;a&gt;元素
  }
  //切换tab
  async onSelectChange(e: number) {
    console.log(e);
    switch (e) {
      case 1:
        this.afterFilterObj.contained = [];
        let query = new Parse.Query('EduReview');
        query.notEqualTo('isDeleted', true);
        query.equalTo('profile', this.tbookSer.profile?.objectId);
        query.equalTo('verify', true);
        query.select('eduTextbook');
        let r = await query.find();
        console.log(r);
        r.forEach((item) => {
          console.log(item?.get('eduTextbook')?.id);
          this.afterFilterObj.contained.push(
            item?.get('eduTextbook')?.id || item?.get('eduTextbook')?.objectId
          );
        });
        console.log(this.afterFilterObj.contained);

        break;

      default:
        await this.getEduReview();
        break;
    }
    this.active = e;
  }
  async onMarkScore(e: any) {
    console.log(e);
    if (
      this.eduProcess?.get('status') != '201' ||
      this.activity?.get('startDate') > new Date() ||
      this.activity?.get('deadline') < new Date()
    ) {
      this.message.warning('当前状态不可操作');
      return;
    }
    let query = new Parse.Query('EduReview');
    query.notEqualTo('isDeleted', true);
    query.equalTo('eduTextbook', e);
    query.equalTo('profile',this.tbookSer.profile?.objectId)
    this.eduReview = await query.first();
    if (!this.eduReview?.id) {
      let obj = Parse.Object.extend('EduReview');
      this.eduReview = new obj();
    }
    this.editTextbook = e;
    this.score = this.eduReview?.get('score') ?? this.eduReview?.get('num');
    this.mrakVisible = true;
  }
  handleCancel() {
    this.mrakVisible = false;
    this.eduReview = undefined;
    this.editTextbook = undefined;
    this.score = undefined;
  }
  /* 保存/提交评分 */
  async saveScore(type: string) {
    if (!this.score && this.score != 0) {
      this.message.warning('请填写分数');
      return;
    }
    if (type == 'submit') {
      this.modal.confirm({
        nzTitle: '确认提交打分？',
        nzContent: `提交后将不能再修改`,
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: async () => {
          this.eduReview?.set('score', this.score);
          this.eduReview?.set('eduTextbook', {
            __type: 'Pointer',
            className: 'EduTextbook',
            objectId: this.editTextbook,
          });
          this.eduReview?.set('profile', {
            __type: 'Pointer',
            className: 'Profile',
            objectId: this.tbookSer.profile?.objectId,
          });
          this.eduReview?.set('verify', true);
          await this.eduReview?.save();
          this.message.success('提交成功');
          this.textbook.scoreMap[this.editTextbook] = {
            status: '已评审',
            score: this.eduReview?.get('score'),
          };
          this.scoreMap = this.textbook.scoreMap;
          this.textbook.updateStatusChange();
          this.handleCancel();
        },
        nzCancelText: '取消',
        nzOnCancel: () => console.log('Cancel'),
      });
    } else {
      this.eduReview?.set('num', this.score);
      this.eduReview?.set('eduTextbook', {
        __type: 'Pointer',
        className: 'EduTextbook',
        objectId: this.editTextbook,
      });
      this.eduReview?.set('profile', {
        __type: 'Pointer',
        className: 'Profile',
        objectId: this.tbookSer.profile?.objectId,
      });
      await this.eduReview?.save();
      this.message.success('保存成功');
      this.textbook.scoreMap[this.editTextbook] = {
        status: '已保存',
        score: this.eduReview?.get('num'),
      };
      this.scoreMap = this.textbook.scoreMap;
      this.textbook.updateStatusChange();
      this.handleCancel();
    }
  }
}
