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 { 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 { setHours } from 'date-fns';
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { UploadCollectComponent } from '../../../nav-province-contact/components/upload-collect/upload-collect.component';
import { NzCollapseModule } from 'ng-zorro-antd/collapse';
@Component({
  selector: 'app-collect-textbook',
  templateUrl: './collect-textbook.component.html',
  styleUrls: ['./collect-textbook.component.scss'],
  imports: [
    CommonModule,
    NzSpaceModule,
    CommonCompModule,
    NzMessageModule,
    NzEmptyModule,
    NzPopoverModule,
    NzDatePickerModule,
    UploadCollectComponent,
    NzCollapseModule
  ],
  providers: [DatePipe],
  standalone: true,
})
export class CollectTextbookComponent implements OnInit {
  textbookList: Array<Parse.Object> = [];
  count: number = 0;
  timeDefaultValue = setHours(new Date(), 0);

  @Input('limit') limit: number = 10;
  pageIndex: number = 1;
  loading: boolean = false;
  @Input('maxWidth') maxWidth: any; //最大宽度
  @Input('eduProcess') eduProcess?: Parse.Object; //流程id

  // @Input('filterObj') filterObj: any = {
  //   contained: [],
  // };

  showModal: boolean = false;
  textBookList: Array<Parse.Object> = []; //流程教材列表（推荐）
  collectStartData: any;
  collectEndData: 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 || '-';
  }
  manageProfiles: any = {};

  formatMapProfile(list: Array<Parse.Object>): Array<string> {
    let arr: Array<string> = [];
    list.forEach((item) => {
      arr.push(this.manageProfiles[item?.get('editionUnit')]);
    });
    return [...new Set(arr)];
  }
  statusMap: any = {}; //任务状态

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

  constructor(
    // private activeRoute: ActivatedRoute,
    // public tbookSer: textbookServer,
    private msg: NzMessageService,
    public dialog: MatDialog,
    private route: Router,
    private datePipe: DatePipe,
    private modal: NzModalService
  ) {}

  ngOnInit() {
    this.getTextbook();
  }
  async getTextbook(val?: string, review?: boolean): 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 || ''}.*` },
                      },
                      // {
                      //   author: { $regex: `.*${val || ''}.*` },
                      // },
                    ],
                  },
                  className: 'EduTextbookVolume',
                },
              },
            },
          ],
        },
      };
      let query = Parse.Query.fromJSON('EduTextbook', queryParams);
      this.eduProcess?.id && query.equalTo('eduProcess', this.eduProcess?.id);
      query.descending('updatedAt');
      query.notEqualTo('isDeleted', true);
      query.equalTo('status', '400');
      query.equalTo('recommend', true);
      query.notEqualTo('discard', true);
      query.include('childrens','department.name');
      this.count = await query.count();
      query.limit(this.limit);
      query.skip(this.limit * (this.pageIndex - 1));
      this.textbookList = await query.find();
      //获取对应出版单位管理员
      if (!review && this.textbookList.length > 0) {
        let contains: Array<string> = [];
        this.textbookList.forEach((item: any) => {
          item
            .get('childrens')
            .forEach((child: Parse.Object) =>
              contains.push(child.get('editionUnit'))
            );

          this.statusMap[item.id] = {
            status: '待上传',
            color: '#1890ff',
            btn: '提醒',
          };
          //是否保存
          // let isSave = item?.get('childrens').some((child: Parse.Object) => {
          //   return child?.get('collectStatus') == '100';
          // });
          // if (isSave) {
          //   this.statusMap[item.id] = {
          //     status: '待上传',
          //     color: '#1890ff',
          //     btn: '提醒',
          //   };
          //   return;
          // }
          //是否提交
          let isSbmit = item?.get('childrens').every((child: Parse.Object) => {
            return child?.get('collectStatus') == '200';
          });
          console.log(isSbmit);
          if (isSbmit) {
            this.statusMap[item.id] = {
              status: '已提交',
              color: '#20c94e',
              btn: '查看',
            };
          }
        });
        let queryProcess = new Parse.Query('EduProcess');
        queryProcess.notEqualTo('isDeleted', true);
        queryProcess.containedIn('name', [...new Set(contains)]);
        queryProcess.include('profileSubmitted.user');
        queryProcess.select('profileSubmitted.user.name', 'name');
        let processList = await queryProcess.find();
        console.log(processList);
        processList.forEach((i) => {
          this.manageProfiles[i?.get('name')] = i
            ?.get('profileSubmitted')
            ?.get('user')
            ?.get('name');
        });
      }
      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($event: any): void {
    console.log(this.limit);
    // this.onAllChecked(false)
    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]);
  }

  onReview(data:Parse.Object){
    this.currentTextbook = data;
    this.isVisible = true;
  }
  //短信提醒
  async onEmitMsg(data:Parse.Object){
    console.log(data);
    let unitList:Array<string> = []
    data?.get('childrens')?.forEach((item:Parse.Object) => {
      console.log(item);
      unitList.push(item?.get('editionUnit'))
    });
    let query = new Parse.Query('EduProcess')
    query.containedIn('name',[...new Set(unitList)])
    query.notEqualTo('isDeleted',true)
    query.select('profileSubmitted')
    query.include('profileSubmitted.user')
    let r = await query.find()
    let users = r?.map(item=>{
      console.log(item);
      return item?.get('profileSubmitted')?.get('user')?.get('phone')
    })
    console.log(users);
    this.modal.confirm({
      nzTitle: '短信提醒',
      nzContent: '是否短信通知单位工作联系人审核上传文件?',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: false,
      nzOnOk: () => console.log('OK'),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  //打开编辑收集文件弹窗
  async openEditCollect() {
    this.collectStartData = this.eduProcess?.get('collectStartData');
    this.collectEndData = this.eduProcess?.get('collectEndData');
    this.pageIndex = 1;
    this.searchValue = '';
    this.getTextbook();

    this.showModal = true;
  }
  handleCancel(): void {
    this.showModal = false;
  }
  //保存收集文件设置
  async editCollect() {
    if (
      !this.collectStartData ||
      !this.collectEndData ||
      this.collectStartData > this.collectEndData
    ) {
      this.msg.warning('请设置正确的开始和截止时间');
      return;
    }
    this.eduProcess?.set('collectStartData', this.collectStartData);
    this.eduProcess?.set('collectEndData', this.collectEndData);
    await this.eduProcess?.save();
    this.msg.success('设置成功');
    this.showModal = false;
  }

  /* 退回 */
  onReject(data:Parse.Object){
    console.log(data);
    this.modal.confirm({
      nzTitle: '是否退回文件？',
      nzContent: '退回后，工作联系人将需要重新提交文件。',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk:async () => {
        console.log('OK')
        let rejectPromiseList = data.get('childrens').map((volume: any) => {
          return new Promise((resolve) => {
            volume?.set('collectStatus','100')
            volume?.save().then(()=>  resolve(true))
          })
        })
        await Promise.all(rejectPromiseList);
        this.statusMap[data.id] = {
          status: '待上传',
          color: '#1890ff',
          btn: '提醒',
        };
        this.msg.success('已退回')
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
