import { Component, OnInit } from '@angular/core';

import { CloudObject, CloudQuery } from 'src/lib/ncloud';

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

  routes:CloudObject[]=[];
  isLoading: boolean = false;
  showCreateModal: boolean = false;
  newRouteData: any = {
    title: '',
    location: '',
    duration: '',
    description: '',
    thumbnail: '',
    birdCount: 0,
    rating: 0,
    birds: [],
    tags: []
  };

  constructor() { }

  ngOnInit() {
    this.loadRoutes();
  }
  // 显示创建表单
  showCreateForm() {
    this.showCreateModal = true;
  }

  // 关闭模态框
  closeModal() {
    this.showCreateModal = false;
    this.resetForm();
  }
  // 重置表单
  resetForm() {
    this.newRouteData = {
      title: '',
      location: '',
      duration: '',
      description: '',
      thumbnail: '',
      birdCount: 0,
      rating: 0,
      birds: [],
      tags: []
    };
  }

  // 确认创建
  async confirmCreate() {
    if (!this.newRouteData.title || !this.newRouteData.location) {
      alert('请填写标题和位置');
      return;
    }

    try {
      const newRoute = new CloudObject("Route");
      newRoute.set({
        ...this.newRouteData,
        thumbnail: this.newRouteData.thumbnail || 
                 `https://picsum.photos/600/400?random=${Math.floor(Math.random() * 1000)}`
      });
      
      await newRoute.save();
      this.closeModal();
      await this.loadRoutes();
      console.log('路线创建成功');
    } catch (error) {
      console.error('创建路线失败', error);
      alert('创建路线失败，请重试');
    }
  }

  // 删除路线
  async deleteRoute(route: CloudObject) {
    if (!confirm('确定要删除这条路线吗？')) {
      return;
    }

    try {
      await route.destroy();
      this.routes = this.routes.filter(r => r.id !== route.id);
      console.log('路线删除成功');
    } catch (error) {
      console.error('删除路线失败', error);
      alert('删除路线失败，请重试');
    }
  }
  async loadRoutes() {
    this.isLoading = true;
    try {
      let query = new CloudQuery("Route");
      this.routes = await query.find();
      console.log("路线数据加载完成", this.routes);
    } catch (error) {
      console.error("加载路线数据失败", error);
    } finally {
      this.isLoading = false;
    }
  }

  getStars(rating: number): string[] {
    const fullStars = Math.floor(rating);
    const halfStar = rating % 1 >= 0.5 ? 1 : 0;
    const emptyStars = 5 - fullStars - halfStar;

    return [
      ...Array(fullStars).fill('★'),
      ...(halfStar ? ['½'] : []),
      ...Array(emptyStars).fill('☆')
    ];
  }

  async importSampleRoutes() {
    const routeDataset = [
      {
        title: "鄱阳湖冬季候鸟观赏路线",
        location: "江西九江",
        duration: "3小时",
        birdCount: 23,
        rating: 4.5,
        thumbnail: "https://picsum.photos/600/400?random=101",
        description: "冬季观赏候鸟的最佳路线，可观察到多种珍稀候鸟",
        birds: [
          { name: "白鹤", avatar: "https://picsum.photos/100/100?random=1", protectionLevel: "一级" },
          { name: "小天鹅", avatar: "https://picsum.photos/100/100?random=2" },
          { name: "东方白鹳", avatar: "https://picsum.photos/100/100?random=3", protectionLevel: "一级" }
        ],
        tags: ["冬季", "候鸟", "湿地"]
      },
      {
        title: "庐山森林鸟类观察路线",
        location: "江西九江",
        duration: "5小时",
        birdCount: 18,
        rating: 4.2,
        thumbnail: "https://picsum.photos/600/400?random=102",
        description: "穿越庐山森林，观察多种留鸟和森林鸟类",
        birds: [
          { name: "白鹇", avatar: "https://picsum.photos/100/100?random=7", protectionLevel: "二级" },
          { name: "红嘴相思鸟", avatar: "https://picsum.photos/100/100?random=8" },
          { name: "画眉", avatar: "https://picsum.photos/100/100?random=9" }
        ],
        tags: ["森林", "留鸟", "山地"]
      }
    ];

    const query = new CloudQuery("Route");

    for (const route of routeDataset) {
      try {
        // 检查是否已存在同名路线
        query.equalTo("title", route.title);
        const existing = await query.first();

        if (existing) {
          console.log(`路线"${route.title}"已存在，跳过保存`);
          continue;
        }

        // 创建新路线对象
        const newRoute = new CloudObject("Route");
        newRoute.set(route);
        
        // 保存到数据库
        await newRoute.save();
        console.log(`路线"${route.title}"保存成功`);
      } catch (error) {
        console.error(`保存路线"${route.title}"时出错`, error);
      }
    }

    console.log("所有路线数据处理完成");
    await this.loadRoutes(); // 刷新列表
  }

  async handleUploadClick() {
    const newRoute = new CloudObject("Route");
    newRoute.set({
      title: "新建路线",
      location: "未设置位置",
      duration: "0小时",
      birdCount: 0,
      rating: 0,
      thumbnail: "https://picsum.photos/600/400?random=" + Math.floor(Math.random() * 1000),
      birds: [],
      tags: []
    });
    
    try {
      await newRoute.save();
      await this.loadRoutes();
      console.log('路线已创建并保存！');
    } catch (error) {
      console.error('创建路线失败', error);
    }
  }
}
