import { Component, OnInit, ViewChild } from '@angular/core';
import {
  AlertController,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import { NavComponent } from '../../../app/components/nav/nav.component';
import { LiveService } from '../../../services/live.service';
import { UploadComponent } from '../../../app/components/upload/upload.component';
import * as Parse from 'parse';
import { AuthService } from '../../../services/auth.service';
import { FormsModule } from '@angular/forms';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';
import { ConnectTaskService } from '../../../services/connectTask.service';

@Component({
  selector: 'app-room-manage',
  templateUrl: './room-manage.component.html',
  styleUrls: ['./room-manage.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    NavComponent,
    UploadComponent,
    FormsModule,
  ],
})
export class RoomManageComponent implements OnInit {
  @ViewChild('upload') upload!: UploadComponent;
  room?: Parse.Object;
  formData: any = {
    title: '',
    cover: null,
    content: null,
    price: 0.5,
  };
  loading: any;
  profile?: Parse.Object;
  initLoad: boolean = true;
  placeholder: string = '请填写点播费用';
  min: number = 1;
  max: number = 990;
  constructor(
    private toastController: ToastController,
    private loadingCtrl: LoadingController,
    private liveService: LiveService,
    private alertController: AlertController,
    private connectTask: ConnectTaskService,
    private authServ: AuthService
  ) {}

  async ngOnInit() {
    await this.getProfile();
    this.getRoom();
  }
  // 获取用户信息
  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');
    let r = await query.first();
    this.profile = r;
    if (r?.get('state')) {
      switch (r?.get('state')) {
        case '三星':
          this.min = 20;
          this.max = 99;
          break;
        case '四星':
          this.min = 100;
          this.max = 150;
          break;
        case '五星':
          this.min = 160;
          this.max = 990;
          break;
        default:
          break;
      }
    }
    this.placeholder = this.min + '-' + this.max;
    localStorage.setItem('profile', JSON.stringify(this.profile?.toJSON()));
  }
  /* 直播间 */
  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('user', Parse.User.current()?.id);
    query.equalTo('profile', this.profile?.id);
    query.notEqualTo('isDeleted', true);
    this.room = await query.first();
    this.formData = {
      title: this.room?.get('title'),
      cover: this.room?.get('cover'),
      content: this.room?.get('content'),
      price: this.profile?.get('laborCosts') || 1,
    };
    console.log(this.formData);
    this.initLoad = false;
  }
  onChange() {
    this.formData.price = Math.max(
      0.5,
      parseFloat(this.formData.price.toFixed(1))
    );
    console.log(this.formData.price);
  }
  async saveEdit(e: any) {
    let url = e[0]?.url;
    console.log(url);
    if (!url || !this.formData.title || !this.formData.price) {
      const toast = await this.toastController.create({
        message: '请填写完整',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if(this.formData.price < this.min || this.formData.price > this.max){
      const toast = await this.toastController.create({
        message: '请输入正确的点播费用',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
      return;
    }
    this.loading = await this.loadingCtrl.create({
      message: '正在保存修改',
    });
    this.loading.present();
    this.profile?.set('laborCosts', this.formData.price);
    await this.profile?.save();
    if (!this.room?.id) {
      let obj = Parse.Object.extend('Room');
      this.room = new obj();
      this.room?.set('user', Parse.User.current()?.toPointer());
      this.room?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
      this.room?.set('profile', {
        __type: 'Pointer',
        className: 'Profile',
        objectId: this.profile?.id,
      });
      this.room?.set('roomid', this.profile?.id);
    }
    this.room?.set('title', this.formData.title);
    this.room?.set('cover', url);
    this.room?.set('content', this.formData.content);
    await this.room?.save();
    this.room && this.liveService.getToken(this.room);
    this.loading.dismiss();
    this.getRoom();
    await this.connectTask.anchorOnline(); //房间修改或创建后重新初始化连接
    this.presentAlert('保存成功');
  }
  async presentAlert(msg: string) {
    const alert = await this.alertController.create({
      header: '提示',
      message: msg,
      buttons: [
        {
          text: '好的',
          role: 'confirm',
          handler: () => {},
        },
      ],
    });
    await alert.present();
  }
}
