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';
import { Platform } from '@ionic/angular';

@Component({
  selector: 'app-invite',
  templateUrl: './invite.component.html',
  styleUrls: ['./invite.component.scss'],
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    ...ionicStandaloneModules,
  ],
})
export class InviteComponent implements OnInit {
  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
    private platform: Platform
  ) {
    this.company = authServ.company;
  }
  inviteUser?:Parse.Object
  company: string = '';
  inputType: string = 'password';
  // 注册
  agreement: boolean = false;
  registerAgreement: any;
  registerInfo: any = {
    mobile: '',
    code: '',
    password: '',
    confirmPassword: '',
    invite: '',
    nickname: '',
  };
  isRegister: boolean = false; //是否注册成功
  app:Parse.Object
  nicknameArr = [
    "星辰",
    "月夜夜影",
    "花儿阳光",
    "彩虹颜色",
    "云朵天空",
    "凤凰火焰",
    "龙呼吸",
    "鹰翅膀",
    "狼族群",
    "虎爪子",
    "狮咆哮",
    "熊拥抱",
    "狐狸尾巴",
    "鹿鹿角",
    "马奔跑",
    "兔跳跃",
    "松鼠坚果",
    "猴子香蕉",
    "熊猫竹子",
    "长颈鹿脖子"
  ]
  ngOnInit() {
    if (this.platform.is('hybrid')) {
      this.authServ.logout();
      return;
    }
    this.registerInfo.nickname = this.nicknameArr[Math.floor(Math.random() * 20)] + new Date().getMilliseconds()
    let invite = localStorage.getItem('invite');
    // console.log('invite:', invite);
    if (invite) this.registerInfo.invite = invite;
    this.activatedRoute.paramMap.subscribe(async (param) => {
      let id = param?.get('id');
      if(!invite) invite = id
      if (invite) {
        let query = new Parse.Query('User');
        query.equalTo('invite', invite);
        query.select('mobile', 'username', 'nickname');
        this.inviteUser = await query.first();
        this.registerInfo.invite = invite;
      }else{
        window.location.href = '';
      }
      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);
        this.app = await App.first();
      }
      this.getAgreement();
    });
  }

  //   获取验证码
  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;
    }
    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;
      });
  }

  togglePassword() {
    if (this.inputType == 'password') {
      this.inputType = 'text';
    } else {
      this.inputType = 'password';
    }
  }
  // 注册账号
  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.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: res.msg,
            color: 'success',
            duration: 1000,
          });
          toast.present();
          const alert = await this.alertController.create({
            cssClass: 'my-custom-class',
            header: '注册成功',
            message: `恭喜你，注册成功`,
            backdropDismiss: false,
            buttons: [
              {
                text: '确认',
                handler: () => {
                  this.registerInfo = {
                    mobile: '',
                    code: '',
                    password: '',
                    confirmPassword: '',
                    invite: '',
                  };
                  this.isRegister = true
                },
              },
            ],
          });
          await alert.present();
        } else {
          const toast = await this.toastController.create({
            // 接口返回的错误，提示用户
            message: res.mess,
            color: 'danger',
            duration: 1000,
          });
          toast.present();
        }
      });
  }

  downImg(url:string) {
    let dlLink: any = document.createElement('a');
    if ('download' in dlLink) {
      dlLink.style.visibility = 'hidden';
      dlLink.href = url;
      dlLink.download = 'hey聊';
      document.body.appendChild(dlLink);
      dlLink.click();
      document.body.removeChild(dlLink);
    } else {
      location.href = url;
    }
  }
}
