import { Component, OnInit, ViewChild } from '@angular/core';
import {
  AlertController,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import { NavComponent } from '../../../app/components/nav/nav.component';
import * as Parse from 'parse';
// import { Router } from '@angular/router';
import { UploadComponent } from '../../../app/components/upload/upload.component';
import { AuthService } from '../../../services/auth.service';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';
import { province } from '../../../services/address';
import { CommonModule } from '@angular/common';
import { AccountService } from '../../../services/account.service';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    NavComponent,
    UploadComponent,
    CommonModule,
  ],
})
export class SettingComponent implements OnInit {
  @ViewChild('upload') upload!: UploadComponent;
  profile?: Parse.Object; //身份信息
  formData: any = {
    avatar: '',
    name: '',
    nickname: '',
    sex: '',
    age: '',
    remark: '',
    auditing:false
  };
  mobile: string = '';
  loading: any;
  isOpen: boolean = false;

  address: string = '';
  provinceColumns = province.map((item) => item.provinceName);
  cityColumns = province[0].citys.map((item) => item.cityName);
  province: string = ''; //省份
  city: string = ''; //市

  isOpenTag: boolean = false;
  tags: any[] = [
    { val: '篮球', check: false },
    { val: '音乐', check: false },
    { val: '90后', check: false },
    { val: '00后', check: false },
    { val: '可爱', check: false },
    { val: '旅行', check: false },
    { val: '摄影', check: false },
    { val: '电影', check: false },
    { val: '阅读', check: false },
    { val: '美食', check: false },
    { val: '健身', check: false },
    { val: '游戏', check: false },
    { val: '编程', check: false },
    { val: '绘画', check: false },
    { val: '写作', check: false },
    { val: '舞蹈', check: false },
    { val: '时尚', check: false },
    { val: '宠物', check: false },
    { val: '手工', check: false },
    { val: '咖啡', check: false },
    { val: '动漫', check: false },
    { val: '历史', check: false },
    { val: '科技', check: false },
    { val: '运动', check: false },
    { val: '瑜伽', check: false },
    { val: '文学', check: false },
    { val: '心理学', check: false },
    { val: '创业', check: false },
    { val: '投资', check: false },
    { val: '环保', check: false },
    { val: '公益', check: false },
    { val: '书法', check: false },
    { val: '棋类', check: false },
    { val: '骑行', check: false },
    { val: '游泳', check: false },
    { val: '登山', check: false },
    { val: '滑板', check: false },
    { val: '电竞', check: false },
    { val: '手办', check: false },
    { val: '汉服', check: false },
    { val: '古风', check: false },
    { val: '民谣', check: false },
    { val: '摇滚', check: false },
    { val: '街舞', check: false },
    { val: '爵士', check: false },
    { val: '古典乐', check: false },
    { val: '流行乐', check: false },
    { val: '户外', check: false },
    { val: '露营', check: false },
  ];
  get getTag(){
    return this.tags.filter(item=>item.check);
  }
  vip:any
  constructor(
    private alertController: AlertController,
    public loadingCtrl: LoadingController,
    public toastController: ToastController,
    private authServ: AuthService,
    private accServ: AccountService,
    // private router: Router
  ) {}

  ngOnInit() {
    this.getProfile();
  }
  // 获取用户信息
  async getProfile() {
    this.loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    this.loading.present();
    let user = Parse.User.current();
    let query = new Parse.Query('Profile');
    query.equalTo('user', user?.id);
    query.notEqualTo('isDeleted', true);
    this.profile = await query.first();
    this.formData.avatar =
      user?.get('avatar') ||
      'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png';
    this.formData.nickname = user?.get('nickname') || '';
    this.formData.sex = user?.get('sex') || '';
    this.formData.age = user?.get('age') || '';
    this.mobile = user?.get('mobile');
    this.formData.name = this.profile?.get('name') || '';
    this.formData.age = this.profile?.get('birthdate') || '';
    this.formData.remark = this.profile?.get('remark') || '';
    this.formData.auditing = this.profile?.get('auditing');
    this.loading.dismiss();
    if (user?.get('city') && user?.get('province')) {
      this.address = user?.get('province') + '-' + user?.get('city');
    }
    this.province = user?.get('province') || this.provinceColumns[0];
    this.city = user?.get('city') || this.cityColumns[0];
    this.tags.map(item=>{
      item.check = this.profile?.get('tags')?.includes(item.val) || false;
    })
    this.vip = this.accServ.userVip;
  }
  onChange(e: any, type: string) {
    this.formData[type] = e.detail.value;
  }
  async onChangeTag() {
    this.isOpenTag = true;
  }
  async saveEdit(e: any) {
    this.loading = await this.loadingCtrl.create({
      message: '正在保存修改',
    });
    this.loading.present();
    console.log(e);
    console.log(this.formData);
    let urls = e?.map((item: any) => item.url);
    let user = Parse.User.current();
    if (!user?.id) {
      this.loading.dismiss();
      const alert = await this.alertController.create({
        header: '提示',
        message: '登录信息已过期,请重新登录',
        buttons: [
          {
            text: '好的',
            role: 'confirm',
            handler: () => {
              this.authServ.logout();
            },
          },
        ],
      });
      await alert.present();
      return;
    }
    user.set('avatar', urls[0]);
    user.set('nickname', this.formData.nickname);
    user.set('sex', this.formData.sex);
    // user.set('age', Number(this.formData.age));
    user.set('address', this.address);
    user.set('city', this.city);
    user.set('province', this.province);
    await user.save();
    if (!this.profile?.id) {
      let obj = Parse.Object.extend('Profile');
      this.profile = new obj();
      this.profile?.set('user', Parse.User.current()?.toPointer());
      this.profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
    }
    this.profile?.set('mobile', Parse.User.current()?.get('mobile'));
    this.profile?.set('sex', this.formData.sex);
    this.profile?.set('birthdate', this.formData.age);
    this.profile?.set('remark', this.formData.remark);
    this.profile?.set('auditing', this.formData.auditing);
    this.profile?.set('address', this.address);
    let t = this.tags.filter((x) => x.check)?.map(item=> item.val)
    this.profile?.set('tag', t);
    await this.profile?.save();
    this.loading.dismiss();
    this.getProfile();
    this.presentAlert('修改成功');
  }

  async presentToast(title: string, time: number, color: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time,
      color: color,
    });
    toast.present();
  }

  async presentAlert(msg: string) {
    const alert = await this.alertController.create({
      header: '提示',
      message: msg,
      buttons: [
        {
          text: '好的',
          role: 'confirm',
          handler: () => {},
        },
      ],
    });
    await alert.present();
  }

  cancel(type: string) {
    if (type === 'cancel') {
      this.province = this.address.split('-')[0];
      this.city = this.address.split('-')[1];
    } else {
      this.address = this.province + '-' + this.city;
    }
    this.isOpen = false;
    console.log(this.address);
  }
  onCheck(index: number) {
    let n = this.tags.filter((item) => item.check).length;
    if (!this.tags[index].check && n > 10) {
      this.presentToast('最多选择10个标签', 1500, 'warning');
      return;
    }
    this.tags[index].check = !this.tags[index].check;
  }
  onIonChange(event: CustomEvent, type: string) {
    let val = event.detail.value;
    switch (type) {
      case 'province':
        this.province = event.detail.value;
        this.cityColumns = province
          .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);
  }
}