import { Component, ViewChild, Input } from '@angular/core';
// import { ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import * as Parse from 'parse';
import { IonicModule } from '@ionic/angular';

// 全局消息服务和JIM插件
import { OnInit } from '@angular/core';
// import { AlertController } from '@ionic/angular';
import { FlutterCompComponent } from '../../../app/components/flutter-comp/flutter-comp.component';
// import { MessageService } from '../../../services/message.service';
// import { ConnectTaskService } from '../../../services/connectTask.service';

import { Camera } from '@capacitor/camera';
import { Filesystem } from '@capacitor/filesystem';
import { DeviceService } from '../../../services/device.service';
import { CommonModule } from '@angular/common';
import { HttpService } from '../../../services/http.service';

@Component({
  selector: 'live-tabs',
  templateUrl: 'tabs.component.html',
  styleUrls: ['tabs.component.scss'],
  standalone: true,
  imports: [IonicModule, FlutterCompComponent,CommonModule],
})
export class TabsComponent implements OnInit {
  @Input('tabsOption') tabsOption: any = {};
  company: any = window.localStorage.getItem('company');
  constructor(
    private router: Router,
    // private alertController: AlertController,
    private activateRoute: ActivatedRoute,
    public deviceSer: DeviceService,
    private http: HttpService
  ) // private connectTask: ConnectTaskService
  {
    this.activateRoute.paramMap.subscribe(async (params) => {
      await this.presentAlert();
      // this.connectTask.init();
      this.active = this.option.findIndex((item: any) => {
        return item.url == location.pathname.slice(1)
      }) ?? 0
    });
  }

  option: any = [
    {
      src: 'img/首页.png',
      active: 'img/首页_active.png',
      url: 'tabs/home',
      name: '首页',
    },
    {
      src: 'img/消息.png',
      active: 'img/消息_active.png',
      url: 'tabs/notice',
      name: '消息',
    },
    // {
    //   src: 'img/live.png',
    //   active: 'img/live.png',
    //   url: 'tabs/live-review',
    //   name: '直播',
    // },
    {
      src: 'img/圈子.png',
      active: 'img/圈子_active.png',
      url: 'tabs/space',
      name: '种花',
    },
    // {
    //   src: 'img/排名.png',
    //   active: 'img/排名_active.png',
    //   url: 'tabs/ranking',
    //   name: '排名',
    // },
    {
      src: 'img/我的.png',
      active: 'img/我的_active.png',
      url: 'tabs/my',
      name: '我的',
    },
  ];
  show: any;
  active: number = 0;

  ngOnInit() {
    this.initDeviceService()
    this.updateParent()
  }

  async presentAlert() {
    // let profile = localStorage.getItem('profile');
    // if (profile) {
    //   return;
    // }
    let uid = Parse.User.current()?.id;
    let query = new Parse.Query('Profile');
    query.equalTo('user', uid);
    query.equalTo('isCross', true);
    query.equalTo('company', this.company);
    query.notEqualTo('isDeleted', true);
    let res = await query.first();
    if (res?.id) {
      localStorage.setItem('profile', JSON.stringify(res.toJSON()));
      if (res?.get('identyType') === 'anchor') {
        this.option.splice(0, 1, {
          src: 'img/首页.png',
          active: 'img/首页_active.png',
          url: 'tabs/anthirhome',
          name: '首页',
        });
      }
      return;
    }
    // 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');
    //     //   },
    //     // },
    //     {
    //       text: '去认证',
    //       handler: () => {
    //         this.router.navigate(['user/certification']);
    //       },
    //     },
    //   ],
    // });
    // await alert.present();
  }

  allowNavi: boolean = true;
  goTabPage(index: number, route: string) {
    if (this.allowNavi == false) {
      return;
    }
    this.active = index;
    localStorage.setItem('active', String(this.active));
    if (('temp' + route).indexOf('http') > 0) {
      window.location.href = route;
      console.log('temp' + route);
    } else {
      let r = route;
      let params: any = {};
      if (r.split(';').length > 1) {
        // 若存在;参数，则拼接参数对象params
        for (let index = 1; index < r.split(';').length; index++) {
          let key = r.split(';')[index].split('=')[0];
          let val = r.split(';')[index].split('=')[1];
          params[key] = val;
        }
        // 此时路由为数组第一个
        route = r.split(';')[0];
      }
      this.router.navigate([route, params]);
    }
    this.allowNavi = false;
    setTimeout(() => {
      this.allowNavi = true;
    }, 1000);
  }


  async initDeviceService() {
    try {
      // 请求相机权限
      const cameraPermission = await Camera.requestPermissions();
      if (cameraPermission.camera === 'granted') {
        console.log('相机权限已授予');
      } else {
        console.log('相机权限被拒绝');
      }

      // 请求文件系统权限
      const filesystemPermission = await Filesystem.requestPermissions();
      if (filesystemPermission.publicStorage === 'granted') {
        console.log('文件系统权限已授予');
      } else {
        console.log('文件系统权限被拒绝');
      }
      await this.requestMicrophonePermission()
    } catch (error) {
      console.warn('请求权限时出错:', error);
    }
  }
  async requestMicrophonePermission() {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      console.log('麦克风权限已授予');
      // 你可以在这里处理音频流
    } catch (error) {
      console.error('麦克风权限被拒绝或请求失败:', error);
    }
  }

  updateParent(){
    let url = `https://server.fmode.cn/api/user/agent/parent`
    this.http.httpRequst(url,{uid:Parse.User.current()?.id},'POST')
  }
}
