import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { addIcons } from 'ionicons';
import { add,close,location,lockOpen} from 'ionicons/icons';
import { CloudObject} from 'src/lib/ncloud';

@Component({
  selector: 'app-tab3',
  templateUrl: './tab3.page.html',
  styleUrls: ['./tab3.page.scss'],
  standalone: true,
  imports: [
    CommonModule,
    IonicModule,
    FormsModule,
  ]
})
export class Tab3Page {
  postTitle: string = '';
  postContent: string = '';
  selectedFiles: { src: string | ArrayBuffer | null, isImage: boolean }[] = []; // 用于存储多个文件信息
  location: string = ''; // 新增属性，用于存储地点
  isPublic: boolean = true; // 新增属性，用于存储公开可见状态
  saveToAlbum: boolean = false; // 新增属性，用于存储是否保存到相册
  visibility: string = 'none'; // 初始化可见性变量，默认值可以根据需求设定

  cities: string[] = [
    '北京', '上海', '广州', '深圳', '杭州', '成都', '武汉',
    '南京', '西安', '重庆', '天津', '青岛', '沈阳', '郑州',
    '合肥', '厦门', '福州', '哈尔滨', '长春', '济南', '南昌',
    // ... 继续添加更多城市
  ];

  constructor() {
    addIcons({ add,close,location,lockOpen});
  }


  onFilesSelected(event: Event) {
    // 清空已选文件数组
    this.selectedFiles = [];

    const files = (event.target as HTMLInputElement).files;
    if (files) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const reader = new FileReader();
        reader.onload = () => {
          this.selectedFiles.push({ src: reader.result, isImage: file.type.startsWith('image/') }); // 将文件信息添加到数组中
        };
        reader.readAsDataURL(file);
      }
    }
  }

  removeFile(fileToRemove: { src: string | ArrayBuffer | null, isImage: boolean }) {
    this.selectedFiles = this.selectedFiles.filter(file => file !== fileToRemove); // 从数组中移除指定文件
  }

  sendMessage() {
    
  }

  publishPost() {
    if (this.postTitle && this.postContent && this.location) {

    // 创建一个新的CloudObject实例，类名为"TravelPost"
    const post = new CloudObject('TravelPost');
console.log(this.postTitle);
    // 设置帖子的属性
    post.set({
      title: this.postTitle,
      content: this.postContent,
      location: this.location,
      isPublic: this.isPublic,
      saveToAlbum: this.saveToAlbum,
      visibility: this.visibility
    });

    // 保存帖子到数据库
    post.save().then(
      () => {
        console.log('Post created successfully:', post);
        this.clearForm();
      },
      (error) => {
        console.error('Failed to create post:', error);
      }
    );
    } else {
      console.log('标题和正文不能为空');
    }
  }
  //清空表单
  clearForm() {
    this.postTitle = '';
    this.postContent = '';
    this.selectedFiles = [];
    this.location = '';
    this.isPublic = true;
    this.saveToAlbum = false;
    this.visibility = 'none';
  }
  
}