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';
import * as major from '../../services/majors.map';
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,
  ],
  standalone: true,
})
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 = '/nav-admin/manage/textbook/details';
  @Input('discard') discard: Boolean = false; //是否删除
  @Input('eduProcess') eduProcess?: Parse.Object; //流程id，verify存在时需要

  //相关权限配置
  @Input('filterObj') filterObj: any = {
    showMore: false, //显示更多字段
    isCheck: true,
    noStared: false, //非推荐
    status: [],
    btns: {
      edit: false, //编辑
      isDelete: false, //删除权限
      review: false, //预览
      reject: false, //退回教材
      star: false, //加入推荐
      remove: false, //移除推荐
      submit: false, //提交
      export: false,
      verify: false, //提交推荐权限
      restore: false, //恢复教材
    },
  };
  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();
      },
    },
  };
  //筛选条件
  filters: filter | any = {
    lang: { type: 'string', value: [] },
    majorPoniter: { type: 'string', value: [] },
    editionUnit: { type: 'string', value: [] },
    approval: { type: 'string', value: [] },
    carrierShape: { type: 'string', value: [] },
    department: { type: 'pointer', value: [] },
  };
  loading: boolean = false;
  checkedAll: boolean = false; //全选
  setOfCheckedId = new Set<string>();
  searchValue: string = '';
  manage: boolean = false;
  calc:number = 120

  showLoading:boolean = false //全局

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

  ngOnInit() {
    this.activeRoute.paramMap.subscribe(async (params) => {
      // this.eduProcessId = params.get('id');
      this.calc += Object.values(this.filterObj?.btns).length * 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
        );
      }
    });
  }
  async getTextbook(val?: string, exported?: boolean): Promise<any[] | void> {
    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);
    }
    // this.uid && query.equalTo('user',this.tbookSer.profile.user?.objectId);
    for (const key in this.filters) {
      const element = this.filters[key];
      if (element.value?.length > 0) {
        query.containedIn(key, element.value);
      }
    }
    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);
    query.descending('createdAt');
    query.notEqualTo('isDeleted', true);
    if (!this.uid) {
      query.equalTo('render', true);
      // query.containedIn('status', ['200', '400']);
    }
    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) {
      let r = await query.find();
      this.loading = false;
      return r;
    }
    query.include('department');
    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.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);
  }
  onSearch(e: string) {
    console.log(e);
    this.getTextbook(e);
  }
  //分页切换
  pageIndexChange(e: any) {
    console.log(e);
    this.pageIndex = e;
    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;
  }
  //单选
  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)
    );
  }
  //退回
  reject(data?: Parse.Object) {
    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)
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
    if (this.filterObj?.btns?.verify) {
      history.go();
    }
  }
  //提交教材
  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 //推荐单位
    // if(parentMap[0]?.title == '省级教育行政部门' || parentMap[0]?.title == '有关部门（单位）教育司（局）'){
    //   inviteUnit = parentMap[2]?.title
    // }
    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;
          }
          let t =
            this.tbookSer.formatTime('YYYYmmdd', new Date()) +
            Math.random().toString().slice(-4);
          data.set('render', true);
          data.set('status', '200');
          data.set('code', t);
          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++;
                let t =
                  this.tbookSer.formatTime('YYYYmmdd', new Date()) +
                  Math.random().toString().slice(-4);
                item.set('render', true);
                item.set('status', '200');
                item.set('code', t);
                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'),
    });
  }
  //恢复
  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 })
      this.showLoading = false
    }
    catch(err){
      this.message.error('导出超时，请稍后重试')
      console.log(err);
      this.showLoading = false
    }
    // 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;元素
    //   }
    // );
  }
  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() {
    let data: any = await this.getTextbook('', true);
    let table = `<table border="1px" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th>申报编号</th>
            <th>教材名称</th>
            <th>册数</th>
            <th>第一主编/作者</th>
            <th>所属单位</th>
            <th>所属本科专业</th>
            <th>主要语种类型</th>
            <th>ISBN</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('title') || '-'}`;
      _body += '</td>';

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

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

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

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

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

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

      _body += '<td>';
      _body += `${data[row]?.get('editionUnit') || '-'}`;
      _body += '</td>';
      _body += '</tr>';
    }
    table += _body;
    table += '</tbody>';
    table += '</table>';
    let title = '申报流程列表';
    this.excel(table, `${title}.xls`);
  }
  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);
  }
}
