import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NavComponent } from '../../../app/components/nav/nav.component';
import { ActivatedRoute, Router } from '@angular/router';
import {
  AlertController,
  IonicModule,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import * as Parse from 'parse';
import { ImagePreviewComponent } from '../../../app/components/image-preview/image-preview.component';
import { AiChatService } from '../../../services/aichart.service';
import { HttpService } from '../../../services/http.service';
import { UploadComponent } from '../../../app/components/upload/upload.component';
import { GiftModalComponent } from '../../../app/components/gift-modal/gift-modal.component';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
  standalone: true,
  imports: [
    IonicModule,
    FormsModule,
    // DatePipe,
    NavComponent,
    CommonModule,
    ImagePreviewComponent,
    UploadComponent,
    GiftModalComponent,
  ],
  providers: [DatePipe],
})
export class ProfileComponent implements OnInit {
  // @ViewChild('upload') upload!: UploadComponent;
  uid: string = '';
  currentUser?: Parse.Object = Parse.User.current(); //当前登录用户
  profiel?: Parse.Object; // 用户信息
  user?: Parse.Object; // 查看用户
  @ViewChild('preview') preview!: ImagePreviewComponent;
  profile?: Parse.Object;
  active: number = 0;
  currenImg: string = '';
  numsObject: { fans: number; follow: number; gift: number } = {
    fans: 0, //粉丝量
    follow: 0, //关注量
    gift: 0, //送出礼物
  };
  isFollow: boolean = false;
  giftList: any[] = []; //礼物
  isOpen: boolean = false; //打开弹窗
  room?: Parse.Object;
  @ViewChild('gift') gift!: GiftModalComponent;

  constructor(
    private activateRoute: ActivatedRoute,
    private router: Router,
    public toastController: ToastController,
    public loadingCtrl: LoadingController,
    private aiChatServ: AiChatService,
    private http: HttpService,
    private alertController: AlertController
  ) {}

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let id: any = params.get('id');
      this.uid = id;
      await this.refresh();
      this.getRoom();
    });
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    await this.getProfile();
    await this.getFollwState();
    let res = await this.aiChatServ.getFansAndFollow(this.uid);
    this.numsObject.fans = res.data[0].fans;
    this.numsObject.follow = res.data[0].follow;
    let res1 = await this.aiChatServ.getGiftLogCount(this.uid);
    this.numsObject.gift = res1.data[0].gift ?? 0;
    this.giftList = await this.aiChatServ.getGiftList(this.uid, 16);
    loading.dismiss();
  }
  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('company', this.aiChatServ.company);
    query.equalTo('profile', this.profile?.id);
    // query.equalTo('state', true);
    query.notEqualTo('isDeleted', true);
    // query.select('objectId')
    let r = await query.first();
    this.room = r;
  }
  async getProfile() {
    let queryProfile = new Parse.Query('Profile');
    queryProfile.equalTo('user', this.uid);
    queryProfile.notEqualTo('isDeleted', true);
    queryProfile.include('user');
    let p = await queryProfile.first();
    this.profile = p;
    if (this.profile?.id) {
      this.user = this.profile?.get('user');
    } else {
      let queryUser = new Parse.Query('_User');
      queryUser.equalTo('objectId', this.uid);
      this.user = await queryUser.first();
    }
    console.log(this.user, this.profile);
  }
  /* 关注状态 */
  async getFollwState() {
    let query = new Parse.Query('ProfileRadar');
    query.equalTo('fromUser', this.currentUser?.id);
    query.equalTo('toUser', this.uid);
    query.notEqualTo('isDeleted', true);
    query.equalTo('name', '关注');
    let r = await query.first();
    this.isFollow = r?.id ? true : false;
  }
  /* 关注 */
  async onCollection() {
    let query = new Parse.Query('ProfileRadar');
    query.equalTo('toUser', this.uid);
    query.equalTo('fromUser', this.currentUser?.id);
    // query.notEqualTo('isDeleted', true);
    query.equalTo('name', '关注');
    let profileRadar = await query.first();
    if (!profileRadar?.id) {
      let radar = Parse.Object.extend('ProfileRadar');
      profileRadar = new radar();
      profileRadar?.set('toUser', {
        __type: 'Pointer',
        className: '_User',
        objectId: this.uid,
      });
      profileRadar?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.currentUser?.get('company')?.id,
      });
      profileRadar?.set('fromUser', this.currentUser?.toPointer());
      profileRadar?.set('name', '关注');
    }
    profileRadar?.set('isDeleted', this.isFollow);
    await profileRadar?.save();
    this.isFollow = !this.isFollow;
    this.isFollow ? (this.numsObject.fans += 1) : (this.numsObject.fans -= 1);
  }
  onShowImg(url: string) {
    this.currenImg = url;
    this.preview.show = 'inline-flex';
  }
  onShow() {
    if (this.uid == this.currentUser?.id) this.isOpen = true;
  }

  /* 更换背景 */
  async onSaveBackGround(e: any) {
    let url = e[0]?.url;
    console.log(url);
    if (!url) {
      const toast = await this.toastController.create({
        message: '请上传背景图片',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    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.aiChatServ.company,
      });
    }
    this.profile?.set('image', url);
    await this.profile?.save();
    const toast = await this.toastController.create({
      message: '保存成功',
      color: 'success',
      duration: 1000,
    });
    toast.present();
    this.isOpen = false;
  }
  onEdit() {
    this.router.navigate(['/user/setting'], {
      queryParams: {
        id: this.uid,
      },
    });
  }
  toMsg() {
    this.router.navigate(['live/chat/' + this.uid]);
  }
  async toLiveContact() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '邀请通话',
      message: '你将与对方发起私聊通话',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (blah) => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler: () => {
            this.router.navigate(['live/link-room/' + this.room?.id]);
          },
        },
      ],
    });
    await alert.present();
  }
  onSendGift() {
    console.log('点击送出礼物');
    // this.liveService.get_duration()
  }
}
