import { Component, OnInit,Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { SwiperOptions } from 'swiper/types'; // 导入 Swiper 类型
import { ActionSheetController, Platform,  AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Share } from '@capacitor/share';
import { Browser } from '@capacitor/browser';
import { Location } from '@angular/common';

import { ModalController } from '@ionic/angular';
import { DiaryService } from '../../services/diary.service';

interface Diary {
  id: number;
  date: string;
  weekday: string;
  time: string;
  content: string;
  weather: string;
  mood: string;
}

interface LocationInfo {
  name: string;
  address: string;
  lat?: number;
  lng?: number;
}

@Component({
  selector: 'app-test-message',
  templateUrl: './test-message.page.html',
  styleUrls: ['./test-message.page.scss'],
  standalone:false,
})
export class TestMessagePage implements OnInit {
 
  message: Diary = {
    id: 1,
    date: '15',
    weekday: '周三',
    time: '14:30',
    content: '今天阳光明媚，去公园散步时看到樱花开了。粉色的花瓣随风飘落，美得像一幅画。坐在长椅上读了一会儿书，感觉心情特别平静。',
    weather: '晴',
    mood: '😊'
  }; 

  tags: string[] = ['公园', '樱花', '阅读'];
  tagColors: { [key: string]: string } = {
    '公园': 'success',
    '樱花': 'danger',
    '阅读': 'tertiary'
  };

  location: LocationInfo = {
    name: '中央公园',
    address: '北京市朝阳区朝阳公园南路1号',
    lat: 39.9334,
    lng: 116.4833
  };

  relatedDiaries: Diary[] = [
    {
      id: 2,
      date: '14',
      weekday: '周二',
      time: '21:15',
      content: '项目终于告一段落，加班到很晚但很有成就感。回家的路上买了杯热奶茶犒劳自己。',
      weather: '多云',
      mood: '😌'
    },
    {
      id: 3,
      date: '12',
      weekday: '周日',
      time: '09:45',
      content: '周末尝试做了新的菜谱 - 番茄牛腩。虽然炖的时间比预期长，但结果非常美味！',
      weather: '小雨',
      mood: '🥰'
    }
  ];

  slideOpts = {
    slidesPerView: 1.2,
    spaceBetween: 16,
    freeMode: true
  };

  isDarkMode = false;

  toastCtrl: any;
  constructor( 
    
    private route:ActivatedRoute,
    private router: Router,
    private actionSheetCtrl: ActionSheetController,
    private alertController: AlertController,
    private platform: Platform,
    private locationBack: Location,

    private diaryService: DiaryService,
    private modalCtrl: ModalController
  ) { 
    this.route.queryParams.subscribe(params=>{
     //console.log(params)
      //this.message=params
       
    //安全地从参数中提取并转换为Diary类型
    this.message = {
      id: params['id'] || 0, // 提供默认值
      date: params['date'] || new Date().toISOString(),
      weekday: params['weekday'] || '',
      time: params['time'] || '',
      content: params['content'] || '',
      weather: params['weather'] || '',
      mood: params['mood'] || 'normal'
      // 添加Diary接口定义的所有必需属性
    };
    
    //console.log('转换后的Diary对象:', this.message);
    })
  }

  ngOnInit() {
    this.checkDarkMode();
    this.loadDiaryData();
    //this.message = this.navParams.get('message');
  }

  // 在组件中
async onDelete(id: number) {
  const success = await this.diaryService.deleteDiary(id);
  if (success) {
    // 刷新列表
    this.modalCtrl.dismiss({ deleted: true });
    //this.loadDiaries();
  }
  this.locationBack.back();
}
  loadDiaries() {
    throw new Error('Method not implemented.');
  }

  loadDiaryData() {
    const navigation = this.router.getCurrentNavigation();
    if (navigation?.extras?.state) {
      this.message = navigation.extras.state['message'];
    }
  }

  checkDarkMode() {
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
    this.isDarkMode = prefersDark.matches;
    prefersDark.addListener((mediaQuery) => {
      this.isDarkMode = mediaQuery.matches;
    });
  }

  getWeatherIcon(): string {
    const weatherIcons: { [key: string]: string } = {
      '晴': 'sunny-outline',
      '多云': 'cloudy-outline',
      '雨': 'rainy-outline',
      '雪': 'snow-outline',
      '阴': 'cloud-outline'
    };
    return weatherIcons[this.message.weather] || 'partly-sunny-outline';
  }

  getWeatherColor(): string {
    const weatherColors: { [key: string]: string } = {
      '晴': 'warning',
      '多云': 'medium',
      '雨': 'primary',
      '雪': 'light',
      '阴': 'dark'
    };
    return weatherColors[this.message.weather] || 'medium';
  }

  getMoodColor(): string {
    const moodColors: { [key: string]: string } = {
      '😊': 'success',
      '😌': 'tertiary',
      '🥰': 'danger',
      '😄': 'warning',
      '😺': 'primary'
    };
    return moodColors[this.message.mood] || 'medium';
  }

  // async presentActionSheet() {
  //   const actionSheet = await this.actionSheetCtrl.create({
  //     header: '日记操作',
  //     buttons: [
  //       {
  //         text: '编辑日记',
  //         icon: 'create-outline',
  //         handler: () => {
  //           this.editDiary();
  //         }
  //       },
  //       { 
  //         text: '删除日记',
  //         icon: 'trash-outline',
  //         role: 'destructive',
  //         handler: () => {
  //           this.presentDeleteConfirm();
  //         }
  //       }, 
  //     ]
  //   });
  //   await actionSheet.present();
  // }

  // async presentDeleteConfirm() {
  //   const alert = await this.alertController.create({
  //     header: '确认删除',
  //     message: '确定要删除这篇日记吗？此操作不可撤销。',
  //     buttons: [
  //       {
  //         text: '取消',
  //         role: 'cancel'
  //       },
  //       {
  //         text: '删除',
  //         role: 'destructive',
  //         handler: () => {
  //           this.deleteDiary();
  //         }
  //       }
  //     ]
  //   });
  //   await alert.present();
  // }

  editDiary() {
    this.modalCtrl.dismiss();
    this.router.navigate(['/edit-diary'], {
      state: { diary: this.message }
    });
  }
 
  
  // async deleteDiary() {
  //   console.log('删除日记:', this.message.id);
    
  //     await this.diaryService.deleteDiary(this.message.id);
            
  // }

  // openMap() {
  //   if (this.platform.is('capacitor')) {
  //     // 使用原生地图应用
  //     Browser.open({
  //       url: `https://maps.google.com/?q=${this.location.lat},${this.location.lng}`
  //     });
  //   } else {
  //     // 网页版使用Google地图
  //     window.open(`https://maps.google.com/?q=${this.location.lat},${this.location.lng}`, '_blank');
  //   }
  // }

  openRelatedDiary(diary: Diary) {
    this.router.navigate(['/tabs/tab1/message'], {
      state: { message: diary }
    });
  }

}
