import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';

@Component({
  selector: 'app-create-request',
  templateUrl: 'create-request.page.html',
  styleUrls: ['create-request.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule]
})
export class CreateRequestPage {
  request = {
    title: '',
    description: '',
    type: 'normal',
    points: 10,
    images: [] as File[],
    topic: '' // 新增话题字段
  };
  
  showTopics = false; // 控制下拉框显示
    hasDraft= false;

  toggleTopics() {
    this.showTopics = !this.showTopics;
  }

  @ViewChild('fileInput') fileInput: any;

  selectImage() {
    this.fileInput.nativeElement.click();
  }

  onImageSelected(event: any) {
    const file = event.target.files[0];
    if (file) {
      // 这里可以添加图片上传逻辑
      console.log('Selected image:', file);
      // 示例：将图片添加到请求对象
      this.request.images.push(file);
    }
  }

  constructor(private router: Router) {
    this.loadDraft();
  }

  async loadDraft() {
    try {
      const query = new CloudQuery("Drafts");
      const drafts = await query.find();
      if (drafts.length > 0) {
        const latestDraft = drafts[0];
        this.request = {
          title: latestDraft.get('title') || '',
          description: latestDraft.get('description') || '',
          type: latestDraft.get('type') || 'normal',
          points: latestDraft.get('points') || 10,
          images: latestDraft.get('images') || [],
          topic: latestDraft.get('topic') || ''
        };
        this.hasDraft = true;
      }
    } catch (error) {
      console.error('加载草稿失败:', error);
    }
  }

  async submitRequest() {
    try {
      const obj = new CloudObject("Inprogress");
      obj.set({
        title: this.request.title,
        description: this.request.description,
        type: this.request.type,
        points: this.request.points,
        status: 'pending'
      });
      await obj.save();
      this.router.navigate(['/tabs/tab2']); // 修改为正确的路由路径
    } catch (error) {
      console.error('提交需求失败:', error);
    }
  }

  dismiss() {
    this.router.navigate(['/tabs/tab2']); // 修改为正确的路由路径
  }

  addTopicToDescription() {
    if (this.request.topic && this.request.description.indexOf(this.request.topic) === -1) {
      this.request.description += (this.request.description ? '\n' : '') + this.request.topic;
    }
    this.showTopics = false; // 选择后隐藏下拉框
  }

  async saveDraft() {
    try {
      // 先清空所有草稿
      await this.clearAllDrafts();
      
      // 保存当前数据为新草稿
      const obj = new CloudObject("Drafts");
      obj.set({
        title: this.request.title,
        description: this.request.description,
        type: this.request.type,
        points: this.request.points,
        images: this.request.images,
        topic: this.request.topic
      });
      await obj.save();
      this.router.navigate(['/tabs/tab2']);
    } catch (error) {
      console.error('保存草稿失败:', error);
    }
  }
  
  async submitToPending() {
    try {
      const obj = new CloudObject("PendingRequests");
      obj.set({
        title: this.request.title,
        description: this.request.description,
        type: this.request.type,
        points: this.request.points,
        status: 'pending',
        topic: this.request.topic,
        images: this.request.images,
        time: new Date()
      });
      await obj.save();
      
      // 发布成功后删除所有草稿
      await this.clearAllDrafts();
      this.router.navigate(['/tabs/tab2']);
    } catch (error) {
      console.error('发布到待领取失败:', error);
    }
  }

  async clearAllDrafts() {
    try {
      const query = new CloudQuery("Drafts");
      const drafts = await query.find();
      
      for (const draft of drafts) {
        await draft.destroy();
      }
    } catch (error) {
      console.error('清空草稿失败:', error);
    }
  }
}
