import { Component, OnInit, ViewChild } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import * as Parse from 'parse';
import { ActivatedRoute } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { AgreementComponent } from './agreement/agreement.component';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import {
  ionicStandaloneModules,
  AlertController,
  ToastController,
  ModalController,
  LoadingController,
} from '../ionic-standalone.modules';

@Component({
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    ...ionicStandaloneModules,
  ],
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  user: { username?: string; password?: string } = {
    username: '',
    password: '',
  };
  currentUser: any;
  constructor(
    private toastController: ToastController,
    public authServ: AuthService,
    // private router: Router,
    private activatedRoute: ActivatedRoute,
    private http: HttpClient,
    private modalCtrl: ModalController,
    private alertController: AlertController,
    private loadingCtrl: LoadingController
  ) {
    this.company = authServ.company;
  }

  company: string = '';
  appName: any;
  logo: any;
  // 显示登陆、注册内容
  status: string = 'login';
  type: string = 'password';
  loginInfo: any = {
    mobile: '',
    password: '',
    code: '',
  };
  // 忘记密码
  reset: any = {
    mobile: '',
    code: '',
    password: '',
    confirmPassword: '',
  };
  inputType: string = 'password';
  // 注册
  agreement: boolean = false;
  registerAgreement: any;
  registerInfo: any = {
    mobile: '',
    code: '',
    password: '',
    confirmPassword: '',
    invite: '',
    nickname: '',
  };
  nicknameArr = [
    "星辰",
    "月夜夜影",
    "花儿阳光",
    "彩虹颜色",
    "云朵天空",
    "凤凰火焰",
    "龙呼吸",
    "鹰翅膀",
    "狼族群",
    "虎爪子",
    "狮咆哮",
    "熊拥抱",
    "狐狸尾巴",
    "鹿鹿角",
    "马奔跑",
    "兔跳跃",
    "松鼠坚果",
    "猴子香蕉",
    "熊猫竹子",
    "长颈鹿脖子"
  ]
  ngOnInit() {
    let invite = localStorage.getItem('invite');
    console.log('invite:',invite);
    if(invite) this.registerInfo.invite = invite;
    this.authServ.logout();
    this.activatedRoute.paramMap.subscribe((param) => {
      localStorage.setItem('APP_DEFAULT_COMPANY', 'Qje9D4bqol');
      localStorage.setItem('company', this.company);
      if (this.company) {
        let App = new Parse.Query('App');
        App.equalTo('company', this.company);
        App.equalTo('isEnabled',true)
        App.select('name','logo')
        App.first().then((res) => {
          // console.log(res);
          if (res && res.id) {
            this.appName = res.get('name');
            this.logo = res.get('logo');
          }
        });
      }
      this.getAgreement();
      let Company = new Parse.Query('Company');
      Company.get(this.company).then((res) => {
        console.log(res, res.get('tabsOption'));
        let value = res.get('tabsOption');
        localStorage.setItem('tabsOption', JSON.stringify(value));
      });
    });

    this.registerInfo.nickname = this.nicknameArr[Math.floor(Math.random() * 20)] + new Date().getMilliseconds()
  }

  //   获取验证码
  wait: number = 60;
  waitStatus: boolean = false;
  time() {
    if (this.wait == 0) {
      this.waitStatus = false;
      this.wait = 60;
    } else {
      this.waitStatus = true;
      this.wait--;
      setTimeout(() => {
        this.time();
      }, 1000);
    }
  }

  //   获取验证码
  vcode: string = '';
  mobile: string = '';
  loginToken: string = '';
  timer: boolean = false;
  async sendVerifyCode(mobile: string) {
    if (this.timer) {
      return;
    }
    this.timer = true;
    let a = /^1[3456789]\d{9}$/;
    if (mobile == undefined || !String(mobile).match(a)) {
      const toast = await this.toastController.create({
        message: '请填写正确手机号',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      this.timer = false;
      return;
    }
    if (this.status == 'login') {
      let query = new Parse.Query('_User');
      query.equalTo('company', this.company);
      query.equalTo('mobile', mobile);
      query.select('objectId');
      let r = await query.first();
      if (!r?.id) {
        const toast = await this.toastController.create({
          message: '用户手机号不存在，请先注册',
          color: 'warning',
          duration: 1000,
        });
        toast.present();
        this.timer = false;
        return;
      }
    }
    this.http
      .post('https://server.fmode.cn/api/apig/message', {
        company: this.company,
        mobile: mobile,
      })
      .subscribe((res: any) => {
        this.waitStatus = true;
        this.time();
        this.vcode = res.data.code;
        this.timer = false;
      });
  }

  changeType() {
    let type = this.type;
    if (type == 'password') {
      this.type = 'code';
    } else {
      this.type = 'password';
    }
  }

  async login() {
    const loading = await this.loadingCtrl.create({
      message: '正在登录，请稍等',
    });
    loading.present();
    console.log(this.loginInfo);
    if (this.loginInfo.mobile == undefined || this.loginInfo.mobile == '') {
      loading.dismiss();
      const toast = await this.toastController.create({
        message: '请输入手机号',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    let a = /^1[3456789]\d{9}$/;
    if (!String(this.loginInfo.mobile).match(a)) {
      loading.dismiss();
      const toast = await this.toastController.create({
        message: '请填写正确手机号',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (this.type == 'password') {
      if (this.loginInfo.password == '' || this.loginInfo.password.trim == '') {
        loading.dismiss();
        const toast = await this.toastController.create({
          message: '请填写密码',
          color: 'warning',
          duration: 1000,
        });
        toast.present();
        return;
      }
      this.authServ
        .authMobile(
          this.loginInfo.mobile,
          this.loginInfo.password,
          this.loginInfo.mobile
        )
        .then((data) => {
          console.log(data);
          loading.dismiss();
        })
        .catch(async (err) => {
          loading.dismiss();
          const toast = await this.toastController.create({
            message: err,
            color: 'danger',
            duration: 1000,
          });
          toast.present();
        });
    } else if (this.type == 'code') {
      if (!this.loginInfo.code) {
        loading.dismiss();
        const toast = await this.toastController.create({
          message: '请填写有效验证码',
          color: 'warning',
          duration: 1000,
        });
        toast.present();
        return;
      }
      this.authServ
        .authMobile(
          this.loginInfo.mobile,
          undefined,
          this.loginInfo.mobile,
          this.loginInfo.code
        )
        .then((data) => {
          console.log(data);
          loading.dismiss();
        })
        .catch(async (err) => {
          loading.dismiss();
          const toast = await this.toastController.create({
            message: err,
            color: 'danger',
            duration: 1000,
          });
          toast.present();
        });
    }
  }
  // 忘记密码部分逻辑
  back() {
    this.status = 'login';
  }
  togglePassword() {
    if (this.inputType == 'password') {
      this.inputType = 'text';
    } else {
      this.inputType = 'password';
    }
  }
  async resetPassword() {
    let a = /^1[3456789]\d{9}$/;
    if (this.reset.mobile == undefined || !String(this.reset.mobile).match(a)) {
      const toast = await this.toastController.create({
        message: '请输入手机号',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (this.reset.code == undefined || this.reset.code == '') {
      const toast = await this.toastController.create({
        message: '请输入验证码',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (this.reset.password == undefined || this.reset.password.trim() == '') {
      const toast = await this.toastController.create({
        message: '请输入密码',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (
      this.reset.password.length < 6 ||
      this.reset.password.length.length > 20
    ) {
      const toast = await this.toastController.create({
        message: '密码长度不得小于6位或大于20位',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (
      this.reset.confirmPassword == undefined ||
      this.reset.confirmPassword.trim() == ''
    ) {
      const toast = await this.toastController.create({
        message: '请确认密码',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (this.reset.password.trim() != this.reset.confirmPassword.trim()) {
      const toast = await this.toastController.create({
        message: '两次输入密码不一致',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    let headers: HttpHeaders = new HttpHeaders({});
    headers.append('Content-Type', 'application/json');
    headers.set('Access-Control-Allow-Origin', '*');
    this.http
      .post(
        `https://server.fmode.cn/api/auth/reset_password`,
        {
          company: this.company,
          code: this.reset.code,
          mobile: this.reset.mobile,
          password: this.reset.password,
        },
        { headers }
      )
      .pipe(
        catchError(async (e) => {
          // 显示报错
          const toast = await this.toastController.create({
            message: e.error?.mess || '服务器错误',
            color: 'danger',
            duration: 1000,
          });
          toast.present();
          console.log(e);
          return;
        })
      )
      .subscribe(async (res: any) => {
        console.log(res);
        if (res && res.code == 200) {
          const toast = await this.toastController.create({
            message: '密码重置成功',
            color: 'success',
            duration: 1000,
          });
          toast.present();
        } else {
          const toast = await this.toastController.create({
            // 接口返回的错误，提示用户
            message: res.mess,
            color: 'danger',
            duration: 1000,
          });
          toast.present();
        }
      });
  }
  // 注册账号
  agree() {
    this.agreement = !this.agreement;
  }
  getAgreement() {
    let Agreement = new Parse.Query('ContractAgreement');
    Agreement.equalTo('company', this.company);
    Agreement.equalTo('type', 'register');
    Agreement.first().then((res) => {
      console.log(res);
      this.registerAgreement = res;
    });
  }
  async showAgreement() {
    const modal = await this.modalCtrl.create({
      component: AgreementComponent,
      cssClass: 'my-custom-class',
      componentProps: {
        agreement: this.registerAgreement,
      },
    });
    return await modal.present();
  }
  async registerUser() {
    let a = /^1[3456789]\d{9}$/;
    if (
      this.registerInfo.mobile == undefined ||
      !String(this.registerInfo.mobile).match(a)
    ) {
      const toast = await this.toastController.create({
        message: '请填写正确的手机号',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (this.registerInfo.code == undefined || this.registerInfo.code == '') {
      const toast = await this.toastController.create({
        message: '请输入验证码',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (
      this.registerInfo.password == undefined ||
      this.registerInfo.password.trim() == ''
    ) {
      const toast = await this.toastController.create({
        message: '请输入密码',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (
      this.registerInfo.password.length < 6 ||
      this.registerInfo.password.length.length > 20
    ) {
      const toast = await this.toastController.create({
        message: '密码长度不得小于6位或大于20位',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (
      this.registerInfo.confirmPassword == undefined ||
      this.registerInfo.confirmPassword.trim() == ''
    ) {
      const toast = await this.toastController.create({
        message: '请确认密码',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (
      this.registerInfo.password.trim() !=
      this.registerInfo.confirmPassword.trim()
    ) {
      const toast = await this.toastController.create({
        message: '两次输入密码不一致',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    this.registerInfo.nickname = this.registerInfo.nickname?.trim()
    if(!this.registerInfo.nickname){
      const toast = await this.toastController.create({
        message: '请输入昵称',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (!this.agreement) {
      const alert = await this.alertController.create({
        cssClass: 'my-custom-class',
        header: '提示',
        message: `请先勾选${this.registerAgreement?.get('title')}`,
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            cssClass: 'secondary',
            handler: (blah) => {
              console.log('Confirm Cancel: blah');
            },
          },
          {
            text: '同意',
            handler: () => {
              this.agreement = true;
            },
          },
        ],
      });
      await alert.present();
      return;
    }
    let data = this.registerInfo.invite
      ? {
          company: this.company,
          code: this.registerInfo.code,
          mobile: this.registerInfo.mobile,
          password: this.registerInfo.password,
          invite: this.registerInfo.invite,
          nickname:this.registerInfo.nickname,
        }
      : {
          company: this.company,
          code: this.registerInfo.code,
          mobile: this.registerInfo.mobile,
          password: this.registerInfo.password,
          nickname:this.registerInfo.nickname,
        };
    this.http
      .post(`https://server.fmode.cn/api/auth/register`, data)
      .pipe(
        catchError(async (e) => {
          // 显示报错
          const toast = await this.toastController.create({
            message: e.message,
            color: 'danger',
            duration: 1000,
          });
          toast.present();
          console.log(e);
          return;
        })
      )
      .subscribe(async (res: any) => {
        console.log(res);
        if (res && res.code == 200) {
          const toast = await this.toastController.create({
            message: res.msg,
            color: 'success',
            duration: 1000,
          });
          toast.present();
          this.registerInfo = {
            mobile: '',
            code: '',
            password: '',
            confirmPassword: '',
            invite: '',
          };
          this.status = 'login';
        } else {
          const toast = await this.toastController.create({
            // 接口返回的错误，提示用户
            message: res.mess,
            color: 'danger',
            duration: 1000,
          });
          toast.present();
        }
      });
  }
}
