import { Component, Input, OnInit } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonCompModule } from '../../services/common.modules';
import { Router, ActivatedRoute } from '@angular/router';
import Parse from 'parse';
import { textbookServer } from '../../services/textbook';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { MatButtonModule } from '@angular/material/button';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { DatePipe } from '@angular/common';
import { NzEmptyModule } from 'ng-zorro-antd/empty';

@Component({
  selector: 'app-textbook',
  templateUrl: './textbook.component.html',
  styleUrls: ['./textbook.component.scss'],
  imports: [
    CommonCompModule,
    FormsModule,
    ReactiveFormsModule,
    MatButtonModule,
    NzRadioModule,
    DatePipe,
    NzEmptyModule,
  ],
  standalone: true,
})
export class TextbookComponent implements OnInit {
  textbookList: Array<Parse.Object> = [];
  @Input('maxWidth') maxWidth: any; //最大宽度
  @Input('depart') depart: any; //指定申报单位
  @Input('recommend') recommend: any; //是否推荐
  @Input('uid') uid: string = ''; //个人空间

  loading: boolean = false;
  checkedAll: boolean = false; //全选
  setOfCheckedId = new Set<string>();
  searchValue: string = '';

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

  ngOnInit() {
    this.getTextbook();
  }
  async getTextbook(val?: string) {
    this.loading = true;
    let query = new Parse.Query('EduTextbook');
    if (val) {
      let query1 = Parse.Query.fromJSON('EduTextbook', {
        where: {
          $or: [
            {
              title: { $regex: `.*${val}.*` },
            },
          ],
        },
      });
      let query2 = Parse.Query.fromJSON('EduTextbook', {
        where: {
          $or: [
            {
              ISBN: { $regex: `.*${val}.*` },
            },
          ],
        },
      });
      query = Parse.Query.or(query1, query2);
    }
    if (this.tbookSer.profile.user.department?.objectId) {
      query.equalTo(
        'department',
        this.tbookSer.profile.user.department?.objectId
      );
    }
    this.depart && query.equalTo('department', this.depart);
    this.recommend && query.equalTo('recommend', true);
    this.uid && query.equalTo('user', this.uid);
    query.notEqualTo('isDeleted', true);
    this.textbookList = await query.find();
    console.log(this.textbookList);
    this.loading = false;
  }
  onSearch(e: string) {
    console.log(e);
    this.getTextbook(e);
  }
  //全选
  onAllChecked(checked: boolean) {
    console.log(checked);
    this.textbookList.forEach((item: any) => {
      if (checked) {
        this.setOfCheckedId.add(item.id);
      } else {
        this.setOfCheckedId.delete(item.id);
      }
    });
    this.checkedAll = checked;
  }
  //单选
  onItemChecked(id: string, e: boolean) {
    if (e) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.checkedAll = this.textbookList.every((item) =>
      this.setOfCheckedId.has(item.id)
    );
  }
  deleteSelected() {
    this.modal.confirm({
      nzTitle: '批量删除',
      nzContent: `删除后数据不可恢复，请谨慎操作`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let selectedList = this.textbookList.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'),
    });
  }
}
