import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/check_record_page.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/quick_report_page.dart';
import 'package:qhd_prevention/pages/app/danger_wait_list_page.dart';
import 'package:qhd_prevention/pages/badge_manager.dart';
import 'package:qhd_prevention/pages/home/work/risk_list_page.dart';

import '../../tools/tools.dart';
import '../home/userInfo_page.dart';
import 'ai_alarm_page.dart';
import '../home/work/danger_page.dart';

enum AppItem {
  riskInspection,    // 隐患排查
  quickReport,       // 隐患快报
  checkRecord,       // 检查记录
  riskRecord,        // 隐患记录
  pendingRectification, // 待整改隐患
  overdueRectification, // 超期未整改
  riskAcceptance,    // 隐患验收
  acceptedRisk,      // 已验收隐患
  specialRectification, // 专项检查中的隐患整改
  specialRecord,     // 专项检查中的隐患记录
  supervisionRectification, // 监管帮扶中的隐患整改
  supervisionRecord, // 监管帮扶中的隐患记录
  aiAlarm, // 监管帮扶中的隐患记录
}

class ApplicationPage extends StatefulWidget {
  const ApplicationPage({Key? key}) : super(key: key);

  @override
  State<ApplicationPage> createState() => _ApplicationPageState();
}

class _ApplicationPageState extends State<ApplicationPage> {
  final badgeManager = BadgeManager();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    BadgeManager().addListener(_onBadgeChanged);

  }
  void _onBadgeChanged() {
    setState(() {});
  }

  // 处理项目点击事件
  void _handleItemClick(BuildContext context, AppItem item) async{
    switch (item) {
      case AppItem.quickReport:
      // 跳转到隐患快报页面
        pushPage(QuickReportPage(), context);
        break;

      case AppItem.riskInspection:
      // 跳转到隐患排查页面
        bool isRest= await _getIsRest();
        if(isRest){
          ToastUtil.showNormal(context, "您已经处于离岗状态中");
          return;
        }
        pushPage(DangerPage(1), context);
        break;
      case AppItem.checkRecord:
      // 跳转到检查记录页面
        pushPage(CheckRecordPage(1), context);
        break;
      case AppItem.specialRectification:
      // 跳转到专项检查隐患整改页面
      //Navigator.push(context, MaterialPageRoute(builder: (_) => SpecialRectificationPage()));
        break;
      case AppItem.specialRecord:
      // 跳转到专项检查隐患记录页面
      // Navigator.push(context, MaterialPageRoute(builder: (_) => SpecialRecordPage()));
        break;
      case AppItem.supervisionRectification:
      // 跳转到监管帮扶隐患整改页面
        bool isRest= await _getIsRest();
        if(isRest){
          ToastUtil.showNormal(context, "您已经处于离岗状态中");
          return;
        }
        pushPage(DangerPage(2), context);
        //Navigator.push(context, MaterialPageRoute(builder: (_) => SupervisionRectificationPage()));
        break;
      case AppItem.supervisionRecord:
      // 跳转到监管帮扶隐患记录页面
      //Navigator.push(context, MaterialPageRoute(builder: (_) => SupervisionRecordPage()));
        pushPage(CheckRecordPage(2), context);
        break;

      case AppItem.riskRecord:
      // 跳转到隐患记录页面
        pushPage(DangerWaitListPage(DangerType.ristRecord,1), context);
        break;
      case AppItem.pendingRectification:
      // 跳转到待整改隐患页面
        await pushPage(DangerWaitListPage(DangerType.wait,2), context);
        badgeManager.updateAppCount();

        break;
      case AppItem.overdueRectification:
      // 跳转到超期未整改页面
        pushPage(DangerWaitListPage(DangerType.expired,3), context);
        break;
      case AppItem.riskAcceptance:
      // 跳转到隐患验收页面
        await pushPage(DangerWaitListPage(DangerType.waitAcceptance,4), context);
        badgeManager.updateAppCount();
        break;
      case AppItem.acceptedRisk:
      // 跳转到已验收隐患页面
        pushPage(DangerWaitListPage(DangerType.acceptanced,5), context);
        break;
      case AppItem.aiAlarm:
      // ai
        pushPage(AiAlarmPage(), context);
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 使用枚举定义项目
    final List<Map<String, dynamic>> buttonInfos = [
      {
        'title': '隐患快报',
        'list': [
          {'item': AppItem.quickReport, 'icon': 'assets/icon-apps/icon-pc-1.png', 'title': '隐患快报', 'num': 0},
        ],
      },

      {
        'title': '隐患排查',
        'list': [
          {'item': AppItem.riskInspection, 'icon': 'assets/icon-apps/icon-zl-6.png', 'title': '隐患排查', 'num': 0},
          {'item': AppItem.checkRecord, 'icon': 'assets/icon-apps/icon-zl-2.png', 'title': '检查记录', 'num': 0},
        ],
      },
      {
        'title': '标准排查',
        'list': [
          {'item': AppItem.supervisionRectification, 'icon': 'assets/icon-apps/icon-zl-6.png', 'title': '标准排查', 'num': 0},
          {'item': AppItem.supervisionRecord, 'icon': 'assets/icon-apps/icon-zl-2.png', 'title': '检查记录', 'num': 0},
        ],
      },

      {
        'title': '隐患治理',
        'list': [
          {'item': AppItem.riskRecord, 'icon': 'assets/icon-apps/icon-zl-2.png', 'title': '隐患记录', 'num': 0},
          {'item': AppItem.pendingRectification, 'icon': 'assets/icon-apps/icon-zl-3.png', 'title': '待整改隐患', 'num': badgeManager.appDzgCount},
          {'item': AppItem.overdueRectification, 'icon': 'assets/icon-apps/icon-zl-4.png', 'title': '超期未整改', 'num': 0},
          {'item': AppItem.riskAcceptance, 'icon': 'assets/icon-apps/icon-yh-1.png', 'title': '隐患验收', 'num': badgeManager.appDysCount},
          {'item': AppItem.acceptedRisk, 'icon': 'assets/icon-apps/icon-zl-1.png', 'title': '已验收隐患', 'num': 0},
        ],
      },

      {
        'title': '监测预警',
        'list': [
          {'item': AppItem.aiAlarm, 'icon': 'assets/icon-apps/icon-pc-1.png', 'title': 'AI报警', 'num': 0},
        ],
      },
    ];

    return Scaffold(
      body: ListView.builder(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.all(0),
        itemCount: buttonInfos.length + 1,
        itemBuilder: (context, index) {
          if (index == 0) {
            return ClipRRect(
              child: Image.asset(
                'assets/images/apps-banner.png',
                fit: BoxFit.cover,
              ),
            );
          }

          final section = buttonInfos[index - 1];
          final items = section['list'] as List<dynamic>;
          return Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(10, 10, 10, 5),
                    child: Row(
                      children: [
                        Container(width: 2, height: 10, color: Colors.blue),
                        const SizedBox(width: 5),
                        Text(
                          section['title'] as String,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(10),
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        const spacing = 10.0;
                        final totalWidth = constraints.maxWidth;
                        final itemWidth = (totalWidth - spacing * 3) / 4;
                        return Wrap(
                          spacing: spacing,
                          runSpacing: spacing,
                          children: items.map<Widget>((item) {
                            return SizedBox(
                              width: itemWidth,
                              child: _buildItem(
                                item,
                                onTap: () => _handleItemClick(context, item['item'] as AppItem),
                              ),
                            );
                          }).toList(),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // 添加 onTap 回调参数
  Widget _buildItem(Map<String, dynamic> item, {VoidCallback? onTap}) {
    const double size = 60;
    final int badgeNum = item['num'] as int;

    return InkWell(
      onTap: onTap, // 添加点击事件
      borderRadius: BorderRadius.circular(8),
      child: SizedBox(
        width: size,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Stack(
              clipBehavior: Clip.none,
              children: [
                SizedBox(
                  width: 30,
                  height: 30,
                  child: Image.asset(item['icon'] as String, fit: BoxFit.contain),
                ),
                if (badgeNum > 0)
                  Positioned(
                    top: -5,
                    right: -10,
                    child: Container(
                      width: 16,
                      height: 16,
                      decoration: const BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.circle,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        badgeNum.toString(),
                        style: const TextStyle(color: Colors.white, fontSize: 10),
                      ),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 4),
            Text(
              item['title'] as String,
              style: const TextStyle(fontSize: 12),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> _getIsRest( )async {
    try {
      final raw = await ApiService.getIsRest();
      if (raw['result'] == 'success') {
        if(  raw['ISREST']=="1"){
          return true;
        }else{
          return false;
        }
      }else{
        return false;
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载头像数据失败：$e');
      return false;
    }
  }

}