import { Injectable } from "@angular/core";
import Parse from "parse";
import { Router } from "@angular/router";
@Injectable({
  providedIn: "root",
})
export class AuthServr {
  isLoggedIn = false;
  countdown: number = 60; //登录时验证码倒计时
  regcountdown: number = 60; //注册验证码倒计时
  resetcountdown: number = 60; //重置密码验证码倒计时

  redirectUrl: string = '';
  constructor(public router: Router) {}
  login(username:string, password:string, 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) => {
          // await this.developerSer.authDevCompany(); //更新开发者信息
          console.log(data);
          resolve(data);
        })
        .catch((err:any) => {
          console.log(err.message);
          if (err.message.indexOf("Invalid username/password.") != -1) {
            reject({ message: "用户名或密码不正确" });
          } else {
            reject({ message: "用户名或密码不正确" });
          }
        });
    });
  }

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