import { Injectable } from '@angular/core';
import * as Parse from 'parse';
import { Router } from '@angular/router';
import { MessageService } from './message.service';
import { ConnectTaskService } from './connectTask.service';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { NavController } from '@ionic/angular';
import { Location } from '@angular/common';
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  company: string = 'Qje9D4bqol';
  redirectUrl: string = 'tabs';
  constructor(
    private connectTask: ConnectTaskService,
    private router: Router,
    private msgSer: MessageService,
    private http: HttpClient,
    private navCtrl: NavController,
    private location: Location,
  ) {}
  authMobile(
    mobile: string,
    password?: string,
    nickname?: string,
    code?: string,
    register?: boolean
  ) {
    return new Promise((resolve, reject) => {
      if (password) {
        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);
                  await this.getProfile();
                  await this.connectTask.init();
                  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);
          });
      } else {
        this.http
          .get(
            `https://server.fmode.cn/api/auth/mobile?company=${this.company}&mobile=${mobile}&code=${code}`
          )
          .pipe(catchError(async (e) => {
            console.log(e);
            reject(e?.error.mess || '登录失败，服务器错误');
          }))
          .subscribe((res: any) => {
            console.log(res);
            if (res.code == 200) {
              Parse.User.become(res.data.token)
                .then(async (data) => {
                  console.log(data);
                  await this.getProfile();
                  await this.connectTask.init();
                  this.redirectUrl = this.redirectUrl
                    ? this.redirectUrl
                    : 'tabs';
                  this.router.navigate([this.redirectUrl]);
                  resolve(data);
                })
                .catch((err) => {
                  // console.error(err);
                  reject('登录失败，token已过期');
                });
            } else {
              reject(res?.mess);
            }
          });
      }
    });
  }
  async getProfile() {
    if (localStorage.getItem('profile')) return;
    let queryProfile = new Parse.Query('Profile');
    queryProfile.equalTo('user', Parse.User.current()?.id);
    queryProfile.notEqualTo('isDeleted', true);
    queryProfile.equalTo('isCross', true);
    let res = await queryProfile.first();
    if (res?.id) {
      localStorage.setItem('profile', JSON.stringify(res?.toJSON()));
    }
  }
  clearReWechat(cid: string) {
    // 清楚过期登录状态，重新登陆
    localStorage.clear(); // 清楚过期登录状态，重新登陆
    window.location.search = `c=${cid}`; // TODOLIST 此处需要通过循环清楚CODE，STATE等微信后缀，重新拼接用户的QueryParams
  }
  logout(): void {
    localStorage.clear(); // 清楚过期登录状态，重新登陆
    Parse.User.logOut().then((user) => {
      this.msgSer?.logOutRTM();
      this.msgSer?.reset();
      this.connectTask?.reset();
      // this.router.navigate(['login']);
      this.navCtrl.navigateRoot('/login', { animated: false });
      this.location.replaceState('/login');
    });
  }
}
