/**
 * Copyright (c) 2025 TDCAT.CN
 */

import { router } from '@kit.ArkUI';
import logManager, { LogCategory, LogEventType } from '../common/logtext';
import settingsService, { SettingsModel, TextResources } from '../common/SettingsService';
import web_webview from '@ohos.web.webview';

// 摄像头接口定义
interface CameraType {
  name: string;
  url: string;
}

@Entry
@Component
struct HomePage {
  @State message: string = '智慧教室管理系统';
  @State classroomMonitorData: MonitorDataType = {
    roomId: 'A301',
    temperature: 25.5,
    humidity: 60,
    occupancy: 32,
    status: '正常'
  };
  @State comprehensiveClassData: ClassDataType = {
    classId: 'CS101',
    subjectName: '高等数学',
    teacherName: '张教授',
    duration: 95,
    studentCount: 45
  };
  
  // 摄像头URL
  @State currentCameraUrl: string = 'https://www.skylinewebcams.com/webcam/maldives/lhaviyani-atoll/kuredu/kuredu-island-resort.html';
  
  // 摄像头列表
  private cameras: Array<CameraType> = [
    { 
      name: '马尔代夫库雷都岛', 
      url: 'https://www.skylinewebcams.com/webcam/maldives/lhaviyani-atoll/kuredu/kuredu-island-resort.html' 
    },
    { 
      name: '意大利米兰大教堂', 
      url: 'https://www.skylinewebcams.com/webcam/italia/lombardia/milano/duomo-milano.html' 
    },
    { 
      name: '埃及吉萨金字塔', 
      url: 'https://www.skylinewebcams.com/webcam/egypt/cairo/cairo/pyramids-giza.html' 
    }
  ];
  
  // 从设置服务获取设置
  @State settings: SettingsModel = settingsService.getSettings();
  // 获取文本资源
  @State texts: TextResources = settingsService.getTextResources();

  //确保每次从EntryAbility传递过来的参数都能刷新到UI
  @StorageLink('userName') userName: string = AppStorage.get('userName') || '';


  aboutToAppear() {

/*    // 确保在组件出现之前从AppStorage获取最新的值
    this.userName = AppStorage.get('userName') || '';*/

    // 注册语言变化的回调
    settingsService.registerLanguageChangeCallback(() => {
      this.texts = settingsService.getTextResources();
      this.message = this.texts.title;
    });
    
    // 获取当前用户名
    this.userName = settingsService.getUserNickname() || settingsService.getCurrentAccount() || '访客';
    
    // 注册用户信息变化的回调
    settingsService.registerUserInfoChangeCallback(() => {
      this.userName = settingsService.getUserNickname() || settingsService.getCurrentAccount() || '访客';
    });
    
    // 初始化文本
    this.message = this.texts.title;

    // 注册摄像头选择事件
    this.registerCameraSelectorEvent();
  }

  // 注册摄像头选择事件
  private registerCameraSelectorEvent() {
    getContext(this).eventHub.on('showCameraSelector', () => {
      this.showCameraSelector();
    });
  }

  // 显示摄像头选择对话框
  private showCameraSelector() {
    // 创建一个CustomDialogController
    let dialogController = new CustomDialogController({
      builder: CameraDialogBuilder({
        cameras: this.cameras,
        onSelect: (url: string, name: string) => {
          this.currentCameraUrl = url;
          console.info(`选择了摄像头: ${name}`);
        }
      }),
      cancel: () => {
        console.info('取消选择摄像头');
      },
      autoCancel: true,
      alignment: DialogAlignment.Center
    });
    
    // 显示对话框
    dialogController.open();
  }

  build() {
    Column() {
      // 顶部导航栏
      Row() {
        Text(this.message).fontSize(22).fontColor(Color.White).fontWeight(FontWeight.Bold)
      }
      .width('100%')
      .backgroundColor(this.settings.themeColor)
      .height(60)
      .justifyContent(FlexAlign.Center)
      .padding({ left: 20 })

      // 跑马灯公告
      Row() {
        Image($r('app.media.notification'))
          .width(20)
          .height(20)
          .margin({ right: 8 })

        Marquee({
          start: true,
          step: 6,  // 降低步长，使滚动更慢
          loop: -1,
          fromStart: true,
          src: "欢迎【" + this.userName + "】，使用【智能教室管理系统】，本项目由【922213102班鸿蒙第一组】制作，相关服务正在完善，欢迎您的使用！！"
        })
          .width('90%')
          .height(30)
          .fontSize(14)
          .fontColor('#FF5A5A')
      }
      .width('100%')
      .padding(10)
      .backgroundColor('#FFF8F8')
      .margin({ top: 5, bottom: 5 })

      // 页面内容区
      Scroll() {
        Column() {
          // 教室监控卡片
          Card({ 
            title: this.texts.classroomMonitor, 
            data: this.classroomMonitorData,
            themeColor: this.settings.themeColor,
            cameraUrl: this.currentCameraUrl
          })
          .margin({ top: 16, bottom: 16 })


          // 综合上课数据卡片
          Card({ 
            title: this.texts.comprehensiveData, 
            data: this.comprehensiveClassData,
            themeColor: this.settings.themeColor,
            cameraUrl: this.currentCameraUrl
          })
        }
        .width('100%')
        .padding({ left: 16, right: 16 })
      }
      .layoutWeight(1)
      .scrollBar(BarState.Off)

      // 底部导航栏
      BottomNavigation({
        activePage: 'home',
        themeColor: this.settings.themeColor,
        texts: this.texts
      })
    }
    .width('100%')
    .height('100%')
  }

  // 页面生命周期方法
  onPageShow(): void {
    this.Log_Event('onPageShow');
  }

  onPageHide(): void {
    this.Log_Event('onPageHide');
  }

  onBackPress(): void {
    this.Log_Event('onBackPress');
  }

  aboutToDisappear(): void {
    this.Log_Event('aboutToDisappear');
  }

  // 日志记录方法
  public Log_Event(eventName: string): void {
    // 根据事件名称选择合适的日志事件类型
    switch (eventName) {
      case 'aboutToAppear':
        logManager.info(LogCategory.HOME, LogEventType.PAGE_APPEAR, 'HomePage');
        break;
      case 'aboutToDisappear':
        logManager.info(LogCategory.HOME, LogEventType.PAGE_DISAPPEAR, 'HomePage');
        break;
      case 'onPageShow':
        logManager.info(LogCategory.HOME, LogEventType.PAGE_SHOW, 'HomePage');
        break;
      case 'onPageHide':
        logManager.info(LogCategory.HOME, LogEventType.PAGE_HIDE, 'HomePage');
        break;
      case 'onBackPress':
        logManager.info(LogCategory.HOME, LogEventType.PAGE_BACK, 'HomePage');
        break;
      default:
        logManager.info(LogCategory.HOME, LogEventType.SYSTEM_INFO, `HomePage: ${eventName}`);
    }
  }
}

// Define proper interfaces
export interface MonitorDataType {
  roomId: string;
  temperature: number;
  humidity: number;
  occupancy: number;
  status: string;
}

export interface ClassDataType {
  classId: string;
  subjectName: string;
  teacherName: string;
  duration: number;
  studentCount: number;
}

// 卡片组件
@Component
struct Card {
  title: string = '';
  data: MonitorDataType | ClassDataType = {} as MonitorDataType;
  themeColor: string = '#409eff';
  
  // 接收摄像头URL
  @Link cameraUrl: string;
  
  build() {
    Column() {
      // 卡片标题
      Row() {
        Text(this.title)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .fontColor('#333')
      }
      .width('100%')
      .padding({ top: 8, bottom: 16 })

      // 图表内容
      if (this.isMonitorData()) {
        // 教室监控数据显示
        this.MonitorDataChart()
      } else {
        // 综合上课数据显示
        this.ClassDataChart()
      }
    }
    .width('100%')
    .backgroundColor(Color.White)
    .borderRadius(12)
    .padding(16)
    .shadow({ radius: 6, color: '#eeeeee' })
  }

  // 判断是否为监控数据类型
  private isMonitorData(): boolean {
    // 使用特有属性进行区分
    return (this.data as MonitorDataType).temperature !== undefined;
  }

  // 教室监控数据图表
  @Builder
  MonitorDataChart() {
    Column() {
      // 监控摄像头视频
      Column() {
        Web({ src: this.cameraUrl, controller: new web_webview.WebviewController() })
          .width('100%')
          .height(200)
          .zoomAccess(false)  // 禁用缩放
          .onPageBegin(() => {
            console.info('网页开始加载');
          })
          .onPageEnd(() => {
            console.info('网页加载完成');
          })
          .onErrorReceive((event) => {
            console.error('网页加载失败', event);
          })
      }
      .width('100%')
      .margin({ bottom: 10 })

      // 传感器数据展示
      Row() {
        // 温度展示
        Column() {
          Text('温度')
            .fontSize(14)
            .fontColor('#666')
          Row() {
            Text((this.data as MonitorDataType).temperature.toString())
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .fontColor(this.themeColor)
            Text('°C')
              .fontSize(14)
              .fontColor('#666')
              .margin({ left: 4 })
          }
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Center)

        // 湿度展示
        Column() {
          Text('湿度')
            .fontSize(14)
            .fontColor('#666')
          Row() {
            Text((this.data as MonitorDataType).humidity.toString())
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .fontColor(this.themeColor)
            Text('%')
              .fontSize(14)
              .fontColor('#666')
              .margin({ left: 4 })
          }
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Center)

        // 人数展示
        Column() {
          Text('人数')
            .fontSize(14)
            .fontColor('#666')
          Text((this.data as MonitorDataType).occupancy.toString())
            .fontSize(20)
            .fontWeight(FontWeight.Bold)
            .fontColor(this.themeColor)
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Center)
      }
      .width('100%')
      .margin({ bottom: 8 })

      // 状态和操作按钮
      Row() {
        // 状态展示
        Column() {
          Text('状态')
            .fontSize(14)
            .fontColor('#666')
          Text((this.data as MonitorDataType).status || '正常')
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .fontColor(this.getStatusColor((this.data as MonitorDataType).status))
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Start)

        // 切换摄像头按钮
        Button('切换摄像头', { type: ButtonType.Capsule })
          .fontSize(14)
          .height(32)
          .backgroundColor(this.themeColor)
          .onClick(() => {
            // 显示摄像头选择对话框
            this.showCameraSelector();
          })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .backgroundColor('#f5f5f5')
    .borderRadius(8)
    .width('100%')
    .padding(16)
  }
  
  // 显示摄像头选择器
  private showCameraSelector() {
    if (getContext(this) && getContext(this).eventHub) {
      // 触发自定义事件，在HomePage中处理
      getContext(this).eventHub.emit('showCameraSelector', {});
    }
  }

  // 综合上课数据图表
  @Builder
  ClassDataChart() {
    Column() {
      // 课程信息
      Row() {
        Column() {
          Text('课程')
            .fontSize(14)
            .fontColor('#666')
          Text((this.data as ClassDataType).subjectName || '未指定')
            .fontSize(18)
            .fontWeight(FontWeight.Medium)
            .fontColor('#333')
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Start)

        Column() {
          Text('教师')
            .fontSize(14)
            .fontColor('#666')
          Text((this.data as ClassDataType).teacherName || '未指定')
            .fontSize(18)
            .fontWeight(FontWeight.Medium)
            .fontColor('#333')
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Start)
      }
      .width('100%')
      .margin({ bottom: 20 })

      // 课堂数据
      Row() {
        // 课堂时长
        Column() {
          Text('时长')
            .fontSize(14)
            .fontColor('#666')
          Row() {
            Text(this.formatDuration((this.data as ClassDataType).duration))
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .fontColor(this.themeColor)
          }
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Center)

        // 学生人数
        Column() {
          Text('学生人数')
            .fontSize(14)
            .fontColor('#666')
          Row() {
            Text((this.data as ClassDataType).studentCount.toString())
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .fontColor(this.themeColor)
            Text('人')
              .fontSize(14)
              .fontColor('#666')
              .margin({ left: 4 })
          }
        }
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Center)
      }
      .width('100%')
    }
    .backgroundColor('#f5f5f5')
    .borderRadius(8)
    .width('100%')
    .padding(16)
  }

  // 获取状态对应的颜色
  private getStatusColor(status: string): string {
    switch (status) {
      case '警告':
        return '#E6A23C';
      case '危险':
        return '#F56C6C';
      case '正常':
      default:
        return '#67C23A';
    }
  }

  // 格式化时长（分钟转为小时和分钟）
  private formatDuration(minutes: number): string {
    if (!minutes) return '0分钟';
    
    if (minutes < 60) {
      return `${minutes}分钟`;
    }
    
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    
    if (remainingMinutes === 0) {
      return `${hours}小时`;
    }
    
    return `${hours}小时${remainingMinutes}分钟`;
  }
}

// 底部导航栏组件
@Component
struct BottomNavigation {
  @Prop activePage: string = 'home';
  @Prop themeColor: string;
  @Prop texts: TextResources = {} as TextResources;

  build() {
    Row() {
      // 首页按钮
      Column() {
        Image($r('app.media.home'))
          .width(24)
          .height(24)
          .fillColor(this.activePage === 'home' ? this.themeColor : '#999')
        Text(this.texts.home)
          .fontSize(12)
          .fontColor(this.activePage === 'home' ? this.themeColor : '#999')
          .margin({ top: 4 })
      }
      .layoutWeight(1)
      .onClick(() => {
        if (this.activePage !== 'home') {
          router.replaceUrl({
            url: 'pages/HomePage'
          });
        }
      })
      
      // 上课按钮
      Column() {
        Image($r('app.media.class'))
          .width(24)
          .height(24)
          .fillColor(this.activePage === 'class' ? this.themeColor : '#999')
        Text(this.texts.class)
          .fontSize(12)
          .fontColor(this.activePage === 'class' ? this.themeColor : '#999')
          .margin({ top: 4 })
      }
      .layoutWeight(1)
      .onClick(() => {
        if (this.activePage !== 'class') {
          router.replaceUrl({
            url: 'pages/ClassPage',
            params: {
              direction: 'right' // 从首页向右切换到上课页
            }
          });
        }
      })
      
      // 设置按钮
      Column() {
        Image($r('app.media.settings'))
          .width(24)
          .height(24)
          .fillColor(this.activePage === 'settings' ? this.themeColor : '#999')
        Text(this.texts.settings)
          .fontSize(12)
          .fontColor(this.activePage === 'settings' ? this.themeColor : '#999')
          .margin({ top: 4 })
      }
      .layoutWeight(1)
      .onClick(() => {
        if (this.activePage !== 'settings') {
          router.replaceUrl({
            url: 'pages/SettingsPage',
            params: {
              direction: 'right' // 从首页向右切换到设置页
            }
          });
        }
      })
    }
    .width('100%')
    .height(60)
    .backgroundColor(Color.White)
    .border({ color: '#eeeeee', width: 1, style: BorderStyle.Solid })
  }
}

// 自定义摄像头选择对话框
@CustomDialog
struct CameraDialogBuilder {
  controller: CustomDialogController;
  @Prop cameras: Array<CameraType> = [];
  @Prop onSelect: (url: string, name: string) => void = () => {};
  
  build() {
    Column() {
      Text('选择监控摄像头')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20, bottom: 16 })
      
      List() {
        ForEach(this.cameras, (camera: CameraType) => {
          ListItem() {
            Row() {
              Text(camera.name)
                .fontSize(16)
                .fontColor('#333')
              
              Blank()
              
              Button('选择')
                .fontSize(14)
                .height(32)
                .backgroundColor('#409eff')
                .onClick(() => {
                  this.onSelect(camera.url, camera.name);
                  this.controller.close();
                })
            }
            .width('100%')
            .padding(12)
            .justifyContent(FlexAlign.SpaceBetween)
          }
          .backgroundColor('#f5f5f5')
          .borderRadius(8)
          .margin({ bottom: 8 })
        })
      }
      .width('100%')
      .layoutWeight(1)
      
      Button('取消')
        .fontSize(16)
        .width('40%')
        .margin({ top: 16, bottom: 20 })
        .onClick(() => {
          this.controller.close();
        })
    }
    .width('80%')
    .backgroundColor(Color.White)
    .borderRadius(16)
    .padding(16)
  }
}

export { HomePage }