import { Component, OnInit } from '@angular/core';
import { LoadingController, ToastController } from '@ionic/angular';
import * as Parse from 'parse';
import { AgreementComponent } from '../../login/agreement/agreement.component';
import { AlertController, ModalController } from '@ionic/angular';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { AiChatService } from '../../../services/aichart.service';
import { AccountService } from '../../../services/account.service';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';
import { DatePipe, CommonModule } from '@angular/common';
import { AvatarComponent } from '../../../app/components/avatar/avatar.component';
import { HttpService } from '../../../services/http.service';
import { DeviceService } from '../../../services/device.service';
@Component({
  selector: 'app-my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, CommonModule,AvatarComponent],
  providers: [DatePipe],
})
export class MyComponent implements OnInit {
  profile?: Parse.Object; //身份信息
  user: Parse.Object = Parse.User.current()!;
  constructor(
    private loadingCtrl: LoadingController,
    private modalController: ModalController,
    private alertController: AlertController,
    private authServ: AuthService,
    private toastController: ToastController,
    private activateRoute: ActivatedRoute,
    private router: Router,
    public aiServ: AiChatService,
    private accServ: AccountService,
    private http: HttpService,
    public deviceSer:DeviceService
  ) {}
  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/browse',
    },
    {
      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,
    vip: null,
  };
  orderList: Array<any> = [];
  loading: boolean = true;
  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      this.refresh();
    });
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    this.user = Parse.User.current()!;
    await this.getProfile();
    this.getAgreement();
    const data = await this.aiServ.getFansAndFollow(this.user.id);
    // console.log(data);
    this.orderList = await this.aiServ.getOrderAnchor(null,10,'day');
    console.log(this.orderList);
    const { fans, follow } = data.data[0];
    this.userObj = { fans, follow, friendly_degree: 0 };
    this.userObj.vip = this.accServ.userVip;
    if (!this.userObj.vip) {
      this.userObj.vip = await this.accServ.getVip();
    }
    console.log(this.userObj);
    await this.updateLevel()
    loading.dismiss();
    this.loading = false;
  }
  // 获取用户信息
  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','birthdate','identyType','degreeNumber');
    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') ||
      this.profile?.get('identyType') !== 'anchor'
    ) {
      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/anchor');
            },
          },
        ],
      });
      await alert.present();
    } else {
      this.toUrl('/live/room-manage');
    }
  }
  /* 退出登录 */
  async onLogout() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '',
      message: '你确定退出登录吗？',
      backdropDismiss:false,
      buttons: [
        {
          text: '确定',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            console.log('Confirm Cancel: blah');
            this.authServ.logout();
          },
        },
        {
          text: '取消',
          handler: () => {},
        },
      ],
    });
    await alert.present();
  }

  toService(){
    location.href = 'tel:4000-000-000';
    console.log('拨号');
  }

  async updateLevel(){
    let url = 'https://server.fmode.cn/api/ailiao/update/level'
    let data = await this.http.httpRequst(url,{pid: this.profile?.id},'POST')
    console.log(data);
  }

  async toUrlService(url: string){
    if(!this.accServ.userVip?.rights?.['vip-service']){
      const toast = await this.toastController.create({
        message: '高级会员专享服务',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return
    }
    this.router.navigate([url]);
  }

  async changeTop(e:any, type?:string){
    e.cancelBubble = true;
    this.orderList = await this.aiServ.getOrderAnchor(null,10,type);
  }
  async toArticle(){
    let query = new Parse.Query('Article');
    query.equalTo('company', this.aiServ.company);
    query.equalTo('isEnabled', true);
    query.notEqualTo('isDeleted', true);
    query.equalTo('type', 'promotion');
    query.select('objectId');
    let article = await query.first();
    console.log(article?.id);
    this.router.navigate(['webview',{id:article?.id}]);
  }
}
