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';

@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-submit",
    "流程管理员登录":"/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(username: any, password: any, company: string) {
    return new Promise(async (resolve, reject) => {
      let a = /^1[3456789]\d{9}$/;
      //如果是手机号登录，获取对应的mobile
      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(){
    let query = new Parse.Query('Profile')
    query.equalTo('user',Parse.User.current()?.id)
    query.notEqualTo('isDeleted',true)
    let r = await query.first()
    if(r?.id){
      if(r.get('identity')){
        this.router.navigate([this.roterPath[r.get('identity')]])
        let profile = r.toJSON()
        localStorage.setItem(
          'profile',
          JSON.stringify(profile)
        );
        this.textbook.profile = profile;
      }
      else if(!r.get('verify')){
        this.message.warning('请完善个人信息')
        this.router.navigate(['/user/account_info'])
      }
    }else{
      this.router.navigate(['/user/account_info'])
    }
  }

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

}
