import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController } from '@ionic/angular';
import { ModalController } from '@ionic/angular/standalone';
import { ChatPanelOptions, FmChatModalInput, FmodeChat, FmodeChatMessage, openChatPanelModal } from 'fmode-ng';
import Parse from "parse";
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';

interface KnowledgeItem {
  id: string;
  title: string;
  summary: string;
  image: string;
  type: 'article' | 'video';
  category: string;
  tag?: 'emergency' | 'prevention' | 'expert';
  duration?: string;
  isEmergency?: boolean;
}

interface Expert {
  id: string;
  name: string;
  avatar: string;
  specialty: string;
  isOnline: boolean;
  rating: number;
}

@Component({
  selector: 'app-tab2',
  templateUrl: './tab2.page.html',
  styleUrls: ['./tab2.page.scss'],
})
export class Tab2Page implements OnInit {
  searchQuery = '';
  isLargeFont = false;
  currentCategory = 'all';
  consultList: Array<CloudObject> = [];

  categories = [
    { id: 'all', name: '全部', icon: 'apps' },
    { id: 'wheat', name: '小麦', icon: 'leaf' },
    { id: 'rice', name: '水稻', icon: 'water' },
    { id: 'corn', name: '玉米', icon: 'ear' },
    { id: 'fruit', name: '果树', icon: 'nutrition' },
  ];

  onlineExperts: Expert[] = [
    {
      id: '1',
      name: '张农艺师',
      avatar: 'assets/images/expert1.jpg',
      specialty: '水稻种植专家',
      isOnline: true,
      rating: 4.8
    },
    {
      id: '2',
      name: '李研究员',
      avatar: 'assets/images/expert2.jpg',
      specialty: '果树病虫害防治',
      isOnline: true,
      rating: 4.9
    },
    {
      id: '3',
      name: '王技术员',
      avatar: 'assets/images/expert3.jpg',
      specialty: '土壤改良',
      isOnline: true,
      rating: 4.7
    }
  ];

  knowledgeList: KnowledgeItem[] = [
    {
      id: '1',
      title: '小麦赤霉病防治',
      summary: '识别赤霉病早期症状及防治方案',
      image: 'assets/images/wheat-disease.jpg',
      type: 'article',
      category: 'wheat',
      tag: 'emergency',
      isEmergency: true
    },
    {
      id: '2',
      title: '水稻科学灌溉技巧',
      summary: '不同生长阶段的水分管理要点',
      image: 'assets/images/rice-irrigation.jpg',
      type: 'article',
      category: 'rice',
      tag: 'expert',
      duration: '5分钟阅读'
    },
    {
      id: '3',
      title: '果树修剪实操指南',
      summary: '视频演示冬季修剪的正确方法',
      image: 'assets/images/fruit-pruning.jpg',
      type: 'video',
      category: 'fruit',
      duration: '12分钟'
    },
    {
      id: '4',
      title: '玉米螟虫预防措施',
      summary: '生物防治与化学防治结合方案',
      image: 'assets/images/corn-pest.jpg',
      type: 'article',
      category: 'corn',
      tag: 'prevention'
    },
    {
      id: '5',
      title: '土壤改良方法',
      summary: '酸性土壤改良的7种有效方式',
      image: 'assets/images/soil-improve.jpg',
      type: 'article',
      category: 'all',
      duration: '8分钟阅读'
    }
  ];

  filteredKnowledge: KnowledgeItem[] = [];
  //alertCtrl: any;

  constructor(
    private modalCtrl: ModalController,
    private alertCtrl: AlertController,
    private router: Router
  ) {}

  ngOnInit() {
    this.filteredKnowledge = [...this.knowledgeList];
    this.loadConsultList();
  }

  async clearAllChatRecords() {
    if (this.consultList.length === 0) {
      return;
    }

    const alert = await this.alertCtrl.create({
      header: '确认清空',
      message: '确定要清空所有聊天记录吗？此操作不可恢复',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确定',
          handler: async () => {
            try {
              // 创建批量删除查询
              const query = new CloudQuery("LiaoTianJiLu");
              const currentUser = new CloudUser();
              await currentUser.current();
              
              if (currentUser.id) {
                query.equalTo("userId", currentUser.id);
                
                // 先获取所有要删除的记录
                const recordsToDelete = await query.find();
                
                // 批量删除
                const deletePromises = recordsToDelete.map(record => record.destroy());
                await Promise.all(deletePromises);
                
                // 更新界面
                this.consultList = [];
              }
            } catch (error) {
              console.error('删除聊天记录失败:', error);
              // 可以添加错误提示
              const errorAlert = await this.alertCtrl.create({
                header: '操作失败',
                message: '清空聊天记录时发生错误',
                buttons: ['确定']
              });
              await errorAlert.present();
            }
          }
        }
      ]
    });

    await alert.present();
  }

  

  async loadConsultList() {
    let query = new CloudQuery("LiaoTianJiLu");
    let currentUser = new CloudUser();
    await currentUser.current();
    
    if (currentUser.id) {
      query.equalTo("userId", currentUser.id);
      query.queryParams["order"] = "-lastMessageTime";
      this.consultList = await query.find();
    }
  }

  openConsult(chatId?: string) {
    localStorage.setItem("company", "E4KpGvTEto");
    let options: ChatPanelOptions = {
      roleId: "2DXJkRsjXK",
      chatId: chatId,
      
      onChatInit: (chat: FmodeChat) => {
        chat.role.set("name", "农业专家");
        chat.role.set("title", "稻作大师");
        chat.role.set("desc", "言语朴实充满乡土智慧，擅长用农谚解释专业问题，张师傅，年龄58岁");
        chat.role.set("tags", ['育种', '节水灌溉']);
        chat.role.set("avatar", "/assets/images/expert1.jpg");
        chat.role.set("prompt", `...`); // 保持原有prompt内容
        
        let promptCates = [
          { img: "/assets/icon/yy.jpg", name: "种植" },
          { img: "/assets/icon/rl.jpg", name: "病害" },
          { img: "/assets/icon/aq.jpg", name: "水利" }
        ];
        
        setTimeout(() => {
          chat.role.set("promptCates", promptCates);
        }, 500);
        
        let promptList = [
          {
            cate: "种植", img: "/assets/icon/yy.jpg",
            messageList: [
              "如何选择适合本地气候的水稻品种？",
              "传统稻作和现代机械化种植各有什么优劣？",
              "有机水稻种植的关键技术要点有哪些？",
              "怎样判断稻田的施肥时机和用量？"
            ]
          },
          {
            cate: "病害", img: "/assets/icon/bh.jpg",
            messageList: [
              "稻瘟病的早期识别和防治方法？",
              "如何用生态方式防治稻田虫害？",
              "遇到连续阴雨天该怎么预防稻谷发霉？",
              "转基因水稻品种真的更抗病吗？"
            ]
          },
          {
            cate: "水利", img: "/assets/icon/sl.jpg",
            messageList: [
              "节水型水稻种植有哪些创新灌溉技术？",
              "盐碱地改良种植水稻的注意事项",
              "如何利用物联网技术实现智能灌溉？",
              "山区梯田的水资源管理经验分享"
            ]
          }
          // 其他提示类别...
        ];
        
        let ChatPrompt = Parse.Object.extend("ChatPrompt");
        setTimeout(() => {
          chat.promptList = promptList.map(item => {
            let prompt = new ChatPrompt();
            prompt.set(item);
            prompt.img = item.img;
            return prompt;
          });
        }, 500);
        
        chat.leftButtons = [
          {
            title: "话题灵感",
            showTitle: true,
            icon: "color-wand-outline",
            onClick: () => { chat.isPromptModalOpen = true },
            show: () => chat?.promptList?.length
          },
        ];
      },
      
      onMessage: (chat: FmodeChat, message: FmodeChatMessage) => {
        console.log("onMessage", message);
      },
      
      onChatSaved: async (chat: FmodeChat) => {
        const chatId = chat?.chatSession?.id;
        
        // 保存到 NutritionConsult 表
        let nutritionQuery = new CloudQuery("NutritionConsult");
        let nutritionConsult = await nutritionQuery.get(chatId);
        if (!nutritionConsult?.id) {
          nutritionConsult = new CloudObject("NutritionConsult");
        }
        nutritionConsult.set({
          "chatId": chatId,
          "messageList": chat.messageList,
          "name": chat.role.get("name"),
          "avatar": chat.role.get("avatar"),
        });
        await nutritionConsult.save();
        
        // 保存到 LiaoTianJiLu 表
        let chatRecordQuery = new CloudQuery("LiaoTianJiLu");
        let chatRecord = await chatRecordQuery.get(chatId);
        if (!chatRecord?.id) {
          chatRecord = new CloudObject("LiaoTianJiLu");
        }
        
        let currentUser = new CloudUser();
        await currentUser.current();
        
        chatRecord.set({
          "chatId": chatId,
          "userId": currentUser.id,
          "userName": currentUser.get("username"),
          "agentName": chat.role.get("name"),
          "avatar": chat.role.get("avatar"),
          "messages": chat.messageList,
          "lastMessage": chat.messageList[chat.messageList.length - 1]?.content,
          "lastMessageTime": new Date().toISOString(),
          "messageCount": chat.messageList.length
        });
        
        await chatRecord.save();
        this.loadConsultList();
      }
    };
    
    openChatPanelModal(this.modalCtrl, options);
  }

  async viewChatDetail(chatId: string) {
    this.openConsult(chatId);
  }

  async deleteChatRecord(chatId: string) {
    try {
      const query = new CloudQuery("LiaoTianJiLu");
      const record = await query.get(chatId);
      
      if (record) {
        await record.destroy();
        // 从本地列表中移除
        this.consultList = this.consultList.filter(
          item => item.get('chatId') !== chatId
        );
      }
    } catch (error) {
      console.error('删除单条记录失败:', error);
      const errorAlert = await this.alertCtrl.create({
        header: '操作失败',
        message: '删除聊天记录时发生错误',
        buttons: ['确定']
      });
      await errorAlert.present();
    }
  }

  toggleFontSize() {
    this.isLargeFont = !this.isLargeFont;
  }

  refreshData() {
    this.filteredKnowledge = [...this.knowledgeList];
    this.searchQuery = '';
    this.currentCategory = 'all';
  }

  resetFilters() {
    this.refreshData();
  }

  onSearch() {
    if (!this.searchQuery) {
      this.filteredKnowledge = [...this.knowledgeList];
      return;
    }

    const query = this.searchQuery.toLowerCase();
    this.filteredKnowledge = this.knowledgeList.filter(item => 
      item.title.toLowerCase().includes(query) || 
      item.summary.toLowerCase().includes(query)
    );
  }

  startVoiceSearch() {
    console.log('启动语音搜索');
  }

  filterByCategory() {
    if (this.currentCategory === 'all') {
      this.filteredKnowledge = [...this.knowledgeList];
    } else {
      this.filteredKnowledge = this.knowledgeList.filter(
        item => item.category === this.currentCategory
      );
    }
  }

  navigateToDetail(item: KnowledgeItem) {
    this.router.navigate(['/knowledge-detail', item.id]);
  }

  getTagColor(tag: string): string {
    switch (tag) {
      case 'emergency': return 'danger';
      case 'prevention': return 'warning';
      case 'expert': return 'success';
      default: return 'primary';
    }
  }

  getTagLabel(tag: string): string {
    switch (tag) {
      case 'emergency': return '紧急';
      case 'prevention': return '预防';
      case 'expert': return '专家推荐';
      default: return '';
    }
  }
}