import { Component, OnInit } from '@angular/core';
import * as Parse from 'parse';
import { ActivatedRoute, Router } from '@angular/router';
import { Swiper } from 'swiper';
import { AiChatService } from '../../../services/aichart.service';
import { ConnectTaskService } from '../../../services/connectTask.service';
import {
  ionicStandaloneModules,
  AlertController,
  LoadingController,
  ToastController,
} from '../../ionic-standalone.modules';
import { CommonModule, DatePipe } from '@angular/common';
import { provinceMap } from '../../../services/address';
import { FormsModule } from '@angular/forms';
import { InfiniteScrollCustomEvent } from '@ionic/core';
import { MessageService } from '../../../services/message.service';
import { DeviceService } from '../../../services/device.service';
@Component({
  selector: 'app-anthorhome',
  templateUrl: './anthorhome.component.html',
  styleUrls: ['./anthorhome.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, CommonModule, FormsModule],
  providers: [DatePipe],
})
export class AnthorhomeComponent implements OnInit {
  value: string = '';
  banner: Array<Parse.Object> = [];
  notices: Array<any> = [];
  viewAnchor: string = localStorage.getItem('sex') || '女';
  get sex(): string {
    const map: any = {
      男: '男',
      女: '女',
    };
    return map[this.viewAnchor];
  }
  isOpenCity: boolean = false;
  provinceColumns = [];
  cityColumns = [];
  province: string = ''; //省份
  city: string = ''; //市
  old_province: string = ''; //省份
  old_city: string = ''; //市
  // isColumn: boolean = false; //单排
  userList: Array<string> | any = [];

  isOpen: boolean = false;
  greetingPhrases: Array<string> = [
    '你好，很高兴认识你！',
    '嘿，最近怎么样？',
    '你好，有什么共同的兴趣吗？',
    '嗨，一起聊点什么吧！',
    '你好，最近在忙什么呢？',
    '嘿，很高兴看到你！',
    '你好，有什么推荐的吗？',
    '嗨，最近有啥新鲜事儿？',
    '你好，一起吃饭怎么样？',
    '嘿，很高兴能和你聊天！',
  ];
  checkUser: any; //当前选择的用户
  disbable: boolean = true;
  pushUserMap = new Set(); // 在线用户列表

  options: Array<any> = [
    {
      label: '用户',
      value: 'user',
      color: 'primary',
    },
    {
      label: '主播',
      value: 'anchor',
      color: 'primary',
    },
  ];
  roomList: Array<any> = [];
  active: string = 'user';
  isColumn: boolean = false; //单排

  constructor(
    private loadingCtrl: LoadingController,
    private alertController: AlertController,
    private activateRoute: ActivatedRoute,
    private connectTask: ConnectTaskService,
    private router: Router,
    private toastController: ToastController,
    private aiServ: AiChatService,
    private msgSer: MessageService,
    private datePipe: DatePipe,
    public deviceSer: DeviceService
  ) {
    // province.unshift({
    //   provinceName: '全部',
    //   citys: [
    //     {
    //       cityName: '',
    //       cityType: '',
    //     },
    //   ],
    // });
    this.provinceColumns = provinceMap.map((item) => item.provinceName);
    this.cityColumns = provinceMap[0].citys.map((item) => item.cityName);
  }

  ngOnInit() {
    // this.activateRoute.paramMap.subscribe(async (params) => {
    this.refresh();
    // });
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '正在加载',
    });
    loading.present();
    await this.connectTask.init();
    await this.getBanner();
    await this.getNotice();
    await this.getUserList();
    setTimeout(() => {
      this.initSwiperTimeEvent();
      loading.dismiss();
    }, 100);
  }
  async getBanner() {
    let query = new Parse.Query('Banner');
    query.equalTo('company', this.aiServ.company);
    query.descending('index');
    query.equalTo('isEnabled', true);
    query.equalTo('type', 'home');
    query.notEqualTo('isDeleted', true);
    let banner = await query.find();
    this.banner = banner;
  }
  async getNotice() {
    let query = new Parse.Query('Notice');
    query.equalTo('company', this.aiServ.company);
    query.notEqualTo('isDeleted', true);
    query.equalTo('type', 'application');
    query.select('title', 'content');
    query.descending('createdAt');
    this.notices = await query.find();
  }
  async getUserList() {
    let res = await this.aiServ.getLinkUsers({
      value: this.value ? this.value : '',
      skip: this.userList.length,
      sex: this.viewAnchor,
      city: this.city,
    });
    console.log(res);
    if (res.length == 0) {
      const toast = await this.toastController.create({
        message: '已加载全部内容',
        duration: 1500,
        color: 'warning',
      });
      toast.present();
      return res.length;
    }
    this.userList.push(...res);
    return res.length;
  }
  initSwiperTimeEvent() {
    // 初始化轮播图
    let swiper = new Swiper('.mySwiper1', {
      loop: true, // 循环模式选项
      observer: false, //修改swiper自己或子元素时，自动初始化swiper
      observeParents: true, //修改swiper的父元素时，自动初始化swiper
      autoplay: {
        delay: 3000,
      },
      pagination: {
        el: '.swiper-pagination',
      },
    });
    swiper.on('slideChange', function (event: any) {
      // console.log(event);
    });

    let swiperNot = new Swiper('.swiper-notice1', {
      loop: true, // 循环模式选项
      observer: false, //修改swiper自己或子元素时，自动初始化swiper
      observeParents: true, //修改swiper的父元素时，自动初始化swiper
      autoplay: {
        delay: 3000,
      },
      direction: 'vertical',
    });
  }

  async presentAlert(item: any) {
    const alert = await this.alertController.create({
      header: item?.get('title') || '消息通知',
      subHeader: this.datePipe.transform(item?.createdAt, 'yyyy-MM-dd HH:mm')!,
      message: item?.get('content') || '',
      buttons: item?.get('url')
        ? [
            { text: '关闭' },
            {
              text: '确定',
              handler: () => {
                this.router.navigate([item?.get('url')]);
              },
            },
          ]
        : [{ text: '关闭' }],
    });
    await alert.present();
  }

  onChangeSex(e: any) {
    localStorage.setItem('sex', e.detail.value);
    if (e.detail.value == this.viewAnchor) return;
    this.viewAnchor = e.detail.value;
    this.userList = [];
    this.getUserList();
    this.disbable = true;
  }

  toUrl(url: string) {
    url && this.router.navigate([url]);
  }

  changeCityCancel(type: string) {
    if (type === 'confirm') {
      if (this.city !== this.old_city) {
        this.userList = [];
        this.getUserList();
        this.disbable = true;
      }
      this.old_province = this.province;
      this.old_city = this.city;
    } else {
      this.province = this.old_province;
      this.city = this.old_city;
    }
    this.isOpenCity = false;
  }
  onIonChangeCity(event: CustomEvent, type: string) {
    let val = event.detail.value;
    switch (type) {
      case 'province':
        this.province = event.detail.value;
        this.cityColumns = provinceMap
          .find((item) => item.provinceName === val)
          ?.citys.map((item) => item.cityName)!;
        console.log(this.cityColumns);
        this.city = this.cityColumns[0];
        break;
      case 'city':
        this.city = event.detail.value;
        break;
    }
    console.log(this.province, this.city);
  }
  async toSearch() {
    this.disbable = true;
    console.log(this.active);
    if (this.active == 'user') {
      this.userList = [];
      this.getUserList();
    } else {
      this.roomList = [];
      this.getRoom();
    }
  }
  async onIonInfinite(ev: any) {
    let result;
    if (this.active == 'user') {
      result = await this.getUserList();
    } else {
      result = await this.getRoom();
    }
    if (result == 0) {
      this.disbable = false;
    }
    setTimeout(() => {
      (ev as InfiniteScrollCustomEvent).target.complete();
    }, 500);
  }
  onOpenGreetingPhrase(user: any) {
    this.checkUser = user;
    this.isOpen = true;
  }
  async changeGreetingPhrase(msg: string) {
    const userStatus = await this.connectTask.getState(
      this.checkUser.uid,
      this.checkUser.uid
    );
    if (userStatus !== 'ONLINE') {
      const toast = await this.toastController.create({
        message: '对方不在线或忙线中',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return;
    }
    if (!this.pushUserMap.has(this.checkUser.uid!)) {
      await this.msgSer.subscribeMessage(this.checkUser.uid!, {
        presence: true,
      }); //进入对方主播频道发送聊天邀请
    }
    this.msgSer.publishMessage('USERGREETING_' + msg, this.checkUser.uid!);
    console.log(msg);
    this.pushUserMap.add(this.checkUser.uid!);
    const toast = await this.toastController.create({
      message: '已发送',
      duration: 1000,
      color: 'success',
    });
    toast.present();
    this.isOpen = false;
  }

  onChange(e: any) {
    // console.log(e.detail.value);
    this.roomList = [];
    this.currentValue = e.detail.value;
    this.getRoom();
  }
  async getRoom(type?: string) {
    console.log(type);
    const loading = await this.loadingCtrl.create({
      message: '正在加载',
    });
    loading.present();
    let data: Array<any> = [];
    // if (type == this.oldCurrentValue) {
    //   loading.dismiss();
    //   return;
    // }
    // this.oldCurrentValue = this.currentValue;
    if (!type) type = this.currentValue;
    let uid = Parse.User.current()?.id;
    let sex = null;
    if (!this.connectTask.onlineUserList.size) {
      await this.connectTask.getOnlieUserList('user_connect_room');
    }
    this.userList = Array.from(this.connectTask.onlineUserList) || [];
    // console.log(userList);
    switch (type) {
      case 'follow':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          follow: true,
          sex,
          city: this.city,
        });
        break;
      case 'recommend':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          recommend: true,
          sex,
          city: this.city,
        });
        break;
      case 'news':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          sex,
          city: this.city,
        });
        break;
      case '三星':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          star: '三星',
          sex,
          city: this.city,
        });
        break;
      case '四星':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          star: '四星',
          sex,
          city: this.city,
        });
        break;
      case '五星':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          star: '五星',
          sex,
          city: this.city,
        });
        break;
      case '海外':
        data = await this.aiServ.getRooms({
          title: this.value,
          skip:this.roomList.length,
          uid: uid,
          // users: userList,
          star: '海外',
          sex,
          city: this.city,
        });
        break;

      default:
        break;
    }
    if (data.length == 0) {
      loading.dismiss();
      const toast = await this.toastController.create({
        message: '已加载全部内容',
        duration: 1500,
        color: 'warning',
      });
      toast.present();
      return data.length;
    }
    this.roomList.push(...data);
    loading.dismiss();
    return data.length;
  }
  currentValue: string = 'recommend';
  segmentChanged(e: any) {
    this.disbable = true;
    let { value } = e.detail;
    this.active = value;
    this.value = '';
    console.log(this.active);
    if (this.active == 'user') {
      this.userList = [];
      this.getUserList();
    } else {
      this.roomList = [];
      this.getRoom();
    }
  }
}
