import { Injectable } from '@angular/core';
import Parse from 'parse';
import { Router } from '@angular/router';
import { textbookServer } from './textbook';
import { catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
@Injectable({
  providedIn: 'root',
})
export class AuthServr {
  isLoggedIn = false;
  countdown: number = 60; //登录时验证码倒计时
  regcountdown: number = 60; //注册验证码倒计时
  resetcountdown: number = 60; //重置密码验证码倒计时
  redirectUrl: string = '';
  roterPath: any = {
    "国家级管理员": '/nav-admin',
    "工作联系人": '/nav-province-contact',
    "高校联系人": '/nav-province-school-contact',
    "评审专家": '/nav-review',
    "教师": '/nav-author/manage/space',
  };
  constructor(
    public router: Router,
    private textbook: textbookServer,
    private http: HttpClient,
    private message: NzMessageService
  ) {}
  //登录
  login(id: string) {
    return new Promise((resolve, reject) => {
      let host =
        (Parse as any).serverURL?.split('parse')?.[0] ||
        'https://server.fmode.cn/';
      this.http
        .post(host + 'api/textbook/login', {
          id: id,
        })
        .pipe(
          catchError(async (e) => {
            reject(e);
          })
        )
        .subscribe((res: any) => {
          console.log(res);
          if (res?.code == 200) {
            let token = res.data.token;
            Parse.User.become(token)
              .then(async (data: any) => {
                console.log(data);
                await this.profileVerify();
                resolve(data);
              })
              .catch((err: any) => {
                console.log(err.message);
                if (err.message.indexOf('Invalid username/password.') != -1) {
                  reject({ message: '用户名或密码不正确' });
                } else {
                  reject({ message: '用户名或密码不正确' });
                }
              });
          }
        });
    });
    // return new Promise(async (resolve, reject) => {
    //   let a = /^1[3456789]\d{9}$/;
    //   if (String(username).match(a)) {
    //     let query = new Parse.Query('_User');
    //     query.equalTo('company', company);
    //     query.equalTo('mobile', username);
    //     let res = await query.first();
    //     if (res?.id) {
    //       username = res.get('username');
    //     } else {
    //       reject({ message: '用户不存在' });
    //       return;
    //     }
    //   }
    //   Parse.User.logIn(username, password)
    //     .then(async (data: any) => {
    //       console.log(data);
    //       await this.profileVerify()
    //       resolve(data);
    //     })
    //     .catch((err: any) => {
    //       console.log(err.message);
    //       if (err.message.indexOf('Invalid username/password.') != -1) {
    //         reject({ message: '用户名或密码不正确' });
    //       } else {
    //         reject({ message: '用户名或密码不正确' });
    //       }
    //     });
    // });
  }
  //手机号注册/登录
  register(mobile: any, code: any, company: string) {
    return new Promise((resolve, reject) => {
      let host =
        (Parse as any).serverURL?.split('parse')?.[0] ||
        'https://server.fmode.cn/';
      this.http
        .post(host + 'api/textbook/register', {
          company: company,
          mobile: mobile,
          code: code,
        })
        .pipe(
          catchError(async (e) => {
            reject(e);
          })
        )
        .subscribe((res: any) => {
          console.log(res);
          if (res?.code == 200) {
            let token = res.data.token;
            Parse.User.become(token)
              .then(async (data: any) => {
                console.log(data);
                await this.profileVerify();
                resolve(data);
              })
              .catch((err: any) => {
                console.log(err.message);
                if (err.message.indexOf('Invalid username/password.') != -1) {
                  reject({ message: '用户名或密码不正确' });
                } else {
                  reject({ message: '用户名或密码不正确' });
                }
              });
          }
        });
    });
  }
  //验证用户类型
  async profileVerify(modal?: NzModalService) {
    if(!Parse.User.current()?.id) return
    let query = new Parse.Query('Profile');
    query.equalTo('user', Parse.User.current()?.id);
    query.notEqualTo('isDeleted', true);
    query.include('user', 'user.department');
    let r = await query.first();
    if (r?.id) {
      let user = Parse.User.current();
      if (user?.get('isDeleted')) {
        !modal && this.message.error('该账号已被封禁');
        modal?.error({
          nzTitle: '该账号已被封禁',
          nzContent: '',
        });
        return;
      }
      switch (user?.get('accountState')) {
        case '已认证':
          if (r.get('identity')) {
            let profile = r.toJSON();
            localStorage.setItem('profile', JSON.stringify(profile));
            this.textbook.profile = profile;
            this.router.navigate([this.roterPath[r.get('identity')]]);
            // this.message.success('登录成功');
            return;
          }
          this.message.warning('已认证暂无身份');
          break;
        case '待认证':
          !modal && this.message.warning('账号待认证，请等待审核完成');
          modal?.warning({
            nzTitle: '账号待认证，请等待审核完成',
            nzContent: '',
          });
          break;
        case '已禁用':
          !modal && this.message.error('账号已禁用');
          modal?.error({
            nzTitle: '账号已禁用',
            nzContent: '',
          });
          break;
        default:
          !modal && this.message.error('异常账号');
          modal?.error({
            nzTitle: '异常账号',
            nzContent: '',
          });
          // this.router.navigate(['/user/account_info']);
          break;
      }
      return;
    }
    this.router.navigate(['/user/account_info']);
  }

  logout(): void {
    Parse.User.logOut().then((user) => {
      // this.developerSer.companyId = ''
      window.localStorage.clear();
      this.router.navigate(['/user/login']);
    });
  }
}
