import {
  Component,
  Input,
  OnInit,
  QueryList,
  ViewChildren,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../services/common.modules';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageModule } from 'ng-zorro-antd/message';
import { NzMessageService } from 'ng-zorro-antd/message';
import Parse from 'parse';
import { textbookServer } from '../../../services/textbook';
import { NzModalService } from 'ng-zorro-antd/modal';
import { MatDialog } from '@angular/material/dialog';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { DatePipe } from '@angular/common';
import { NzPopoverModule } from 'ng-zorro-antd/popover';
import { UploadCollectComponent } from '../components/upload-collect/upload-collect.component';
import { NzCollapseModule } from 'ng-zorro-antd/collapse';

@Component({
  selector: 'app-collect-file',
  templateUrl: './collect-file.component.html',
  styleUrls: ['./collect-file.component.scss'],
  imports: [
    CommonModule,
    NzSpaceModule,
    CommonCompModule,
    NzMessageModule,
    NzEmptyModule,
    NzPopoverModule,
    UploadCollectComponent,
    NzCollapseModule,
  ],
  providers: [DatePipe],
  standalone: true,
})
export class CollectFileComponent implements OnInit {
  textbookList: Array<Parse.Object> = [];
  // eduProcess?: Parse.Object; //流程
  count: number = 0;

  limit: number = 10;
  pageIndex: number = 1;
  loading: boolean = false;
  @Input('maxWidth') maxWidth: any; //最大宽度
  @ViewChildren(UploadCollectComponent) children:
    | QueryList<UploadCollectComponent>
    | any;

  searchValue: string = '';
  time: any;
  showLoading: boolean = false; //全局
  /* 格式化拓展表字段 */
  fromatFiled(list: Array<Parse.Object>, filed: string): string {
    let arr: Array<string | null> = [];
    let isDate = false;
    list.forEach((item: Parse.Object) => {
      if (
        isDate ||
        Object.prototype.toString.call(item.get(filed)).indexOf('Date') != -1
      ) {
        arr.push(this.datePipe.transform(item.get(filed), 'yyyy-MM'));
        isDate = true;
      } else {
        arr.push(item.get(filed));
      }
    });
    let j = Array.from(arr).join(',');
    if (!isDate) {
      j = Array.from(new Set(arr)).join(' ');
    }
    return j || '-';
  }

  isVisible: boolean = false;
  currentTextbook?: Parse.Object; //当前编辑教材

  statusMap: any = {}; //任务状态
  isVisiblePreview:boolean = false
  
  constructor(
    private msg: NzMessageService,
    public tbookSer: textbookServer,
    public dialog: MatDialog,
    private route: Router,
    private datePipe: DatePipe,
    private modal: NzModalService
  ) {}

  async ngOnInit() {
    // await this.getEduProcess();
    if(!this.tbookSer.profile.user?.department?.name) return
    this.getTextbook();
  }
  async getEduProcess() {
    let query = new Parse.Query('EduProcess');
    query.notEqualTo('isDeleted', true);
    query.equalTo('profileSubmitted', this.tbookSer.profile.objectId);
    query.containedIn('status', ['400']);
    let r = await query.first();
    console.log(r);
    // this.eduProcess = r;
  }

  async getTextbook(val?: string): Promise<any[] | void> {
    if (this.loading) return;
    this.loading = true;
    try {
      let queryParams: any = {
        where: {
          $or: [
            {
              title: { $regex: `.*${val || ''}.*` },
            },
            {
              code: { $regex: `.*${val || ''}.*` },
            },
            {
              childrens: {
                $inQuery: {
                  where: {
                    $or: [
                      {
                        ISBN: { $regex: `.*${val || ''}.*` },
                      },
                    ],
                  },
                  className: 'EduTextbookVolume',
                },
              },
            },
          ],
          childrens: {
            $inQuery: {
              where: {
                editionUnit: this.tbookSer.profile.user?.department?.name,
                // editionUnit: '高等教育出版社',
              },
              className: 'EduTextbookVolume',
            },
          },
          eduProcess:{
            $inQuery: {
              where: {
                status: '400',
                collectStartData:{
                  $lt:{
                    "__type": "Date",
                    "iso": new Date()
                  },
                },
                // collectEndData:{
                //   $gt:{
                //     "__type": "Date",
                //     "iso": new Date()
                //   },
                // }
              },
              className: 'EduProcess',
            },
          }
        },
      };
      let query = Parse.Query.fromJSON('EduTextbook', queryParams);
      query.descending('updatedAt');
      query.notEqualTo('isDeleted', true);
      query.equalTo('status', '400');
      query.equalTo('recommend', true);
      query.notEqualTo('discard', true);
      query.include(
        'childrens',
        'eduProcess.profileSubmitted.user',
        'eduProcess.collectStartData',
        'eduProcess.collectEndData',
        'department'
      );
      this.count = await query.count();
      query.limit(this.limit);
      query.skip(this.limit * (this.pageIndex - 1));
      this.textbookList = await query.find();
      //获取对应出版单位管理员
      this.textbookList.forEach((item) => {
        this.statusMap[item.id] = {
          status: '待上传',
          color: '#1890ff',
          btn: '上传',
        };
        //是否保存
        let isSave = item?.get('childrens').some((child: Parse.Object) => {
          return (
            this.tbookSer.profile.user?.department?.name == child?.get('editionUnit') &&
            child?.get('collectStatus') == '100'
          );
        });
        if (isSave) {
          this.statusMap[item.id] = {
            status: '已保存',
            color: '#20c94e',
            btn: '编辑',
          };
          return;
        }
        //是否提交
        let isSbmit = item?.get('childrens').every((child: Parse.Object) => {
          return (
            this.tbookSer.profile.user?.department?.name != child?.get('editionUnit') ||
            (this.tbookSer.profile.user?.department?.name == child?.get('editionUnit') &&
              child?.get('collectStatus') == '200')
          );
        });
        console.log(isSbmit);
        if (isSbmit) {
          this.statusMap[item.id] = {
            status: '已提交',
            color: '#7a7a7a',
            btn: false,
          };
        }
      });
      console.log(this.textbookList);
      this.loading = false;
    } catch (err) {
      console.warn(err);
      this.msg.error('获取超时');
    }
    this.loading = false;
  }
  onSearch(e: string) {
    this.pageIndex = 1;
    console.log(e);
    if (this.time) clearTimeout(this.time);
    this.time = setTimeout(() => {
      this.getTextbook(e);
    }, 500);
  }
  //分页切换
  pageIndexChange(e: any) {
    console.log(e);
    this.pageIndex = e;
    this.getTextbook(this.searchValue);
  }
  //切换分页条数
  onPageSizeChange(): void {
    console.log(this.limit);
    this.pageIndex = 1;
    this.getTextbook(this.searchValue);
  }

  toUrl(url: string, param?: Object) {
    console.log(url);
    if (param) {
      this.route.navigate([url, param]);
      return;
    }
    this.route.navigate([url]);
  }
  //打开上传弹窗
  onEditModal(data: Parse.Object) {
    if (
      !data.get('eduProcess')?.get('collectStartData') ||
      !data.get('eduProcess')?.get('collectEndData') ||
      data.get('eduProcess')?.get('collectStartData') > new Date() ||
      data.get('eduProcess')?.get('collectEndData') < new Date()
    ) {
      this.msg.warning('非收集文件工作期内');
      return;
    }
    this.currentTextbook = data;
    this.isVisible = true;
  }
  handleCancel(): void {
    this.isVisible = false;
    this.isVisiblePreview = false;
    this.currentTextbook = undefined;
  }
  btnLoading: boolean = false;
  async saveCollect(type: string): Promise<any> {
    console.log(type);
    this.btnLoading = true;
    if (type == 'sbmit') {
      this.modal.confirm({
        nzTitle: '温馨提示',
        nzContent: '由于“教材资源上传”工作阶段持续时间较短，教材资源一经上传将无法撤回或修改，请务必在确认无误之后再上传。',
        nzOkText: '确定',
        nzOkType: 'primary',
        nzOkDanger: false,
        nzOnOk: async () => {
          let isVrifly = await this.saveEduTextbookVolume(type);
          if (!isVrifly) {
            this.btnLoading = false;
            this.msg.warning('已保存，填写信息不完整');
            return;
          }
          this.msg.success('提交成功');
          this.btnLoading = false;
          this.isVisible = false;
          this.getTextbook(this.searchValue);
        },
        nzCancelText: '取消',
        nzOnCancel: () => {
          this.btnLoading = false;
        },
      });
    } else {
      await this.saveEduTextbookVolume(type);
      this.msg.success('保存成功');
      this.btnLoading = false;
      this.isVisible = false;
      this.getTextbook(this.searchValue);
    }
  }

  /**上传分册数据 */
  async saveEduTextbookVolume(type: string): Promise<any> {
    let isVrifly = true; //默认都通过，若一项填写未完成，则不通过
    return Promise.all(
      this.children.map(async (comp: any) => {
        let complete = await comp.submitForm(type);
        console.log(comp?.eduTextbookVolume?.id + '===' + complete);
        if (!complete) {
          isVrifly = false;
        }
        return isVrifly;
      })
    ).then((data) => {
      console.log(isVrifly);
      return isVrifly;
    });
  }

  onCheckModal(data:Parse.Object){
    this.currentTextbook = data;
    this.isVisiblePreview = true;
  }
}
