import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
import { CompTableListComponent } from '../../../app/comp-table/comp-table-list/comp-table-list.component';
// import _User from '../../../schemas/_User';
import * as Parse from 'parse';
import { CommonModule } from '@angular/common';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../services/common.modules';
// import { Profile } from '../../../schemas/Profile-list';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzModalService } from 'ng-zorro-antd/modal';
import { textbookServer } from '../../../services/textbook';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzRadioModule } from 'ng-zorro-antd/radio';

@Component({
  selector: 'app-page-user',
  templateUrl: './page-user.component.html',
  styleUrls: ['./page-user.component.scss'],
  imports: [
    CommonModule,
    RouterOutlet,
    NzSpaceModule,
    NzPageHeaderModule,
    CompTableListComponent,
    NzBreadCrumbModule,
    CommonCompModule,
    NzRadioModule,
    NzEmptyModule,
    NzSelectModule,
  ],
  standalone: true,
})
export class PageUserComponent implements OnInit {
  @ViewChild(CompTableListComponent) list: CompTableListComponent | undefined;
  listOfColumns: any = {
    identity: {
      listOfFilter: [
        { value: '工作联系人', text: '工作联系人' },
        { value: '高校联系人', text: '高校联系人' },
        { value: '评审专家', text: '评审专家' },
        { value: '教师', text: '教师' },
      ],
    },
    companyType: {
      listOfFilter: [
        { value: '教育部直属高校', text: '教育部直属高校' },
        { value: '中央有关部门（单位）教育司（局）', text: '中央有关部门（单位）教育司（局）' },
        { value: '省级教育行政部门', text: '省级教育行政部门' },
        { value: '出版单位', text: '出版单位' },
      ],
    },
  }
  // _User = _User;
  // ProfileList = Profile;
  // className: string | undefined;
  // queryParams: any | undefined;
  // fieldsArray: Array<any> | undefined;
  user: Parse.User | undefined;
  profiles: Array<Parse.Object> = [];
  profileLength: number = 0; //总数据
  pageSize: number = 10;
  pageIndex: number = 1;
  checkedAll: boolean = false; //全选
  indeterminate = false;
  loading = false;
  searchValue: string = ''; //搜索内容
  setOfCheckedId = new Set<string>();
  userType: Array<string> = ['工作联系人', '评审专家', '高校联系人', '教师'];
  parentMap: Array<any> = [];
  parentList: Array<any> = [];
  radio: string = '';
  loadingParent: boolean = false;
  /* 添加账号 */
  accountIsVisible: boolean = false;
  account: any = {
    name: '',
    username: '',
    phone: '',
    email: '',
    password: '',
    identity: '',
    department: {},
    companyType: '',
  };
  parents: Array<any> = []; //所有一级列表
  //筛选条件
  filters: any = {
    identity: { type: 'string', value: [] },
    companyType: { type: 'string', value: [] },
  };
  constructor(
    public tbookSer: textbookServer,
    private modal: NzModalService,
    private route: Router,
    private message: NzMessageService,
    private activeRoute: ActivatedRoute
  ) {
    this.user = Parse.User.current();
    if (this.tbookSer.profile.identity != '国家级管理员') {
      this.userType = ['评审专家', '高校联系人', '教师'];
    }
  }

  ngOnInit(): void {
    this.activeRoute.paramMap.subscribe(async (params) => {
      this.getProfile();
      this.parents = await this.getDepart();
    });
  }
  async getProfile() {
    this.profiles = [];
    this.loading = true;
    let queryParams: any = {
      where: {
        $or: [
          {
            user: {
              $inQuery: {
                where: {
                  $or: [
                    {
                      name: { $regex: `.*${this.searchValue}.*` },
                    },
                    {
                      username: { $regex: `.*${this.searchValue}.*` },
                    },
                    {
                      phone: { $regex: `.*${this.searchValue}.*` },
                    },
                    {
                      email: { $regex: `.*${this.searchValue}.*` },
                    },
                  ],
                },
                className: '_User',
              },
            },
          },
        ],
      },
    };
    if (this.tbookSer.profile.identity != '国家级管理员') {
      let childrens = await this.tbookSer.getChild(this.tbookSer.profile.user.department?.objectId)
      this.tbookSer.profile.user.department;
      queryParams['where']['$or'][0]['user']['$inQuery']['where'][
        'department'
      ] = {
        $in: [childrens],
      };
    }
    let query = Parse.Query.fromJSON('Profile', queryParams);
    for (const key in this.filters) {
      const element = this.filters[key];
      if (element.value?.length > 0) {
        query.containedIn(key, element.value);
      }
    }
    query.include('user');
    query.notEqualTo('identity', '国家级管理员');
    query.descending('createdAt');
    if (this.tbookSer.profile.identity == '工作联系人') {
      query.containedIn('identity', ['教师', '评审专家', '高校联系人']);
    } else if (this.tbookSer.profile.identity == '高校联系人') {
      query.containedIn('identity', ['教师', '评审专家']);
    }
    this.profileLength = await query.count();
    query.limit(this.pageSize);
    query.skip((this.pageIndex - 1) * this.pageSize);
    let r = await query.find();
    this.profiles = r;
    this.loading = false;
  }
  //分页切换
  pageIndexChange(e: any) {
    console.log(e);
    this.pageIndex = e;
    this.getProfile();
  }
  //筛选条件
  onChangeFilter(data: any, type:string){
    console.log(data);
    this.filters[type].value = data
    this.profiles = []
    this.pageIndex = 1
    this.getProfile()
  }
  createUser() {
    this.route.navigate(['/nav-admin/manage/user/create']);
  }
  onItemChecked(id: string, e: boolean) {
    if (e) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.checkedAll = this.profiles.every((item) =>
      this.setOfCheckedId.has(item.id)
    );
  }
  onAllChecked(checked: boolean): void {
    this.profiles.forEach((item) => {
      if (checked) {
        this.setOfCheckedId.add(item.id);
      } else {
        this.setOfCheckedId.delete(item.id);
      }
    });
    this.checkedAll = checked;
  }
  resetChange() {
    this.setOfCheckedId = new Set<string>();
    this.checkedAll = false;
  }
  async updateUser(data: Parse.Object, type: string) {
    console.log(type);
    if (
      this.tbookSer.profile.identity != '国家级管理员' &&
      (data?.get('identity') == '工作联系人' ||
        data?.get('identity') == '高校联系人')
    ) {
      this.message.warning('暂无权限');
      return;
    }
    this.modal.confirm({
      nzTitle: '操作提示',
      nzContent: `确定${type}吗？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: type == '删除' ? true : false,
      nzOnOk: async () => {
        let query = new Parse.Query('_User');
        query.equalTo('objectId', data?.get('user')?.id);
        let r = await query.first();
        if (r?.id) {
          switch (type) {
            case '通过认证':
              r?.set('accountState', '已认证');
              Parse.Cloud.run('aliSmsSend',{
                "mobileList": [data?.get('user')?.get('phone')],"templateCode":"SMS_468870790","params":{},"signName":"普通高等教育教材网"
              })
              await r?.save();
              break;
            case '禁用':
              r?.set('accountState', '已禁用');
              await r?.save();
              break;
            case '删除':
              // r?.set('isDeleted', true);
              this.setOfCheckedId.delete(data.id);
              await data.destroy();
              await r.destroy();
              break;
          }
        }
        this.getProfile();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }

  deleteSelected() {
    this.modal.confirm({
      nzTitle: '批量删除',
      nzContent: `删除后数据不可恢复，请谨慎操作`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let selectedList = this.profiles.filter((item: any) =>
          this.setOfCheckedId.has(item?.id)
        );
        let deletePromiseList = selectedList.map((item: any) => {
          return new Promise(async (resolve) => {
            await item.get('user')?.destroy()
            await item.destroy()
            resolve(true)
          });
        });
        try {
          await Promise.all(deletePromiseList);
          this.setOfCheckedId = new Set<string>();
          this.checkedAll = false
          this.getProfile();
        } catch (err) {}
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  goDateil(id: string) {
    this.route.navigate(['/nav-admin/manage/user/edit', { id: id }]);
  }

  /* 添加用户 */
  async addMember() {
    this.radio = '';
    this.account = {
      name: '',
      username: '',
      phone: '',
      email: '',
      password: '',
      identity: '',
      department: {},
      companyType: '',
    };
    if (this.tbookSer.profile.identity != '国家级管理员') {
      // let query = new Parse.Query('Department');
      // query.select('code', 'name', 'branch', 'parent', 'type', 'hasChildren');
      // let res = await query.get(
      //   this.tbookSer.profile.user.department?.objectId
      // );
      // this.parentList = [
      //   {
      //     title: res.get('name'),
      //     key: res.id,
      //     branch: res.get('branch'),
      //     parent: res.get('parent')?.id, //上级
      //     isLeaf: !res.get('hasChildren'), //是否是最下级
      //     type: res.get('type'),
      //   },
      // ];
      this.parentList = await this.getDepart(this.tbookSer.profile.user.department?.objectId);
      this.parentMap = await this.formatNode(this.tbookSer.profile.user.department?.objectId);
    } else {
      this.parentList = await this.getDepart();
    }
    this.accountIsVisible = true;
  }
  async getDepart(parent?: string, searchValue?: string): Promise<Array<any>> {
    let nodes: any = [];
    let query = new Parse.Query('Department');
    query.equalTo(
      'parent',
      searchValue
        ? this.parentMap[this.parentMap.length - 1]?.key
        : parent
        ? parent
        : this.tbookSer.profile.identity != '国家级管理员'
        ? this.tbookSer.profile.user.department?.objectId
        : null
    );
    searchValue && query.contains('name', searchValue);
    query.notEqualTo('isDeleted', true);
    query.select('code', 'name', 'branch', 'parent', 'type', 'hasChildren');
    query.descending('createdAt');
    query.limit(2000);
    let res = await query.find();
    res.forEach((item) => {
      nodes.push({
        title: item.get('name'),
        key: item.id,
        branch: item.get('branch'),
        parent: item.get('parent')?.id, //上级
        isLeaf: !item.get('hasChildren'), //是否是最下级
        type: item.get('type'),
      });
    });
    return nodes;
  }

  //搜索
  async onSearchNodes(e: string) {
    this.parentList = await this.getDepart('', e);
    return;
  }
  async onPre(data?: any, index?: number) {
    if (!data) {
      this.parentList = await this.getDepart();
      this.parentMap = [];
      return;
    }
    if (index == this.parentMap.length - 1){
      if(this.parentList.length == 0 ) this.parentList = await this.getDepart(data?.key);
      return;
    } 
    this.parentMap.splice((index || 0) + 1);
    this.parentList = await this.getDepart(data?.key);
  }
  //选择所属类别下级列表
  async onCheckedDepart(e: any, checked?: boolean) {
    this.radio = e.key;
    this.account.identity = '';
    this.parentMap = await this.formatNode(e.key);
    if (this.tbookSer.profile.identity != '国家级管理员') {
      let index = this.parentMap.findIndex(
        (item) => this.tbookSer.profile.user.department?.objectId == item.key
      );
      if (index != -1) {
        this.parentMap.forEach((item, i) => {
          if (i >= index) {
            this.parentMap[i].verify = true;
          }
        });
      }
    }
    if (checked && e.parent) {
      this.account.department = { title: e.title, id: e.key };
      this.account.companyType = e.branch || e.title;
      this.userType = this.parents.some((item) => e.parent == item.key)
        ? !e.type ? ['工作联系人'] : ['评审专家', '工作联系人', '教师']
        : e.type == '单位'
        ? ['评审专家', '高校联系人', '教师']
        : ['评审专家', '教师'];
      return;
    }
    if (e.isLeaf) {
      return;
    }
    this.parentList = await this.getDepart(e?.key);
  }
  //格式化链
  async formatNode(id: string): Promise<Array<any>> {
    let query = new Parse.Query('Department');
    query.select('name', 'parent');
    let r = await query.get(id);
    let arr = [
      {
        title: r.get('name'),
        key: r.id,
      },
    ];
    if (r?.get('parent')) {
      arr.unshift(...(await this.formatNode(r?.get('parent').id)));
    }
    return arr;
  }
  handleCancel(): void {
    this.parentMap = [];
    this.accountIsVisible = false;
    this.account = null;
  }
  randomPassword() {
    this.account.password = this.tbookSer.randomPassword();
    console.log(this.account.password);
  }
  /* 添加账号 */
  isLoadingOne:boolean = false
  async accountComplete() {
    if(this.isLoadingOne) return
    this.isLoadingOne = true
    this.account.username = this.account?.username.trim();
    this.account.email = this.account?.email.trim();
    this.account.phone = this.account?.phone.trim();
    this.account.name = this.account?.name.trim();
    this.account.password = this.account?.password.trim();
    if(!await this.authVrifly()){
      this.isLoadingOne = false
      return
    }
    try {
      let obj = Parse.Object.extend('_User');
      let user = new obj();
      user?.set(
        'username',
        this.account?.username || this.account?.email || this.account?.phone
      );
      user?.set('name', this.account?.name);
      user?.set('phone', this.account?.phone);
      this.account?.email && user?.set('email', this.account?.email);
      user?.set('password', this.account.password);
      user?.set('accountState', '已认证');
      user?.set('department', {
        __type: 'Pointer',
        className: 'Department',
        objectId: this.account.department?.id,
      });
      let u = await user.save();
      let p = Parse.Object.extend('Profile');
      let profile = new p();
      profile?.set('user', u?.toPointer());
      profile?.set('companyType', this.account.companyType);
      profile?.set('email', this.account.email);
      profile?.set('identity', this.account.identity);
      let res = await profile?.save();
      this.isLoadingOne = false
      this.accountIsVisible = false;
      this.account = null;
      Parse.Cloud.run('aliSmsSend',{
        "mobileList": [this.account?.phone],"templateCode":"SMS_469060724","params":{},"signName":"普通高等教育教材网"
      })
      this.modal.success({
        nzTitle: '添加成功',
        nzContent: '',
        nzOnOk: () => {
          this.pageIndex = 1;
          this.getProfile();
        },
      });
    } catch (err: any) {
      console.warn('添加用户错误', err);
      this.isLoadingOne = false
      this.message.error(
        err?.Error || '错误：请检查用户或邮箱及手机号是否已存在'
      );
      return;
    }
  }
  async authVrifly():Promise< boolean | undefined>{
    this.account.password = this.account?.password.trim();
    this.account.email = this.account?.email.trim();
    this.account.phone = this.account?.phone.trim();
    this.account.name = this.account?.name.trim();
    if (
      !this.account?.name ||
      !this.account.department?.id ||
      !this.account.password||
      !this.account.phone || !this.account?.email
    ) {
      this.message.warning('请填写必填项');
      return;
    }
    if (!this.account.identity) {
      this.message.error('请选择人员类型');
      return;
    }
    let a = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (this.account.phone && !String(this.account.phone).match(a)) {
      this.message.error('请填写正确手机号');
      return;
    }
    let m = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if(!String(this.account.email).match(m)){
      this.message.error("邮箱格式有误");
      return;
    }
    // if (!this.account?.email&& !this.account?.phone) {
    //   this.message.error('邮箱或手机号必须填写一项');
    //   return;
    // }
    if(!(this.account.password.length >= 6 && this.account.password.length <= 18)){
      this.message.error('密码格式错误，请填写6-18位非空字符串（数字、大小写字母或英文符号）');
      return;
    }
    if(!await this.tbookSer.userFind(this.account.phone)){
      this.message.error('手机号已存在');
      return
    }
    return true
  }
}
