import { Component, EventEmitter, Input, OnInit, Output } 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';
import * as major from '../../services/majors.map';
import { NzPopoverModule } from 'ng-zorro-antd/popover';
interface filter {
  lang: any;
  majorPoniter: any;
  editionUnit: any;
  approval: any;
  carrierShape: any;
  department: any;
}
@Component({
  selector: 'app-textbook',
  templateUrl: './textbook.component.html',
  styleUrls: ['./textbook.component.scss'],
  imports: [
    CommonCompModule,
    FormsModule,
    ReactiveFormsModule,
    MatButtonModule,
    NzRadioModule,
    DatePipe,
    NzEmptyModule,
    NzPopoverModule,
  ],
  standalone: true,
  providers: [DatePipe],
})
export class TextbookComponent implements OnInit {
  textbookList: Array<Parse.Object> = [];
  count: number = 0;
  @Input('limit') limit: number = 10;
  pageIndex: number = 1;

  @Input('maxWidth') maxWidth: any; //最大宽度
  @Input('depart') depart: any; //指定申报单位
  @Input('recommend') recommend: any; //是否推荐
  @Input('uid') uid: string = ''; //个人空间
  @Input('path') path: string = '/common/textbook/details';
  @Input('discard') discard: Boolean = false; //是否删除
  @Input('eduProcess') eduProcess?: Parse.Object; //流程id，verify存在时需要
  @Output() updateCheck: EventEmitter<any> = new EventEmitter<any>();
  @Output() markScore: EventEmitter<any> = new EventEmitter<any>();

  //相关权限配置
  @Input('filterObj') filterObj: any = {
    status: [],
    showMore: false, //显示更多字段
    isCheck: true,
    noStared: false, //非推荐
    team: false, //只获取当前部门或下级部门所属用户的教材，且不限制是否提交
    showText: false, //选择后不展示定位btns，只展示相关教材名称列表
    notContained: [], //不包含教材（查询时自动排除）
    contained:[], //包含查询（查询只获取在数组内的id）
    btns: {
      edit: false, //编辑
      isDelete: false, //删除权限
      review: false, //预览
      reject: false, //退回教材
      star: false, //加入推荐
      remove: false, //移除推荐
      submit: false, //提交
      beforSubmit: false, //高校联系人提交至工作联系人
      export: false, //导出附件
      verify: false, //提交推荐权限
      restore: false, //恢复教材
      eduReivew: false, //在线预览
      mark: false, //打分
    },
  };
  @Input('scoreMap') scoreMap:any = {} //评分状态

  listOfColumns: any = {
    lang: {
      listOfFilter: [
        { value: '中文', text: '中文' },
        { value: '英文', text: '英文' },
        { value: '其他外国语', text: '其他外国语' },
        { value: '中国少数名族语言', text: '中国少数名族语言' },
      ],
      onChange: (data: any) => {
        console.log(data);
        this.filters.lang.value = data;
        this.onFilter();
      },
    },
    majorPoniter: {
      listOfFilter: [],
      onChange: (data: any) => {
        console.log(data);
        this.filters.majorPoniter.value = data;
        this.onFilter();
      },
    },
    editionUnit: {
      listOfFilter: [],
      onChange: (data: any) => {
        console.log(data);
        this.filters.editionUnit.value = data;
        this.onFilter();
      },
    },
    approval: {
      listOfFilter: [
        {
          value: '经中央有关部门审定的教材（已点对点通知）',
          text: '经中央有关部门审定的教材（已点对点通知）',
        },
        {
          value: '首届全国教材建设奖优秀教材（高等教育类）教材',
          text: '首届全国教材建设奖优秀教材（高等教育类）教材',
        },
        { value: '“101计划”核心教材', text: '“101计划”核心教材' },
        {
          value: '“四新”重点建设教材（含战略性新兴领域教材）',
          text: '“四新”重点建设教材（含战略性新兴领域教材）',
        },
        { value: '否', text: '否' },
      ],
      onChange: (data: any) => {
        console.log(data);
        this.filters.approval.value = data;
        this.onFilter();
      },
    },
    carrierShape: {
      listOfFilter: [
        { value: '纸质教材', text: '纸质教材' },
        { value: '数字教材', text: '数字教材' },
        { value: '纸质教材附带电子资源', text: '纸质教材附带电子资源' },
      ],
      onChange: (data: any) => {
        console.log(data);
        this.filters.carrierShape.value = data;
        this.onFilter();
      },
    },
    department: {
      listOfFilter: [],
      onChange: (data: any) => {
        console.log(data);
        this.filters.department.value = data;
        this.onFilter();
      },
    },
    status: {
      listOfFilter: [
        { value: '已保存', text: '已保存' },
        { value: '未评审', text: '未评审' },
        { value: '已评审', text: '已评审' },
      ],
      onChange: (data: [any]) => {
        // console.log(data);
        // console.log(this.filterObj.contained);
        // console.log(this.scoreMap);
        this.statusFilter = data
        this.updateStatusChange()
      },
    },
  };
  updateStatusChange(){
    this.filterObj.contained = this.initContained?.map(item=> item)
    this.filterObj.contained = this.filterObj.contained?.filter((item:string)=>{
      if(this.statusFilter?.length < 1){
        return item
      }else{
        if(this.statusFilter.includes(this.scoreMap[item]?.status)){
          return item
        }else if(!this.scoreMap[item]?.status && this.statusFilter.includes('未评审')){
          return item
        }
      }
      return
    })
    // console.log(this.filterObj.contained);
    this.pageIndex = 1
    this.getTextbook(this.searchValue)
  }
  statusFilter:Array<string> = []
  initContained:Array<string> = []

  //筛选条件
  filters: filter | any = {
    lang: { type: 'EduTextbookVolume', value: [] },
    majorPoniter: { type: 'EduTextbookVolume', value: [] },
    editionUnit: { type: 'EduTextbookVolume', value: [] },
    approval: { type: 'EduTextbook', value: [] },
    carrierShape: { type: 'EduTextbookVolume', value: [] },
    department: { type: 'EduTextbook', value: [] },
  };
  loading: boolean = false;
  checkedAll: boolean = false; //全选
  @Input('setOfCheckedId') setOfCheckedId = new Set<string>();
  searchValue: string = '';
  manage: boolean = false;
  calc: number = 150;

  showLoading: boolean = false; //全局
  /* 格式化拓展表字段 */
  fromatFiled(list: Array<Parse.Object>, filed: string): string {
    let arr: Array<string | null> = [];
    let isDate = false;
    list.forEach((item: Parse.Object) => {
      // arr.add(item.get(filed))
      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 || '-';
  }

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

  ngOnInit() {
    this.activeRoute.paramMap.subscribe(async (params) => {
      // this.eduProcessId = params.get('id');
      let arr = ['review', 'verify', 'eduReivew', 'mark'];
      Object.keys(this.filterObj?.btns).forEach((key) => {
        if (this.filterObj[key] && !arr.includes(key)) this.calc += 70;
      });
      this.getTextbook();
      if (Object.values(this.filterObj?.btns).some((item) => item)) {
        this.manage = true;
      }
      if (this.filterObj.showMore) {
        this.listOfColumns.majorPoniter.listOfFilter = major.majors.options.map(
          (item) => {
            return { text: item.name, value: item.name };
          }
        );
        this.listOfColumns.editionUnit.listOfFilter =
          await this.getDepartment();
        this.listOfColumns.department.listOfFilter = await this.getDepartment(
          true
        );
      }
      this.filterObj?.contained && this.initContained.push(...this.filterObj.contained) //需包含的数组再次赋值给原始查询，防止筛选重置问题
    });
  }
  async getTextbook(
    val?: string,
    exported?: { excel: boolean; id: boolean }
  ): Promise<any[] | void> {
    this.loading = true;
    let queryParams: any = {
      where: {
        $or: [
          {
            title: { $regex: `.*${val || ''}.*` },
          },
          {
            childrens: {
              $inQuery: {
                where: {
                  $or: [
                    {
                      ISBN: { $regex: `.*${val || ''}.*` },
                    },
                    {
                      author: { $regex: `.*${val || ''}.*` },
                    },
                  ],
                },
                className: 'EduTextbookVolume',
              },
            },
          },
        ],
      },
    };
    let query1 = Parse.Query.fromJSON('EduTextbook', queryParams);
    let query = Parse.Query.or(query1);
    let queryParams2: any = {
      where: {},
    };
    for (const key in this.filters) {
      const element = this.filters[key];
      if (element.value?.length > 0 && element.type == 'EduTextbookVolume') {
        if (!queryParams2['where']['childrens']) {
          queryParams2['where']['childrens'] = {
            $inQuery: {
              where: {
                [key]: { $in: element.value },
              },
              className: 'EduTextbookVolume',
            },
          };
        } else {
          queryParams2['where']['childrens']['$inQuery']['where'][key] = {
            $in: element.value,
          };
        }
      } else if (element.value?.length > 0 && element.type == 'EduTextbook') {
        queryParams2['where'][key] = { $in: element.value };
      }
    }
    let vrifly = Object.keys(queryParams2['where']).some(
      (item) => Object.values(item).length > 0
    );
    if (vrifly) {
      query = Parse.Query.and(
        Parse.Query.fromJSON('EduTextbook', queryParams2),
        query
      );
    }
    if (this.filterObj.team) {
      let childrens = await this.tbookSer.getChild(
        this.tbookSer.profile.user.department?.objectId
      );
      let query3 = Parse.Query.fromJSON('EduTextbook', {
        where: {
          $or: [
            {
              user: {
                $inQuery: {
                  where: {
                    department: { $in: [childrens] },
                  },
                  className: '_User',
                },
              },
            },
          ],
        },
      });
      if (vrifly) {
        query = Parse.Query.and(
          query3,
          Parse.Query.fromJSON('EduTextbook', queryParams2),
          query
        );
      } else {
        query = Parse.Query.and(query3, query);
      }
    }
    this.eduProcess?.id && query.equalTo('eduProcess', this.eduProcess.id);
    this.depart && query.equalTo('department', this.depart);
    this.recommend && query.equalTo('recommend', true);
    this.filterObj?.noStared && query.notEqualTo('recommend', true);
    this.uid && query.equalTo('user', this.uid);
    this.filterObj?.notContained &&
      query.notContainedIn('objectId', this.filterObj.notContained);
    this.filterObj?.contained && query.containedIn('objectId', this.filterObj.contained);
    query.descending('createdAt');
    query.notEqualTo('isDeleted', true);
    if (!this.uid && !this.filterObj.team) {
      query.equalTo('render', true);
    }
    if (this.filterObj?.status?.length > 0) {
      query.containedIn('status', this.filterObj?.status);
    }
    if (this.discard) {
      query.equalTo('discard', true);
    } else {
      query.notEqualTo('discard', true);
    }
    if (exported?.excel) {
      query.limit(1000);
      if (exported?.id) {
        query.select('objectId');
      }
      let r = await query.find();
      this.loading = false;
      return r;
    }
    query.include('department', 'childrens');
    this.count = await query.count();
    query.limit(this.limit);
    query.skip(this.limit * (this.pageIndex - 1));
    // query.include('user')
    this.textbookList = await query.find();
    console.log(this.textbookList);
    this.checkedAll = this.textbookList.every((item) =>
      this.setOfCheckedId.has(item.id)
    );
    this.loading = false;
  }
  async getDepartment(all?: boolean): Promise<any> {
    let arr: { value: any; text: any }[] = [];
    let filters = [
      '66865e1c5d561921fb4d6764',
      '66865deea3ac903090a7b30b',
      '66865dac288c15c56afd80fa',
      '66865d66ad23a23355b12aa7',
    ];
    if (this.tbookSer.profile.identity != '国家级管理员') {
      filters = [this.tbookSer.profile.user?.department?.objectId];
    }
    let query = new Parse.Query('Department');
    query.select('name');
    query.notEqualTo('isDeleted', true);
    if (all) {
      query.containedIn('parent', filters);
    } else {
      query.equalTo('parent', '66865d66ad23a23355b12aa7');
    }
    query.limit(2000);
    let r = await query.find();
    r.forEach((item) => {
      arr.push({
        value: all ? item.id : item?.get('name'),
        text: item?.get('name'),
      });
    });
    return arr;
  }
  //筛选
  onFilter() {
    this.textbookList = [];
    this.pageIndex = 1;
    this.getTextbook(this.searchValue);
  }
  time:any //节流
  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);
  }
  //全选
  onAllChecked(checked: boolean) {
    console.log(checked);
    this.textbookList.forEach((item: any) => {
      if (checked) {
        this.setOfCheckedId.add(item.id);
      } else {
        this.setOfCheckedId.delete(item.id);
      }
    });
    if (!checked) {
      this.setOfCheckedId = new Set<string>();
    }
    this.checkedAll = checked;
    this.updateCheck.emit(); //选项变更触发传递事件父组建
  }
  //单选
  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)
    );
    this.updateCheck.emit(); //选项变更触发传递事件父组建
  }
  //退回
  reject(data?: Parse.Object) {
    if (this.eduProcess?.get('status') != '200') {
      this.message.warning('当前流程状态非遴选中，不可此操作');
      return;
    }
    this.modal.confirm({
      nzTitle: '退回教材',
      nzContent: `确定退回吗？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        if (data?.id) {
          data.set('status', '300');
          data.set('render', null);
          // data.set('code', null);
          await data.save();
        } else {
          let selectedList = this.textbookList.filter((item: any) =>
            this.setOfCheckedId.has(item?.id)
          );
          let deletePromiseList = selectedList.map((item: any) => {
            return new Promise((resolve) => {
              item.set('status', '300');
              item.set('render', null);
              // item.set('code', null);
              item.save().then(() => resolve(true));
            });
          });
          try {
            await Promise.all(deletePromiseList);
          } catch (err) {}
        }
        this.getTextbook();
        this.onAllChecked(false);
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  //删除
  del(data?: Parse.Object) {
    console.log(data);
    this.modal.confirm({
      nzTitle: '删除教材',
      nzContent: `删除后数据不可恢复，请谨慎操作`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        if (data?.id) {
          data.set('discard', true);
          await data.save();
        } else {
          let selectedList = this.textbookList.filter((item: any) =>
            this.setOfCheckedId.has(item?.id)
          );
          let deletePromiseList = selectedList.map((item: any) => {
            return new Promise((resolve) => {
              item.set('discard', true);
              item.save().then(() => resolve(true));
            });
          });
          try {
            await Promise.all(deletePromiseList);
          } catch (err) {}
        }
        this.getTextbook();
        this.onAllChecked(false);
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  //加入/移除推荐
  updateStatus(data?: Parse.Object, recommend?: boolean) {
    if (this.eduProcess?.get('status') != '200') {
      this.message.warning('当前流程状态非遴选中，不可此操作');
      return;
    }
    this.modal.confirm({
      nzTitle: `${recommend ? '加入' : '移除'}推荐`,
      nzContent: `确定${recommend ? '加入' : '移除'}推荐吗？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: !recommend,
      nzOnOk: async () => {
        if (data?.id) {
          data.set('recommend', recommend);
          await data.save();
          this.getTextbook();
        } else {
          let selectedList = this.textbookList.filter((item: any) =>
            this.setOfCheckedId.has(item?.id)
          );
          let deletePromiseList = selectedList.map((item: any) => {
            return new Promise((resolve) => {
              item.set('recommend', recommend);
              item.save().then(() => resolve(true));
            });
          });
          try {
            await Promise.all(deletePromiseList);
            this.getTextbook();
          } catch (err) {}
        }
        this.onAllChecked(false);
        if (this.filterObj?.btns?.verify) {
          history.go();
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  //提交教材
  async submit(data?: Parse.Object) {
    if (!this.tbookSer?.profile?.user?.department?.objectId) {
      this.message.error('当前账号暂未绑定所属单位');
      return;
    }
    let parentMap = await this.tbookSer.formatNode(
      this.tbookSer?.profile?.user?.department?.objectId
    );
    console.log(parentMap);
    let processId = await this.getEduProcess(parentMap[1]?.key);
    if (!processId) {
      this.message.warning('你的申报单位暂无进行的流程');
      return;
    }
    let inviteUnit = parentMap[1]?.title; //推荐单位
    let status = '200';
    if (
      parentMap[0]?.title == '省级教育行政部门' ||
      parentMap[0]?.title == '有关部门（单位）教育司（局）'
    ) {
      status = '103';
    }
    this.modal.confirm({
      nzTitle: '确认提交教材？',
      nzContent: `申报书提交后不可修改。
      - 请在获得推荐资质后根据相关要求做好联系出版社上传教材等准备工作；并提醒、确认相应出版社到申报系统申请工作联系人账号。
      - 请务必确保函报材料与系统填报材料保持一致，否则不予受理。`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: false,
      nzOnOk: async () => {
        if (data?.id) {
          if (data?.get('status') != '102' && data?.get('status') != '300') {
            this.message.warning('教材信息填写不完整');
            return;
          }
          if (!data?.get('code')) {
            let t =
              this.tbookSer.formatTime('YYYYmmdd', new Date()) +
              Math.random().toString().slice(-4);
            data.set('code', t);
          }
          data.set('render', true);
          data.set('status', status);
          data.set('eduProcess', {
            __type: 'Pointer',
            className: 'EduProcess',
            objectId: processId,
          });
          if (parentMap[1]?.key) {
            data.set('department', {
              __type: 'Pointer',
              className: 'Department',
              objectId: parentMap[1]?.key,
            });
          }
          data.set('inviteUnit', inviteUnit);
          await data.save();
        } else {
          let count = 0,
            failCount = 0;
          let selectedList = this.textbookList.filter((item: any) =>
            this.setOfCheckedId.has(item?.id)
          );
          let deletePromiseList = selectedList.map((item: any) => {
            return new Promise((resolve) => {
              if (
                item?.get('status') == '102' ||
                item?.get('status') == '300'
              ) {
                count++;
                if (!item?.get('code')) {
                  let t =
                    this.tbookSer.formatTime('YYYYmmdd', new Date()) +
                    Math.random().toString().slice(-4);
                  item.set('code', t);
                }
                item.set('render', true);
                item.set('status', status);
                item.set('eduProcess', {
                  __type: 'Pointer',
                  className: 'EduProcess',
                  objectId: processId,
                });
                if (parentMap[1]?.key) {
                  item.set('department', {
                    __type: 'Pointer',
                    className: 'Department',
                    objectId: parentMap[1]?.key,
                  });
                }
                item.set('inviteUnit', inviteUnit);
                item.save().then(() => resolve(true));
              } else {
                failCount++;
                resolve(true);
              }
            });
          });
          try {
            await Promise.all(deletePromiseList);
            failCount > 0
              ? this.message.success(
                  '已提交' +
                    count +
                    '条教材，' +
                    failCount +
                    '条教材提交失败，请检查必填信息是否完整'
                )
              : this.message.success(
                  '已提交' + count + '条教材，' + failCount + '条教材提交失败'
                );
            this.onAllChecked(false);
          } catch (err) {}
        }
        this.getTextbook();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }

  //高校联系人提交教材至工作联系人
  async beforSubmit(data?: Parse.Object) {
    if (this.eduProcess?.get('status') != '200') {
      this.message.warning('当前流程状态非遴选中，不可此操作');
      return;
    }
    this.modal.confirm({
      nzTitle: '确认提交教材？',
      nzContent: `将提交至工作联系人，并从「待提交教材」移至「待评审教材」。`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: false,
      nzOnOk: async () => {
        if (data?.id) {
          data.set('status', '200');
          await data.save();
          this.message.success('提交成功');
        } else {
          let count = 0,
            failCount = 0;
          let selectedList = this.textbookList.filter((item: any) =>
            this.setOfCheckedId.has(item?.id)
          );
          let deletePromiseList = selectedList.map((item: any) => {
            return new Promise((resolve) => {
              if (item?.get('status') == '103') {
                count++;
                item.set('status', '200');
                item.save().then(() => resolve(true));
              } else {
                failCount++;
                resolve(true);
              }
            });
          });
          try {
            await Promise.all(deletePromiseList);
            failCount > 0
              ? this.message.success(
                  '已提交' +
                    count +
                    '条教材，' +
                    failCount +
                    '条教材提交失败，请检查教材是否已提交'
                )
              : this.message.success(
                  '已提交' + count + '条教材，' + failCount + '条教材提交失败'
                );
            this.onAllChecked(false);
          } catch (err) {}
        }
        this.getTextbook();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }

  //恢复
  restore(data?: Parse.Object) {
    this.modal.confirm({
      nzTitle: '恢复教材',
      nzContent: `确定恢复吗？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        if (data?.id) {
          data.set('discard', null);
          data.set('code', null);
          await data.save();
        } else {
          let selectedList = this.textbookList.filter((item: any) =>
            this.setOfCheckedId.has(item?.id)
          );
          let deletePromiseList = selectedList.map((item: any) => {
            return new Promise((resolve) => {
              item.set('discard', null);
              item.set('code', null);
              item.save().then(() => resolve(true));
            });
          });
          try {
            await Promise.all(deletePromiseList);
          } catch (err) {}
        }
        this.getTextbook();
        this.onAllChecked(false);
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  async getEduProcess(id: string): Promise<string | undefined> {
    if (!id) return;
    let query = new Parse.Query('EduProcess');
    query.equalTo('department', id);
    query.lessThanOrEqualTo('startDate', new Date());
    query.greaterThan('deadline', new Date());
    query.notEqualTo('isDeleted', true);
    query.containedIn('status', ['200', '300']);
    query.select('objectId');
    let res = await query.first();
    return res?.id;
  }
  //导出附件
  async exportProcess(data?: Parse.Object) {
    if (this.showLoading) return;
    this.showLoading = true;
    try {
      let bookList: Array<string> = [];
      if (data?.id) {
        bookList = [data?.id];
      } else {
        bookList = Array.from(this.setOfCheckedId);
      }
      // let processId = await this.getEduProcess(
      //   this.tbookSer.profile.user?.department?.objectId
      // );
      await this.tbookSer.tbookExportReport({ bookList: bookList });
      // Parse.Cloud.run('tbookExportReport', { bookList: bookList }).then(
      //   (data) => {
      //     console.log(data);
      //     let url = data.zipUrl;
      //     url = url.replaceAll("http://","https://");
      //     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;元素
      //   }
      // );
      this.showLoading = false;
    } catch (err) {
      this.message.error('导出超时，请稍后重试');
      console.log(err);
      this.showLoading = false;
    }
  }
  //在线预览
  async onlinePreview(id: string) {
    if(this.loading) return
    this.loading = true
    await this.tbookSer.preview({ bookid: id });
    this.loading = false
  }
  //打分
  onMarking(id:string, status:string){
    let pid = this.tbookSer.profile?.objectId
    if(status == '已评审'){
      this.message.warning('当前教材已提交评审打分')
      return
    }
    if(!pid){
      this.message.error('当前登录身份已过期，请重新登录')
      return
    }
    this.markScore.emit(id)
  }
  toUrl(url: string, param?: Object) {
    console.log(url);
    if (param) {
      this.route.navigate([url, param]);
      return;
    }
    this.route.navigate([url]);
  }
  //报送
  async submitted() {
    if (this.eduProcess?.get('status') == '400') {
      this.message.warning('已提交报送，无需重复提交');
      this.toUrl(
        `/nav-province-contact/manage/submitted/${this.eduProcess?.id}`
      );
      return;
    }
    // this.eduProcess?.set('status', '400');
    // this.eduProcess?.set('releaseDate', new Date());
    let query = new Parse.Query('EduTextbook');
    query.equalTo('eduProcess', this.eduProcess?.id);
    query.notEqualTo('isDeleted', true);
    query.notEqualTo('discard', true);
    query.equalTo('render', true);
    query.equalTo('recommend', true);
    query.equalTo('status', '200');
    let list = await query.find();
    query.containedIn('approval', [
      '首届全国教材建设奖优秀教材（高等教育类）教材',
      '否',
    ]);
    let count = await query.count();
    if (count > this.eduProcess?.get('num')) {
      this.message.warning('当前推荐教材数量已超额');
      return;
    }
    // await this.eduProcess?.save();
    // for (let index = 0; index < list.length; index++) {
    //   const item = list[index];
    //   item.set('status', '400');
    //   await item.save();
    // }
    // this.message.success('提交成功')
    this.toUrl(`/nav-province-contact/manage/submitted/${this.eduProcess?.id}`);
  }
  //导出表格
  async export() {
    if (this.showLoading) return;
    this.showLoading = true;
    try {
      console.log(this.eduProcess);
      let query = new Parse.Query('EduProcess');
      query.equalTo('objectId', this.eduProcess?.id);
      query.include('profileSubmitted', 'profileSubmitted.user');
      query.select('name', 'profileSubmitted');
      let r = await query.first();
      let data: any = await this.getTextbook('', { excel: true, id: false });
      let table = `<table border="1px" cellspacing="0" cellpadding="0">
          <thead>
          <tr>
                  <th colspan="10" style="font-size: 20px;font-family: '黑体';">“十四五”普通高等教育本科国家级规划教材推荐汇总表</th>
              </tr>
              <tr>
                  <th></th><th></th><th></th><th></th><th></th>
                  <th></th><th></th><th></th><th></th><th></th>
              </tr>
              <tr>
                  <th></th><th></th><th></th><th></th><th></th>
                  <th></th><th></th><th></th><th></th><th></th>
              </tr>
              <tr>
                  <th></th><th></th>
                  <th style="font-size: 12px;font-family: '黑体';text-align: left;">单位名称（公章）：</th>
                  <th colspan="3" style="font-size: 12px;font-family: '黑体';text-align: left;">${r?.get(
                    'name'
                  )}</th>
                  <th></th><th></th><th></th>
              </tr>
              <tr>
                  <th></th><th></th><th></th><th></th><th></th>
                  <th></th><th></th><th></th><th></th><th></th>
              </tr>
              <tr>
                  <th></th><th></th>
                  <th style="font-size: 12px;font-family: '黑体';text-align: left;">申报工作联系人：</th>
                  <th colspan="2" style="font-size: 12px;font-family: '黑体';text-align: left;">姓名 ${r
                    ?.get('profileSubmitted')
                    ?.get('user')
                    ?.get('name')}</th>
                  <th colspan="2" style="font-size: 12px;font-family: '黑体';text-align: left;">电话 ${r
                    ?.get('profileSubmitted')
                    ?.get('user')
                    ?.get('phone')}</th>
                  <th></th><th></th><th></th>
              </tr>
              <tr>
                  <th></th><th></th><th></th><th></th><th></th>
                  <th></th><th></th><th></th><th></th><th></th>
              </tr>
            <tr>
              <th>序号</th>
              <th>申报编号</th>
              <th>申报教材名称</th>
              <th>第一主编/作者</th>
              <th>第一主编（作者）单位</th>
              <th>申报类型</th>
              <th>是否为重点建设教材</th>
              <th>出版单位</th>
              <th>初版时间</th>
              <th>载体形式</th>
            </tr>
          </thead>
          <tbody>
          `;
      let _body = '';
      for (var row = 0; row < data.length; row++) {
        _body += '<tr>';
        _body += '<td>';
        _body += `${row + 1}`;
        _body += '</td>';

        _body += '<td>';
        _body += `&nbsp;${data[row].get('code') || ''}`;
        _body += '</td>';

        _body += '<td>';
        _body += ` &nbsp;${data[row].get('title') || '-'}`;
        _body += '</td>';

        _body += '<td>';
        _body += `${this.fromatFiled(data[row]?.get('childrens'), 'author')}`;
        _body += '</td>';

        _body += '<td>';
        _body += `${this.fromatFiled(data[row]?.get('childrens'), 'unit')}`;
        _body += '</td>';

        _body += '<td>';
        _body += `${
          data[row]?.get('type') == '单本'
            ? '单本'
            : '全册 - ' + data[row]?.get('typeNumber') || '-'
        }`;
        _body += '</td>';

        _body += '<td>';
        _body += `${data[row]?.get('approval') || '-'}`;
        _body += '</td>';

        _body += '<td>';
        _body += `${this.fromatFiled(
          data[row]?.get('childrens'),
          'editionUnit'
        )}`;
        _body += '</td>';

        _body += '<td>';
        _body += `&nbsp;${this.fromatFiled(
          data[row]?.get('childrens'),
          'editionFirst'
        )}`;
        _body += '</td>';

        _body += '<td>';
        _body += `${this.fromatFiled(
          data[row]?.get('childrens'),
          'carrierShape'
        )}`;
        _body += '</td>';

        _body += '</tr>';
      }
      table += _body;
      table += '</tbody>';
      table += '</table>';
      let title = '推荐汇总表';
      this.excel(table, `${title}.xls`);
      this.showLoading = false;
    } catch (err) {
      this.showLoading = false;
      this.message.error('导出超时');
    }
  }
  excel(data: any, filename: string) {
    let html =
      "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
    html +=
      '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
    html += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
    html += '; charset=UTF-8">';
    html += '<head>';
    html += '</head>';
    html += '<body>';
    html += data;
    html += '</body>';
    html += '</html>';
    let uri =
      'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
    let link = document.createElement('a');
    link.href = uri;
    link.download = `${filename}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
