import { Component, OnInit } from '@angular/core';
import {
  IonicModule,
  LoadingController,
  ToastController,
} from '@ionic/angular';

import * as Parse from 'parse';
import { AgreementComponent } from '../../login/agreement/agreement.component';
import { AlertController, ModalController } from '@ionic/angular';
import { Router } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { AiChatService } from '../../../services/aichart.service';
@Component({
  selector: 'app-my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss'],
  standalone: true,
  imports: [IonicModule],
})
export class MyComponent implements OnInit {
  profile?: Parse.Object; //身份信息
  user: Parse.Object = Parse.User.current()!;
  constructor(
    public loadingCtrl: LoadingController,
    private modalController: ModalController,
    private alertController: AlertController,
    public authServ: AuthService,
    public toastController: ToastController,
    private router: Router,
    private aiServ: AiChatService
  ) {}
  tools: Array<{ icon: string; title: string; path: string }> = [
    {
      icon: '/img/钱包.png',
      title: '钱包',
      path: 'account/wattle',
    },
    {
      icon: '/img/相册.png',
      title: '相册',
      path: 'user/album',
    },
    {
      icon: '/img/邀请.png',
      title: '邀请',
      path: 'user/share',
    },
    {
      icon: '/img/设置.png',
      title: '设置',
      path: 'user/setting',
    },
  ];
  registerAgreement: any; //用户协议
  liveAgreement: any; //直播协议
  company: string | null = localStorage?.getItem('company');
  userObj: any = {
    fans: 0,
    follow: 0,
    friendly_degree: 0,
  };
  ngOnInit() {
    this.refresh();
  }
  async refresh() {
    this.getProfile();
    this.getAgreement();
    const data = await this.aiServ.getFansAndFollow(this.user.id);
    console.log(data);
    const { fans, follow } = data.data[0]
    this.userObj = { fans, follow, friendly_degree: 0 }
  }
  // 获取用户信息
  async getProfile() {
    let user = Parse.User.current();
    let query = new Parse.Query('Profile');
    query.equalTo('user', user?.id);
    query.notEqualTo('isDeleted', true);
    query.select('isCheck', 'isCross');
    this.profile = await query.first();
  }
  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;
    });
    let Agreement2 = new Parse.Query('ContractAgreement');
    Agreement2.equalTo('company', this.company);
    Agreement2.equalTo('type', 'live');
    Agreement2.first().then((res) => {
      console.log(res);
      this.liveAgreement = res;
    });
  }
  async onChange(e: any) {
    const loading = await this.loadingCtrl.create({
      message: '正在修改',
    });
    loading.present();
    let checked = e.detail.checked;
    console.log(checked);
    if (!this.profile?.id) {
      let obj = Parse.Object.extend('Profile');
      this.profile = new obj();
      this.profile?.set('mobile', Parse.User.current()?.get('mobile'));
      this.profile?.set('user', Parse.User.current()?.toPointer());
      this.profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
    }
    this.profile?.set('isCheck', checked);
    await this.profile?.save();
    loading.dismiss();
    const toast = await this.toastController.create({
      message: `已${checked ? '开启' : '关闭'}`,
      color: 'success',
      duration: 1000,
    });
    toast.present();
  }
  toUrl(url: string, params?: Object) {
    console.log(url);
    if (params) {
      this.router.navigate([url, Object]);
    } else {
      this.router.navigate([url]);
    }
  }
  async showAgreement(type: string) {
    if (type == 'liveAgreement' || type == 'registerAgreement') {
      const modal = await this.modalController.create({
        component: AgreementComponent,
        cssClass: 'my-custom-class',
        componentProps: {
          agreement: this[type],
        },
      });
      return await modal.present();
    }
  }
  /* 进入直播间 */
  async goRoom() {
    if (!this.profile?.get('isCross')) {
      const alert = await this.alertController.create({
        header: '提示',
        message: '你还未认证主播身份，请认证后再进入直播间',
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            cssClass: 'secondary',
            handler: (blah) => {},
          },
          {
            text: '去认证',
            handler: () => {
              console.log('Confirm Cancel: blah');
              this.toUrl('/user/auchor');
            },
          },
        ],
      });
      await alert.present();
    } else {
      this.toUrl('/live/room-manage');
    }
  }
  /* 退出登录 */
  async onLogout() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '',
      message: '你确定退出登录吗？',
      buttons: [
        {
          text: '确定',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            console.log('Confirm Cancel: blah');
            this.authServ.logout();
          },
        },
        {
          text: '取消',
          handler: () => {},
        },
      ],
    });
    await alert.present();
  }
}
