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 * as Parse from 'parse';
import { ImagePreviewComponent } from '../../../app/components/image-preview/image-preview.component';
import { AiChatService } from '../../../services/aichart.service';
import { UploadComponent } from '../../../app/components/upload/upload.component';
import { GiftModalComponent } from '../../../app/components/gift-modal/gift-modal.component';
// import { MessageService } from '../../../services/message.service';
import { ConnectTaskService } from '../../../services/connectTask.service';
import { getBirthdatByIdNo, getConstellation } from '../../../services/utils';
import {
  ionicStandaloneModules,
  // AlertController,
  LoadingController,
  ToastController,
} from '../../ionic-standalone.modules';
import { AccountService } from '../../../services/account.service';
import { CallModalComponent } from '../../../app/components/call-modal/call-modal.component';
import { AvatarComponent } from '../../../app/components/avatar/avatar.component';
import { AppraiseComponent } from '../../../app/components/appraise/appraise.component';
import { DeviceService } from '../../../services/device.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    FormsModule,
    // DatePipe,
    // NavComponent,
    CommonModule,
    ImagePreviewComponent,
    UploadComponent,
    GiftModalComponent,
    CallModalComponent,
    AvatarComponent,
    AppraiseComponent
  ],
  providers: [DatePipe],
})
export class ProfileComponent implements OnInit {
  // @ViewChild('upload') upload!: UploadComponent;
  @ViewChild('call') call!: CallModalComponent;

  uid: string = '';
  currentUser?: Parse.Object = Parse.User.current(); //当前登录用户
  user?: Parse.Object; // 查看用户
  @ViewChild('preview') preview!: ImagePreviewComponent;
  friends?: Parse.Object; // 好友
  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;
  // iscall: boolean = false;
  // isLiveing: boolean = false; // 是否在直播通话中
  userStatus: string = 'OFFLINE';
  loading: boolean = true;
  userVip:any
  commentObj:any = {
    score: 0,
    count:0,
    list: []
  }
  userProfile = JSON.parse(localStorage.getItem('profile') || '');
  constructor(
    private activateRoute: ActivatedRoute,
    private router: Router,
    private toastController: ToastController,
    private loadingCtrl: LoadingController,
    public aiChatServ: AiChatService,
    // private alertController: AlertController,
    // private msgSer: MessageService,
    private connectTask: ConnectTaskService,
    public accServ: AccountService,
    public deviceSer: DeviceService
  ) {}
  get state() {
    let map: any = {
      REFUSE: {
        val: '勿扰',
        color: '#f1ac16',
      },
      ONLINE: {
        val: '在线',
        color: '#28bb50',
      },
      OFFLINE: {
        val: '离线',
        color: '#a1a1a1',
      },
      CONNECTING: {
        val: '忙线',
        color: '#cf1b24',
      },
      '': {
        val: '离线',
        color: '#a1a1a1',
      },
    };
    return map?.[this.userStatus] || map['OFFLINE'];
  }

  birthdat?: string;
  constellation?: string;
  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let id: any = params.get('id');
      this.uid = id;
      await this.refresh();
      if (this.uid !== this.currentUser?.id) {
        this.userStatus = await this.connectTask.getState(this.uid, this.uid);
      } else {
        this.userStatus = 'ONLINE';
      }
      if (this.profile?.get('isCheck') && this.userStatus == 'ONLINE') {
        this.userStatus = 'REFUSE';
      }
    });
  }
  ngOnDestroy(): void {
    // if (!this.isLiveing && this.uid !== this.currentUser?.id) {
    //   console.log('断开连接');
    //   this.msgSer?.unsubscribeMessage(this.uid);
    // }
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    this.userVip = await this.accServ.getVip(this.uid)
    await this.getFriends();
    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);
    await this.getCommentLeng()
    this.browseLog()
    // this.getRoom();
    loading.dismiss();
    this.loading = false;
  }
  async getFriends() {
    let query1 = new Parse.Query('Friends');
    query1.equalTo('user', this.currentUser?.id);
    query1.equalTo('friend', this.uid);
    let query2 = new Parse.Query('Friends');
    query2.equalTo('user', this.uid);
    query2.equalTo('friend', this.currentUser?.id);
    let query = Parse.Query.or(query1, query2);
    query.notEqualTo('isDeleted', true);
    query.select('objectId', 'isPass', 'channel');
    this.friends = await query.first();
  }
  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();
    }
    this.birthdat = getBirthdatByIdNo(this.profile?.get('idcard') || '');
    this.constellation = getConstellation(this.profile?.get('idcard') || '');
  }
  async getCommentLeng(){
    let query = new Parse.Query('Room');
    query.equalTo('user', this.uid);
    query.notEqualTo('isDeleted', true);
    query.select('objectId');
    let r = await query.first();
    if(r?.id){
      this.room = r;
      // this.commentObj.score = await this.aiChatServ.getCommentScore(r?.id);
      let queryPost = new Parse.Query('DramaPostLog');
      queryPost.equalTo('room', r.id);
      queryPost.notEqualTo('isDeleted', true);
      queryPost.include('user');
      queryPost.descending('createdAt');
      queryPost.equalTo('isVerify',true)
      this.commentObj.count = await queryPost.count();
      queryPost.limit(10);
      this.commentObj.list = await queryPost.find();
    }
    console.log(this.commentObj);
  }
  /* 关注状态 */
  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 browseLog() {
    let result = await this.judgeIsBrowse();
    let ProfileRadar, tool;
    if (result) {
      return;
    } else {
      // 创建一条浏览记录
      ProfileRadar = Parse.Object.extend('ProfileRadar');
      tool = new ProfileRadar();
      tool.set('name', '查看');
      tool.set('fromUser', {
        __type: 'Pointer',
        className: '_User',
        objectId: Parse.User.current()?.id,
      });
      tool.set('toUser', {
        __type: 'Pointer',
        className: '_User',
        objectId: this.user?.id,
      });
      tool.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.aiChatServ.company,
      });
      await tool.save();
      console.log('---创建了浏览历史记录---');
    }
  }
  // 根据点击查看记录半小时内是否有此浏览记录
  async judgeIsBrowse() {
    let ProfileRadar = new Parse.Query('ProfileRadar');
    ProfileRadar.equalTo('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.aiChatServ.company,
    });
    ProfileRadar.equalTo('fromUser', Parse.User.current()?.id!);
    ProfileRadar.equalTo('toUser', this.user?.id,);
    ProfileRadar.greaterThanOrEqualTo(
      'createdAt',
      new Date(new Date().getTime() - 1000 * 60 * 30)
    );
    ProfileRadar.equalTo('name', '查看');
    ProfileRadar.select('objectId');
    let result = await ProfileRadar.first();
    if (result) {
      return true;
    } else {
      return false;
    }
  }

  // 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 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 = Number(this.numsObject.fans) + 1) : (this.numsObject.fans = 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 onFriend() {
    if (this.friends?.id && !this.friends?.get('isPass')) {
      const toast = await this.toastController.create({
        message: '已申请，等待对方同意',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return;
    }
    if (!this.friends?.id) {
      let obj = Parse.Object.extend('Friends');
      this.friends = new obj();
      this.friends?.set('user', this.currentUser?.toPointer());
      this.friends?.set('friend', this.user?.toPointer());
      this.friends?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.aiChatServ.company,
      });
      this.friends?.set('channel', this.user?.id + '-' + this.currentUser?.id);
      await this.friends?.save();
      const toast = await this.toastController.create({
        message: '已申请，等待对方同意',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
    }
  }

  /* 更换背景 */
  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.friends?.get('channel')]);
  }
  tourl(url:string, params:object){
    this.router.navigate([url,params]);
  }
  onSendGift() {
    console.log('点击送出礼物');
    // this.liveService.get_duration()
  }
  back(){
    history.back();
  }
}
