import 'dart:async';
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:qhdkfq_regulatory_flutter/home/home_categroy_list_page.dart';
import 'package:qhdkfq_regulatory_flutter/tools/h_colors.dart';
import 'package:qhdkfq_regulatory_flutter/tools/tools.dart';

enum HomeCategroyType {
  enterpriseInfo("企业信息", ["监管划分", "信息审核", "持证人员"]), // 企业信息
  dualPrevention("双重预防", ["风险辨识管控", "隐患排查治理", "安全教育培训"]), // 双重预防
  keySafety("重点安全", ["安全生产费用", "危险作业"]), // 重点安全
  supervisionSupport("监管帮扶", ["监管帮扶管理", "监管帮扶隐患管理"]), // 监管帮扶
  specialInspection("专项检查", ["专项检查管理", "专项检查隐患管理"]), // 专项检查
  disasterReduction("防灾减灾", []), // 防灾减灾;
  supervisionRecord("帮扶记录", []); // 帮扶记录;

  final String title;
  final List<String> tabLists;
  const HomeCategroyType(this.title, this.tabLists);
}

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

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 模拟数据
  final List<Map<String, dynamic>> operations = [
    {
      'company': '通用电气-哈动力-南汽轮能源服务 (BSH) 有限公司',
      'type': '动火作业',
      'time': '2025-03-25 10:00',
    },
    {
      'company': '通用电气-哈动力-南汽轮能源服务 (秦皇岛) BRA',
      'type': '高处作业',
      'time': '2025-03-21 09:00',
    },
    {'company': '万基钢管 (秦皇岛) 有限公司', 'type': '高处作业', 'time': '2025-03-18 14:00'},
    {
      'company': '通用电气-哈动力-南汽轮能源服务 (BSH) 有限公司',
      'type': '高处作业',
      'time': '2025-03-17 11:20',
    },
    {
      'company': '通用电气-哈动力-南汽轮能源服务 (BSH) 有限公司',
      'type': '动火作业',
      'time': '2025-03-17 11:20',
    },
    {
      'company': '粤海中粤 (秦皇岛) 马口铁工业有限公司',
      'type': '受限空间作业',
      'time': '2025-03-07 09:28',
    },
    {
      'company': '粤海中粤 (秦皇岛) 马口铁工业有限公司',
      'type': '高处作业',
      'time': '2025-03-05 09:20',
    },
    {
      'company': '通用电气-哈动力-南汽轮能源服务 (BSH) 有限公司',
      'type': '动火作业',
      'time': '2025-02-26 14:40',
    },
  ];

  Future<void> _onRefresh() async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 2));
    // 刷新数据逻辑，如 fetchData()
    setState(() {
      // TODO: 更新数据源
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: h_backGroundColor(),
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),

          children: [
            _buildBgImage(),
            // _buildStatsCards(),
            // const SizedBox(height: 12),
            _buildSectionTitle('企业排查情况'),
            const SizedBox(height: 12),
            _buildInspectionTable(),
            const SizedBox(height: 24),
            _buildSectionTitle('安全作业情况'),
            const SizedBox(height: 12),
            ..._buildOperationList(),
          ],
        ),
      ),
    );
  }

  Widget _buildBgImage() {
    return Column(
      children: [
        // 背景图片
        Image.asset(
          "assets/images/banner.png",
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.cover,
          height: 200, // 设置固定高度或根据内容调整
        ),

        Transform.translate(offset: Offset(0, -40), child: _buildStatsCards()),
      ],
    );
  }

  Widget _buildStatsCards() {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: EdgeInsets.fromLTRB(12, 0, 12, 0),

      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),

      child: GridView.count(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 4,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        // childAspectRatio: 1.5,
        //     enterpriseInfo("企业信息"),     // 企业信息
        //     dualPrevention("双重预防"),     // 双重预防
        //     keySafety("重点安全"),          // 重点安全
        //     supervisionSupport("监管帮扶"), // 监管帮扶
        //     specialInspection("专项检查"),  // 专项检查
        //     disasterReduction("防灾减灾");   // 防灾减灾;
        children: [
          _buildStatCard(
            '企业信息',
            "assets/images/ico1.png",
            HomeCategroyType.enterpriseInfo,
          ),
          _buildStatCard(
            '双重预防',
            "assets/images/ico2.png",
            HomeCategroyType.dualPrevention,
          ),
          _buildStatCard(
            '重点安全',
            "assets/images/ico4.png",
            HomeCategroyType.keySafety,
          ),
          _buildStatCard(
            '监管帮扶',
            "assets/images/ico9.png",
            HomeCategroyType.supervisionSupport,
          ),
          _buildStatCard(
            '专项检查',
            "assets/images/ico8.png",
            HomeCategroyType.specialInspection,
          ),
          _buildStatCard(
            '防灾减灾',
            "assets/images/ico10.png",
            HomeCategroyType.disasterReduction,
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String title, String icon, HomeCategroyType type) {
    return GestureDetector(
      onTap: () {
        pushPage(HomeCategroyListPage(type), context);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(icon, width: 30, height: 30, fit: BoxFit.cover),
          Padding(
            padding: EdgeInsets.only(top: 5),
            child: Text(title, style: const TextStyle(fontSize: 16)),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Row(
      children: [
        Container(
          margin: EdgeInsets.fromLTRB(12, 0, 12, 0),
          width: 4,
          height: 20,
          decoration: BoxDecoration(
            color: const Color(0xFF0D47A1),
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        Text(
          title,
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }

  Widget _buildInspectionTable() {
    return Container(
      margin: EdgeInsets.fromLTRB(12, 0, 12, 0),
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Table(
        columnWidths: const {
          0: FlexColumnWidth(2),
          1: FlexColumnWidth(1),
          2: FlexColumnWidth(1),
        },
        border: TableBorder(
          horizontalInside: BorderSide(color: Colors.grey[200]!),
          verticalInside: BorderSide(color: Colors.grey[200]!),
        ),
        children: [
          TableRow(
            decoration: BoxDecoration(color: Colors.grey[50]),
            children: [
              _buildTableCell('各单位的管辖企业数', Colors.black, isHeader: true),
              _buildTableCell('已排查', Colors.black, isHeader: true),
              _buildTableCell('未排查', Colors.black, isHeader: true),
            ],
          ),
          TableRow(
            children: [
              _buildTableCell('49', Colors.blue),
              _buildTableCell('36', Colors.green),
              _buildTableCell('13', Colors.orange),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTableCell(String text, Color color, {bool isHeader = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          // color: isHeader ? const Color(0xFF333333) : const Color(0xFF666666),
          color: color,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  List<Widget> _buildOperationList() {
    return [
      Container(
        margin: EdgeInsets.fromLTRB(12, 0, 12, 0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Column(
          children: [
            for (int i = 0; i < operations.length; i++)
              _buildOperationItem(operations[i], i),
          ],
        ),
      ),
    ];
  }

  Widget _buildOperationItem(Map<String, dynamic> operation, int index) {
    return Container(
      width: MediaQuery.of(context).size.width, // 获取屏幕宽度
      decoration: BoxDecoration(
        border: Border(
          bottom:
              index < operations.length - 1
                  ? BorderSide(color: Colors.grey[200]!)
                  : BorderSide.none,
        ),
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,

        children: [
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          // children: [
          Text(
            operation['company']!,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
            // maxLines: 1,
            // overflow: TextOverflow.ellipsis,
          ),
          //   ],
          // ),
          const SizedBox(height: 8),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: _getOperationColor(operation['type']!).withOpacity(0.1),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              operation['type']!,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
                color: _getOperationColor(operation['type']!),
              ),
            ),
          ),

          const SizedBox(height: 8),
          Text(
            '作业时间: ${operation['time']}',
            style: const TextStyle(fontSize: 14, color: Color(0xFF666666)),
          ),
        ],
      ),
    );
  }

  Color _getOperationColor(String type) {
    switch (type) {
      case '动火作业':
        return Colors.red;
      case '高处作业':
        return Colors.orange;
      case '受限空间作业':
        return Colors.purple;
      default:
        return Colors.blue;
    }
  }
}
