import { Component, OnInit, Renderer2, ElementRef, Input } from '@angular/core';
import { ModalController, AnimationController, NavController } from '@ionic/angular';
import { IonicModule } from '@ionic/angular';
import { Router } from '@angular/router'; // 新增Router导入
import { ToolsModalPage } from './tools-modal.page';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { ServicesModalPage } from './services-modal.page';
import { ToastController } from '@ionic/angular';
import { SwiperOptions } from 'swiper/types';
import { CommunityActivityModal } from './community-activity.modal.page';
// 独立的语音输入模态组件
@Component({
  selector: 'app-voice-input-modal',
  template: `
    <ion-header>
      <ion-toolbar>
        <ion-title>语音输入</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="dismiss()">关闭</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <div class="voice-input-container">
        <ion-button shape="round" color="primary" size="large">
          <ion-icon name="mic" slot="start"></ion-icon>
          按住说话
        </ion-button>
        <p class="hint">请说出您的需求，例如："需要帮忙买药"</p>
      </div>
    </ion-content>
  `,
  styles: [`
    .voice-input-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 60vh;
    }
    .hint {
      margin-top: 20px;
      color: var(--ion-color-medium);
      text-align: center;
    }
  `],
  imports: [IonicModule],
  standalone: true
})
export class VoiceInputModal {
  constructor(private modalCtrl: ModalController) {}

  dismiss() {
    this.modalCtrl.dismiss();
  }
}

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: false,
})
export class Tab1Page implements OnInit {
  swiperConfig: SwiperOptions = {
    autoplay: {
      delay: 3000,
    },
    loop: true,
    pagination: {
      clickable: true,
    }
  };
  today: Date = new Date();
  // 用户数据
  currentUser: any = { name: 'hc', role: 'elderly' };
  isElderly: boolean = true;

  // 动态问候语
  greetingMessage: string = '';

  // 紧急状态
  emergencyAlert: any = null;

  // 服务九宫格
  services = [
    { id: 'tools', name: '工具借用', icon: 'construct', badge: 2, priority: 2 },
    { id: 'ai', name: 'AI管家', icon: 'headset', badge: 0, priority: 1 },
    { id: 'events', name: '社区活动', icon: 'calendar', badge: 0, priority: 3 },
    { id: 'my', name: '我的服务', icon: 'list', badge: 0, priority: 1 }
  ];

  // 互助信息流
  communityFeed = [
    {
      userName: '张阿姨',
      userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
      description: '需要帮忙修理水龙头',
      type: 'normal',
      time: new Date(),
      points: 10,
      status: 'pending'
    },
    {
      userName: '李大爷',
      userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
      description: '求购降压药',
      type: 'emergency',
      time: new Date(Date.now() - 3600000),
      points: 20,
      status: 'completed'
    }
  ];



  // 是否夜间模式
  isNightMode: boolean = true;
  Message: { name: string; ages:number;matter: string; points: number}[] = [];
  // 删除这行：toastCtrl: any;

  constructor(
    private modalCtrl: ModalController,
    private renderer: Renderer2,
    private el: ElementRef,
    private animationCtrl: AnimationController,
    private navCtrl: NavController,
    private router: Router,
    private toastCtrl: ToastController
  ) {
    this.loadMessage()
  }
  
storeList: CloudObject[]=[]
async loadMessage(){
    let query = new CloudQuery("Message");
    this.storeList = await query.find();
  }

  dismiss() {
    this.modalCtrl.dismiss();
  }

  ngOnInit() {
    this.setGreeting();
    this.checkNightMode();
    this.animateAssistant();

    // 模拟紧急警报
    setTimeout(() => {
      this.emergencyAlert = { 
        message: '暴雨红色预警！点击查看避灾物资点',
        level: 'danger'
      };
      this.pulseEmergencyBar();
    }, 3000);
  }

  // 设置动态问候语
  setGreeting() {
    const now = new Date();
    const hour = now.getHours();
    let timeGreeting = '';

    if (hour < 5) timeGreeting = '夜深了';
    else if (hour < 11) timeGreeting = '早安';
    else if (hour < 14) timeGreeting = '午安';
    else if (hour < 18) timeGreeting = '下午好';
    else timeGreeting = '晚上好';

    this.greetingMessage = `${timeGreeting}，${this.currentUser.name}！今日社区有剪纸活动（步行3分钟）`;
  }

  // 检查是否夜间模式
  checkNightMode() {
    const now = new Date();
    const hour = now.getHours();
    this.isNightMode = hour >= 22 || hour < 6;
  }

  // 紧急状态条动画
  async pulseEmergencyBar() {
    const emergencyBar = this.el.nativeElement.querySelector('.emergency-bar');
    if (emergencyBar) {
      const animation = this.animationCtrl.create()
        .addElement(emergencyBar)
        .duration(1000)
        .iterations(Infinity)
        .keyframes([
          { offset: 0, opacity: '0.7', transform: 'scale(1)' },
          { offset: 0.5, opacity: '1', transform: 'scale(1.02)' },
          { offset: 1, opacity: '0.7', transform: 'scale(1)' }
        ]);
      await animation.play();
    }
  }

  // 悬浮助手动画
  async animateAssistant() {
    const assistant = this.el.nativeElement.querySelector('.assistant-button');
    if (assistant) {
      // 呼吸动画
      const breathAnimation = this.animationCtrl.create()
        .addElement(assistant)
        .duration(3000)
        .iterations(Infinity)
        .fromTo('transform', 'translateY(0)', 'translateY(-5px)')
        .fromTo('opacity', '0.9', '1');

      await breathAnimation.play();
    }
  }

  
  // 打开语音输入模态框
  async openVoiceInput() {
    const modal = await this.modalCtrl.create({
      component: VoiceInputModal,
      cssClass: 'voice-input-modal'
    });
    return await modal.present();
  }

  // 播放子女语音消息
  playMessage(message: any) {
    message.played = true;
    console.log('播放消息:', message.text);
  }

  // 积分绽放动画
  async playPointsAnimation(event: any) {
    const card = event.target.closest('ion-item');
    if (card) {
      const animation = this.animationCtrl.create()
        .addElement(card)
        .duration(1000)
        .keyframes([
          { offset: 0, transform: 'scale(1)', opacity: '1' },
          { offset: 0.5, transform: 'scale(1.05)', opacity: '0.8' },
          { offset: 1, transform: 'scale(1)', opacity: '1' }
        ]);
      await animation.play();
    }
  }

  goDynamic(dynamic?: string) {
    this.navCtrl.navigateForward(["tab1", "dynamic"]);
  }

  // 处理服务项点击
  // 添加工具数据
  tools = [
    
  ];

  // 添加处理工具借用点击的函数
  async openToolsModal() {
// 由于找不到 ToolsModalPage，暂时注释掉 component 属性，后续需要导入对应的组件类
    const modal = await this.modalCtrl.create({
      component: ToolsModalPage,
      componentProps: {
        tools: this.tools
      }
    });
    return await modal.present();
  }

  // 修改handleServiceClick函数
  async openServicesModal() {
    const modal = await this.modalCtrl.create({
      component: ServicesModalPage
    });
    return await modal.present();
  }

  handleServiceClick(serviceId: string) {
    if (serviceId === 'tools') {
      this.openToolsModal();
    } else if (serviceId === 'my') {
      this.openServicesModal();
    } else if (serviceId === 'events') {
      this.openCommunityActivityModal();
    } else {
      switch (serviceId) {
        case 'ai':
          this.navigateToAiAgent();
          break;
        // 其他服务可补充对应逻辑
      }
    }
  }
  
  navigateToAiAgent() {
    this.router.navigate(['/ai-agent']); // 修改为实际导航到AI管家页面
  }
  
  async importMessage() {
    const MessageData = [
        {name: '张阿姨', ages: 50, matter: '修水龙头', points: 52},
        {name: '李师傅', ages: 45, matter: '家电维修', points: 30},
        {name: '王大爷', ages: 60, matter: '门窗修理', points: 25},
        {name: '赵阿姨', ages: 55, matter: '家政清洁', points: 15},
        {name: '刘师傅', ages: 48, matter: '管道疏通', points: 35},
        {name: '陈阿姨', ages: 52, matter: '老人陪护', points: 40},
        {name: '周师傅', ages: 43, matter: '电路检修', points: 30},
        {name: '吴阿姨', ages: 47, matter: '代购跑腿', points: 10},
    ];
    try {
        for (const Messages of MessageData) {
            const message = new CloudObject('Message');
            message.set(Messages);
            await message.save();
            console.log(`成功保存工具: ${Messages.name}`);
        }
        console.log('所有工具数据已成功保存到数据库');
        this.Message = [...this.Message, ...MessageData];
    } catch (error) {
        console.error('保存数据时出错:', error);
    }
  }
  
  async claimService(item: any) {
    // 1. 从Message数组中移除该项
    this.Message = this.Message.filter(msg => msg !== item);
    
    // 2. 创建新服务对象并设置状态
    const service = new CloudObject("Progressing");
    service.set({
        userName: item.name,
        userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
        description: item.matter,
        points: item.points,
        status: 'inProgress',
        time: new Date()
    });
    
    // 3. 保存到"我的服务"列表
    await service.save();
    
    // 4. 显示领取成功提示
    const toast = await this.toastCtrl.create({
      message: '领取成功，请在我的服务中查看',
      duration: 1000,
      position: 'middle'  // 添加这行使提示出现在页面中间
    });
    toast.present();
}
async openCommunityActivityModal() {
  const modal = await this.modalCtrl.create({
    component: CommunityActivityModal
  });
  return await modal.present();
}
} // 此处为 Tab1Page 类的正确闭合

// 原错误代码块已删除（错误的 @Component 装饰器及内部方法）

