import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, RouterOutlet, Router } from '@angular/router';
import { CompTableListComponent } from '../../../../app/comp-table/comp-table-list/comp-table-list.component';
import _Role from '../../../../schemas/_Role';
// import { TranslateService } from '@ngx-translate/core';
import * as Parse from 'parse';
import { CommonModule } from '@angular/common';
import { Department } from '../../../../schemas/Department';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import { CommonCompModule } from '../../../../services/common.modules';
import { NzModalModule } from 'ng-zorro-antd/modal';
import {
  NzFormatEmitEvent,
  NzTreeModule,
  NzTreeNode,
} from 'ng-zorro-antd/tree';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { textbookServer } from '../../../../services/textbook';
interface nodes {
  title: string;
  key: string;
  isLeaf?: boolean;
  isParent?: boolean;
  children?: Array<any>;
}
interface depart {
  name: string;
  id?: string;
  code?: string;
  desc?: string;
  parent?: object | any;
  branch: string;
}
@Component({
  selector: 'app-process-list',
  templateUrl: './process-list.component.html',
  styleUrls: ['./process-list.component.scss'],
  imports: [
    CommonModule,
    CommonCompModule,
    RouterOutlet,
    CompTableListComponent,
    NzSpaceModule,
    NzPageHeaderModule,
    NzBreadCrumbModule,
    NzTreeModule,
    NzCheckboxModule,
    NzEmptyModule,
    NzModalModule,
    NzRadioModule,
  ],
  standalone: true,
})
export class ProcessListComponent implements OnInit {
  @ViewChild(CompTableListComponent) list: CompTableListComponent | undefined;

  // _Role = _Role
  Department = Department;
  user: Parse.User | undefined;
  className: string | undefined;
  queryParams: any | undefined;
  fieldsArray: Array<any> | undefined;
  searchValue: string = ''; //搜索内容
  searchValuePro: string = ''; //搜索流程内容
  nodes: Array<nodes | any> = [];
  currentDepart: nodes | any = null;

  eduProcessList: Array<any> = [];
  statusMap: any = {};
  eduProcessLength: number = 0;
  pageSize: number = 10;
  pageIndex: number = 1;

  checkedShowFilter: boolean = false;

  checkedAll: boolean = false; //全选
  indeterminate = false;
  loading = false;

  isVisible: boolean = false;
  activatedNode: NzTreeNode | any; //当前选择节点
  editType: string = 'add'; //弹窗类型
  activeDepart?: Parse.Object; //当前编辑部门
  editObject: depart = {
    name: '',
    code: '',
    desc: '',
    parent: {},
    branch: '',
  };
  parentMap: Array<any> = [];
  setOfCheckedId = new Set<string>();
  formatStatus = (e: any) => {
    if (e.get('status') == '100') {
      return {
        title: '已暂停',
        color: 'lime',
        strat: true,
        stop: true,
        end: false,
        del: false,
      };
    }
    if (
      e?.get('deadline') &&
      new Date() > new Date(e?.get('deadline')) &&
      e?.get('status') == '400'
    ) {
      return {
        title: '已结束',
        color: 'gold',
        strat: false,
        stop: false,
        end: false,
        del: true,
      };
    }
    if (e?.get('status') == '400') {
      return {
        title: '已完成',
        color: 'green',
        strat: false,
        stop: false,
        end: true,
        del: false,
      };
    }
    if (!e?.get('startDate') || new Date() < new Date(e.get('startDate'))) {
      return {
        title: '未开始',
        color: 'grey',
        strat: true,
        stop: false,
        end: false,
        del: true,
      };
    }
    if (
      e.get('status') == '200' &&
      e?.get('startDate') &&
      new Date() >= new Date(e?.get('startDate'))
    ) {
      return {
        title: '遴选中',
        color: 'blue',
        strat: false,
        stop: true,
        end: true,
        del: false,
      };
    }
    if (e?.get('deadline') && new Date() > new Date(e?.get('deadline'))) {
      return {
        title: '已逾期',
        color: 'red',
        strat: true,
        stop: false,
        end: false,
        del: true,
      };
    }
    if (e.get('status') == '300') {
      return {
        title: '已公示',
        color: 'red',
        strat: false,
        stop: true,
        end: true,
        del: false,
      };
    }
    return;
  };
  constructor(
    public tbookSer: textbookServer,
    private route: Router,
    private activeRoute: ActivatedRoute,
    private message: NzMessageService,
    private modal: NzModalService
  ) {
    this.user = Parse.User.current();
    this.className = this.Department.className;
    this.fieldsArray = this.Department.fieldsArray;
    this.queryParams = {
      where: {
        isDeleted: { $ne: true },
      },
    };
  }

  ngOnInit(): void {
    this.activeRoute.paramMap.subscribe(async (params) => {
      // this.nodes = await this.getDepart();
      this.getEduProcess()
    });
  }
  async getDepart(
    parent?: string,
    searchValue?: string
  ): Promise<Array<nodes>> {
    let nodes: any = [];
    let query = new Parse.Query('Department');
    searchValue && query.contains('name', searchValue);
    query.notEqualTo('isDeleted', true);
    query.select('code', 'name', 'branch', 'parent', 'type');
    query.descending('createdAt');
    query.limit(100);
    query.equalTo('objectId', this.tbookSer.profile.user.department?.objectId)
    let res = await query.find();
    res.forEach((item) => {
      nodes.push({
        title: item.get('name'),
        key: item.id,
        children: [],
        isLeaf: true,
      });
    });
    return nodes;
  }
  async onSearch(e: string) {
    this.nodes = await this.getDepart('', e);
  }
  onSearchPro(e: string){
    this.getEduProcess()
  }
  changeDepart(e: any) {
    this.currentDepart = e;
    this.getEduProcess();
  }

  async getEduProcess() {
    this.eduProcessList = [];
    this.loading = true;
    let query1= Parse.Query.fromJSON('EduProcess', {
      where: {
        $or: [
          {
            name: { "$regex": `.*${this.searchValuePro}.*`},
          },
        ]
      }
    });
    let query2= Parse.Query.fromJSON('EduProcess', {
      where: {
        $or: [
          {
            code: { "$regex": `.*${this.searchValuePro}.*`},
          },
        ]
      }
    });
    let query = Parse.Query.or(query1, query2)
    query.include('profileSubmitted', 'profileSubmitted.user');
    query.notEqualTo('isDeleted', true);
    query.equalTo('department',this.tbookSer.profile.user.department?.objectId)
    query.descending('createdAt');
    let r = await query.find();
    // let list: any[] = [];
    r.forEach((item) => {
      // let _item = item.toJSON();
      // _item['checked'] = false;
      // _item['state'] = this.formatStatus(_item);
      this.statusMap[item.id] = this.formatStatus(item);
    });
    this.eduProcessList = r;
    this.loading = false;
  }
  //分页切换
  pageIndexChange(e: any) {
    console.log(e);
    this.pageIndex = e;
    this.getEduProcess();
  }
  onAllChecked(checked: boolean): void {
    console.log(checked);
    this.eduProcessList.forEach((item) => {
      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.eduProcessList.every((item) =>
      this.setOfCheckedId.has(item.id)
    );
  }

  statusSelected(type: string) {
    let map: any = {
      strat: '开始',
      stop: '暂停',
      end: '结束',
    };
    this.modal.confirm({
      nzTitle: '批量删除',
      nzContent:
        type == 'del'
          ? `删除后数据不可恢复，请谨慎操作`
          : `确认批量${map[type]}吗`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: map[type] ? true : false,
      nzOnOk: async () => {
        let selectedList = this.eduProcessList.filter((item: any) =>
          this.setOfCheckedId.has(item?.id)
        );
        let deletePromiseList = selectedList.map((item: any) => {
          return new Promise((resolve) => {
            resolve(this.onStatusChange(item, type));
          });
        });
        try {
          await Promise.all(deletePromiseList);
          this.getEduProcess();
        } catch (err) {}
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }

    //暂停流程
    async onStatusChange(
      data: Parse.Object,
      type: string,
      end?: boolean
    ): Promise<void> {
      console.log(data, type);
      switch (type) {
        case 'strat':
          if (data?.get('status') == '100') {
            data?.set('status', null);
          }
          if (data?.get('startDate') > new Date()) {
            data?.set('startDate', new Date());
          }
          if (data?.get('deadline') < new Date()) {
            data?.set(
              'deadline',
              new Date(new Date().getTime() + 60 * 1000 * 60 * 24 * 7)
            );
            console.warn('结束时间延长一周之后');
          }
          break;
        case 'stop':
          data?.set('status', '100');
          break;
        case 'end':
          data?.set('status', '400');
          data?.set('deadline', new Date());
          break;
        case 'del':
          data?.set('isDeleted', true);
          break;
      }
      await data.save();
      if (end) {
        this.getEduProcess();
      }
    }

  toUrl(url: string, params?: object) {
    if (params) {
      this.route.navigate([url, params]);
    } else {
      this.route.navigate([url]);
    }
  }
}
