import { Injectable } from '@angular/core';
import * as Parse from 'parse';
import { Router } from '@angular/router';
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  company:string = 'Qje9D4bqol'
  redirectUrl: string = 'tabs';
  constructor(private router: Router) {}
  authMobile(
    mobile: string,
    password?: string,
    nickname?: string,
    code?: string,
    register?: boolean
  ) {
    return new Promise((resolve, reject) => {
      Parse.Cloud.run('auth_mobile', {
        c: this.company,
        mobile: mobile,
        password: password,
        code: code,
        register: register,
        nickname: nickname,
      })
        .then((authData) => {
          // console.log(authData);
          if (authData) {
            // let sessionToken = authData.get('sessionToken');
            Parse.User.become(authData)
              .then(async (data) => {
                // console.log(data);
                this.redirectUrl = this.redirectUrl ? this.redirectUrl : 'tabs';
                this.router.navigate([this.redirectUrl])
                resolve(data);
              })
              .catch((err) => {
                console.error(err);
                reject('登录失败，token已过期');
              });
          }else{
            reject(authData.message);
          }
        })
        .catch((err) => {
          console.error(err.message);
          reject(err.message);
        });
    });
  }
  clearReWechat(cid: string) {
    // 清楚过期登录状态，重新登陆
    localStorage.clear(); // 清楚过期登录状态，重新登陆
    window.location.search = `c=${cid}`; // TODOLIST 此处需要通过循环清楚CODE，STATE等微信后缀，重新拼接用户的QueryParams
  }
  logout(): void {
    localStorage.clear(); // 清楚过期登录状态，重新登陆
    Parse.User.logOut().then((user) => {
      this.router.navigate(['login']);
    });
  }
}
