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 {
  NzContextMenuService,
  NzDropdownMenuComponent,
} from 'ng-zorro-antd/dropdown';
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';
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> = [];
  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> = [];
  parentList: Array<any> = [];
  setOfCheckedId = new Set<string>();
  formatStatus = (e:any)=>{
    if(e.status == '100'){
      return {
        title:'已暂停',
        color:'lime',
        strat:true,
        stop:true,
        end:false,
        del:false,
      }
    }
    if(e?.deadline.iso && new Date() > new Date(e.deadline.iso) && e.status == '200'){
      return {
        title:'已结束',
        color:'gold',
        strat:false,
        stop:false,
        end:false,
        del:true,
      }
    }
    if(e.status == '200'){
      return {
        title:'已完成',
        color:'green',
        strat:false,
        stop:false,
        end:true,
        del:false,
      }
    }
    if(!e?.startDate.iso || (new Date() < new Date(e.startDate.iso))){
      return {
        title:'未开始',
        color:'grey',
        strat:true,
        stop:false,
        end:false,
        del:true,
      }
    }
    if(!e.statuse && e.startDate.iso && new Date() >= new Date(e.startDate.iso) ){
      return {
        title:'遴选中',
        color:'blue',
        strat:false,
        stop:true,
        end:true,
        del:false,
      }
    }
    if(e?.deadline.iso && (new Date() > new Date(e.deadline.iso))){
      return {
        title:'已逾期',
        color:'red',
        strat:true,
        stop:false,
        end:false,
        del:true,
      }
    }
    return
  }
  constructor(
    private route: Router,
    private activeRoute: ActivatedRoute,
    private nzContextMenuService: NzContextMenuService,
    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();
    });
  }
  async getDepart(
    parent?: string,
    searchValue?: string
  ): Promise<Array<nodes>> {
    let nodes: any = [];
    let query = new Parse.Query('Department');
    query.equalTo('parent', parent ? parent : undefined);
    searchValue && query.contains('name', searchValue);
    query.notEqualTo('isDeleted', true);
    query.select('code', 'name', 'branch', 'parent', 'type');
    query.descending('createdAt');
    query.limit(2000);
    let res = await query.find();
    res.forEach((item) => {
      nodes.push({
        title: item.get('name'),
        key: item.id,
        children: [],
        // isParent: item.get('type') =='单位' ? true : false, //是否是最下级
        isLeaf: true,
      });
    });
    return nodes;
  }
  async onSearch(e: string) {
    this.nodes = await this.getDepart('', e);
  }
  onSearchPro(e: string){
    this.getProfile()
  }
  changeDepart(e: any) {
    this.currentDepart = e;
    this.getProfile();
  }

  async getProfile() {
    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('branch',this.currentDepart.key)
    let r = await query.find();
    let list: any[] = [];
    r.forEach((item) => {
      let _item = item.toJSON();
      _item['checked'] = false;
      _item['state'] = this.formatStatus(_item);
      list.push(_item);
    });
    this.eduProcessList = list;
    this.loading = false;
  }

  onAllChecked(checked: boolean): void {
    console.log(checked);
    this.eduProcessList = this.eduProcessList.map((item) => {
      item.checked = checked;
      if (checked) {
        this.setOfCheckedId.add(item.user.objectId);
      } else {
        this.setOfCheckedId.delete(item.user.objectId);
      }
      return item;
    });
    this.checkedAll = checked;
  }
  onItemChecked(id: string, e: boolean) {
    let checkedAll = true;
    this.eduProcessList = this.eduProcessList.map((item) => {
      if (id == item.objectId) item.checked = e;
      if (!item.checked) checkedAll = false;
      return item;
    });
    if (e) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.checkedAll = checkedAll;
  }
  //新建打开弹窗
  async showModalDepart(type: string) {
    this.parentList = this.nodes;
    if (type == 'edit') {
      let query = new Parse.Query('Department');
      let r = await query.get(this.activatedNode?.key);
      this.activeDepart = r;
      this.parentMap = this.formatNode(this.activatedNode);
      if (this.activatedNode?.parentNode?.origin.key) {
        this.parentList = await this.getDepart(
          this.activatedNode.parentNode.origin.key
        );
      }
    }
    this.editType = type;
    this.isVisible = true;
  }
  //格式化链
  formatNode(node: NzTreeNode): Array<any> {
    let arr = [];
    if (node.parentNode?.origin.title) {
      arr.push({
        title: node.parentNode?.origin.title,
        key: node.parentNode?.origin.key,
      });
      arr.unshift(...this.formatNode(node.parentNode));
    }
    return arr;
  }
  async onPre(data?: any, index?: number) {
    if (!data) {
      this.parentList = await this.getDepart();
      this.parentMap = [];
      return;
    }
    if (index == this.parentMap.length - 1) return;
    this.parentMap.splice(index || 0 + 1);
    this.parentList = await this.getDepart(data?.key);
  }
  //选择所属类别下级列表
  async onCheckedDepart(e: any, checked?: boolean) {
    console.log(e);
    if (checked) {
      this.editObject = {
        name: e.title,
        code: '',
        desc: '',
        parent: e,
        branch: '',
      };
      return;
    }
    this.parentMap.push({
      title: e.title,
      key: e.key,
    });
    this.parentList = await this.getDepart(e?.key);
  }
  handleOk(): void {
    this.message.warning('权限灰度中');
    this.isVisible = false;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
    this.activatedNode = undefined;
    this.parentMap = [];
  }

  /* 组织 */
  showModalOrganize() {
    this.message.warning('权限灰度中');
  }
  deleteSelected() {
    this.modal.confirm({
      nzTitle: '批量删除',
      nzContent: `删除后数据不可恢复，请谨慎操作`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let selectedList = this.eduProcessList.filter((item: any) =>
          this.setOfCheckedId.has(item?.id)
        );
        let deletePromiseList = selectedList.map((item: any) => {
          return new Promise((resolve) => {
            item.set('isDeleted', true);
            item.save();
          });
        });
        try {
          await Promise.all(deletePromiseList);
        } catch (err) {}
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  toUrl(url: string, params?: object) {
    if (params) {
      this.route.navigate([url, params]);
    } else {
      this.route.navigate([url]);
    }
  }
}
