import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { Router } from '@angular/router';
import { CloudObject, CloudUser } from 'src/lib/ncloud';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-dynamic-create',
  templateUrl: './dynamic-create.page.html',
  styleUrls: ['./dynamic-create.page.scss'],
  standalone:false,
})
export class DynamicCreatePage implements OnInit {

  content = '';
  images: {file: File, url: string}[] = [];
  currentTime = new Date().toISOString();
  currentUser: any = null;

  constructor(
    private navCtrl: NavController,
    private router: Router,
    private alertController: AlertController
  ) {}

  async ngOnInit() {
    // 获取当前用户
    this.currentUser = new CloudUser();
    await this.currentUser.current();
  }

  onFileChange(event: any) {
    const files = event.target.files;
    if (files && files.length > 0) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file.type.match('image.*')) {
          const reader = new FileReader();
          reader.onload = (e: any) => {
            this.images.push({
              file: file,
              url: e.target.result
            });
          };
          reader.readAsDataURL(file);
        }
      }
    }
  }

  removeImage(index: number) {
    this.images.splice(index, 1);
  }

  async submitDynamic() {
    if (!this.content) return;

    try {
      // 1. 创建动态对象
      const dynamic = new CloudObject("Dynamic");
      
      // 2. 上传图片（如果有）
      const imageUrls = [];
      for (const img of this.images) {
        // 这里需要实现图片上传逻辑，返回图片URL
        // 示例：const uploadedUrl = await this.uploadImage(img.file);
        // imageUrls.push(uploadedUrl);
        imageUrls.push(img.url); // 临时使用本地URL，实际应该上传到服务器
      }

      // 3. 设置动态数据
      dynamic.set({
        content: this.content,
        images: imageUrls,
        author: this.currentUser.toPointer(),
        createdAt: new Date(),
        isPublic: true,
        likeCount: 0,
        commentCount: 0,
        shareCount: 0
      });

      // 4. 保存动态
      await dynamic.save();

      // 5. 显示成功提示
      const alert = await this.alertController.create({
        header: '发布成功',
        message: '动态已成功发布',
        buttons: ['确定']
      });
      await alert.present();

      // 6. 返回并刷新动态列表
      this.navCtrl.navigateBack('/tabs/tab2');
      
    } catch (error) {
      console.error('发布动态失败:', error);
      const alert = await this.alertController.create({
        header: '发布失败',
        message: '动态发布失败，请重试',
        buttons: ['确定']
      });
      await alert.present();
    }
  }

  // 实际项目中需要实现图片上传方法
  private async uploadImage(file: File): Promise<string> {
    // 这里应该实现图片上传逻辑，返回图片URL
    // 示例代码：
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch('http://dev.fmode.cn:1337/parse/files/image.jpg', {
      method: 'POST',
      headers: {
        'X-Parse-Application-Id': 'dev',
        'X-Parse-Session-Token': this.currentUser.sessionToken
      },
      body: formData
    });
    
    const result = await response.json();
    return result.url;
  }

}
