import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from '../post.service'; // 导入服务
import { IonBackButton, IonButton, IonButtons, IonContent, IonHeader, IonInput, IonItem, IonTitle, IonToolbar } from '@ionic/angular/standalone';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-share-page',
  templateUrl: './share-page.component.html',
  styleUrls: ['./share-page.component.scss'],
  standalone: true,
  imports: [IonHeader,IonToolbar,IonButtons,IonBackButton,IonContent,IonItem,IonInput,
    IonButton,FormsModule,CommonModule,IonTitle
    ],
})
export class SharePageComponent  implements OnInit {

  newPost: { text: string } = { text: '' };
  selectedFile: File | null = null; // 存储选择的文件
  imagePreview: string | null = null; // 存储图片预览的 URL

  constructor(private router: Router,private postService: PostService) {}

  onFileSelected(event: Event) {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
      this.selectedFile = target.files[0]; // 获取选择的文件
      const reader = new FileReader();
      reader.onload = () => {
        this.imagePreview = reader.result as string; // 设置图片预览
      };
      reader.readAsDataURL(this.selectedFile); // 读取文件为 Data URL
    }
  }

  submitPost() {
    if (this.newPost.text.trim()) {
      const newPostObj = {
        id: Math.floor(Math.random() * 10000), // 生成一个随机 ID，实际应用中可以使用更可靠的方式
        username: '当前用户', // 可以替换为实际的用户名
        date: new Date(),
        text: this.newPost.text,
        imageUrl: this.imagePreview?this.imagePreview:" ", // 将图片 URL 添加到新动态中
      };
      this.postService.addPost(newPostObj); // 使用服务添加新动态
      this.router.navigate(['/community']); // 发布后返回社区页面
    }
  }

  ngOnInit() {}

}
