import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/big_video_viewer.dart';
import 'package:qhd_prevention/customWidget/full_screen_video_page.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/app/hidden_danger_management/danger_wait_list_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'dart:convert';
import 'package:video_player/video_player.dart';


import '../../http/ApiService.dart';



class HiddenRecordDetailPage extends StatefulWidget {
  const HiddenRecordDetailPage(this.dangerType, this.item, {Key? key}) : super(key: key);


  final DangerType dangerType;
  final item;

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

class _HiddenRecordDetailPageState extends State<HiddenRecordDetailPage> {
  late Map<String, dynamic> pd = {};
  late Map<String, dynamic> hs = {};
  List<String> files = [];
  List<String> files2 = [];
  List<String> files4 = [];
  List<String> files5 = [];
  List<dynamic> files6 = [];
  List<dynamic> videoList = [];
  List<dynamic> checkList = [];

  bool modalShow = false;
  String videoSrc = "";
  VideoPlayerController? _videoController;

  @override
  void initState() {
    super.initState();
    if("2"==widget.item['HIDDEN_RISKSTANDARD']){
      getDataTwo();
    }else {
      getData();
    }
  }

  @override
  void dispose() {
    _videoController?.dispose();
    super.dispose();
  }

  Future<void> getData() async {
    try {
      final data = await ApiService.getDangerDetail(widget.item['HIDDEN_ID']);
      if (data['result'] == 'success') {

          setState(() {
            pd = data['pd'];
            hs = data['hs'] ?? {};

            // 处理图片和视频
            for (var img in data['hImgs']) {
              if (img['FILEPATH'].toString().endsWith('.mp4')) {
                videoList.add(img);
              } else {
                files.add(img["FILEPATH"]);
              }
            }

            // List<dynamic> filesZheng = data['rImgs'] ?? [];
            for (var img in data['rImgs']) {
              files2.add(img["FILEPATH"]);
            }
            // files2=data['rImgs'] ?? [];
            // files4 = data['sImgs'] ?? [];
            for (var img in data['sImgs']) {
              files4.add(img["FILEPATH"]);
            }
            // files5 = data['pImgs'] ?? [];
            for (var img in data['pImgs']) {
              files5.add(img["FILEPATH"]);
            }
            files6 = data['yImgs'] ?? [];
            checkList = data['checkList'] ?? [];
          });
        }

    } catch (e) {
      print('Error fetching data: $e');
    }
  }

  Future<void> getDataTwo() async {
    try {
      final data = await ApiService.getDangerDetailTwo(widget.item['HIDDEN_ID']);
      if (data['result'] == 'success') {

        setState(() {
          pd = data['pd'];
          hs = data['hs'] ?? {};

          // 处理图片和视频
          for (var img in data['hImgs']) {
            if (img['FILEPATH'].toString().endsWith('.mp4')) {
              videoList.add(img);
            } else {
              files.add(img["FILEPATH"]);
            }
          }

          // List<dynamic> filesZheng = data['rImgs'] ?? [];
          for (var img in data['rImgs']) {
            files2.add(img["FILEPATH"]);
          }
          // files2=data['rImgs'] ?? [];
          // files4 = data['sImgs'] ?? [];
          for (var img in data['sImgs']) {
            files4.add(img["FILEPATH"]);
          }
          // files5 = data['pImgs'] ?? [];
          for (var img in data['pImgs']) {
            files5.add(img["FILEPATH"]);
          }
          files6 = data['yImgs'] ?? [];
          checkList = data['checkList'] ?? [];
        });
      }

    } catch (e) {
      print('Error fetching data: $e');
    }
  }



  Widget _buildInfoItem(String title, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 120,
            child: Text(
              title,
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(child: Text(value,textAlign: TextAlign.right,)), 
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: widget.dangerType.detailTitle),
      body: pd.isEmpty
          ? const Center(child: CircularProgressIndicator())
          : LayoutBuilder(
        builder: (context, constraints) {
          return SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: constraints.maxHeight,
              ),
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildInfoItem('隐患描述', pd['HIDDENDESCR'] ?? ''),

                    Divider(height: 1),
                    // 隐患来源
                    _buildInfoItem('隐患来源', _getSourceText(pd['SOURCE'])),
                    Divider(height: 1),
                    // 条件渲染部分
                    if (pd['SOURCE'] == '2') ...[
                      _buildInfoItem('风险点（单元）', pd['RISK_UNIT'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('辨识部位', pd['IDENTIFICATION'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('存在风险', pd['RISK_DESCR'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('风险分级', pd['LEVEL'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('检查内容', pd['CHECK_CONTENT'] ?? ''),
                      Divider(height: 1),
                    ],

                    _buildInfoItem('隐患部位', pd['HIDDENPART'] ?? ''),
                    Divider(height: 1),
                    _buildInfoItem('发现人', pd['CREATORNAME'] ?? ''),
                    Divider(height: 1),
                    _buildInfoItem('发现时间', pd['CREATTIME'] ?? ''),
                    Divider(height: 1),

                    if (pd['HIDDEN_CATEGORY']?.isNotEmpty == true)
                      _buildInfoItem('隐患类别', pd['HIDDEN_CATEGORY_NAME'] ?? ''),

                    _buildInfoItem('隐患类型', pd['HIDDENTYPE_NAME'] ?? ''),
                    Divider(height: 1),
                    _buildInfoItem('整改类型', _getRectificationType(pd['RECTIFICATIONTYPE'])),

                    if (pd['RECTIFICATIONTYPE'] == '2')
                      _buildInfoItem('整改期限', pd['RECTIFICATIONDEADLINE'] ?? ''),
                    Divider(height: 1),
                    // 隐患照片
                    // const Text('隐患照片', style: TextStyle(fontWeight: FontWeight.bold)),
                    // _buildImageGrid(files, onTap: (index) => _showImageGallery(files, index)),
                    ListItemFactory.createTextImageItem(
                      text: "隐患照片",
                      imageUrls: files,
                      onImageTapped: (index) {
                        presentOpaque(
                          SingleImageViewer(imageUrl:ApiService.baseImgPath + files[index]),
                          context,
                        );
                      },
                    ),


                    // 隐患视频
                    if (videoList.isNotEmpty) ...[
                      const SizedBox(height: 16),
                      const Text('隐患视频', style: TextStyle(fontWeight: FontWeight.bold)),
                      GestureDetector(
                        onTap: () {
                          showDialog(
                            context: context,
                            barrierColor: Colors.black54,
                            builder: (_) => VideoPlayerPopup(videoUrl: ApiService.baseImgPath + videoList[0]['FILEPATH']),
                          );

                          // present(
                          //   BigVideoViewer(videoUrl:ApiService.baseImgPath + videoList[0]['FILEPATH']),
                          //   context,
                          // );
                        },
                        // => _playVideo(ApiService.baseImgPath + videoList[0]['FILEPATH']),
                        child: Image.asset(
                          'assets/image/videostart.png', // 替换为你的视频占位图
                          color: Colors.blue,
                          width: 120,
                          height: 120,
                        ),
                      ),
                    ],

                    SizedBox(height: 10,),
                    // 整改信息部分
                    if (pd['STATE'] != null && int.parse(pd['STATE']) >= 2 && int.parse(pd['STATE']) <= 4) ...[
                      // const Divider(height: 10,color: Colors.grey,),
                      Row(
                                children: [
                                Container(width: 3, height: 15, color: Colors.blue),
                                const SizedBox(width: 8),
                                Text(
                                "整改信息",
                                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                                ),
                                ],
                      ),


                      // const Text('整改信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                      Divider(height: 1),
                      _buildInfoItem('整改描述', pd['RECTIFYDESCR'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('整改部门', pd['RECTIFICATIONDEPTNAME'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('整改人', pd['RECTIFICATIONORNAME'] ?? ''),
                      Divider(height: 1),
                      _buildInfoItem('整改时间', pd['RECTIFICATIONTIME'] ?? ''),
                      Divider(height: 1),
                      // const Text('整改后图片', style: TextStyle(fontWeight: FontWeight.bold)),
                      // _buildImageGrid(files2, onTap: (index) => _showImageGallery(files2, index)),
                      ListItemFactory.createTextImageItem(
                        text: "整改后图片",
                        imageUrls: files2,
                        onImageTapped: (index) {
                          presentOpaque(
                            SingleImageViewer(imageUrl: ApiService.baseImgPath +files2[index]),
                            context,
                          );
                        },
                      ),


                      Divider(height: 1),
                      _buildInfoItem('整改方案', pd['HAVESCHEME']=="1" ? '有':'无'),
                      Divider(height: 1),
                      if(pd['HAVESCHEME']=="1")
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _buildInfoItem('排查日期', hs['SCREENINGDATE'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('隐患清单', hs['LISTNAME'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('治理标准要求', hs['GOVERNSTANDARDS'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('治理方法', hs['GOVERNMETHOD'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('经费和物资的落实', hs['EXPENDITURE'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('负责治理人员', hs['PRINCIPAL'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('工时安排', hs['PROGRAMMING'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('时限要求', hs['TIMELIMITFOR'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('工作要求', hs['JOBREQUIREMENT'] ?? ''),
                          Divider(height: 1),
                          _buildInfoItem('其他事项', hs['OTHERBUSINESS'] ?? ''),
                          Divider(height: 1),
                          ListItemFactory.createTextImageItem(
                            text: "方案图片",
                            imageUrls: files4,
                            onImageTapped: (index) {
                              presentOpaque(
                                SingleImageViewer(imageUrl: ApiService.baseImgPath +files2[index]),
                                context,
                              );
                            },
                          ),


                      ],
                      ),

                      Divider(height: 1),
                      _buildInfoItem('整改计划', pd['HAVEPLAN']=="1" ? '有':'无'),
                      Divider(height: 1),
                      if(pd['HAVEPLAN']=="1")
                      ListItemFactory.createTextImageItem(
                        text: "计划图片",
                        imageUrls: files2,
                        onImageTapped: (index) {
                          presentOpaque(
                            SingleImageViewer(imageUrl: ApiService.baseImgPath +files2[index]),
                            context,
                          );
                        },
                      ),

                      // ... 其他整改信息字段
                    ],

                    // 添加底部安全区域间距
                    SizedBox(height: MediaQuery.of(context).padding.bottom + 20),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }




  String _getSourceText(String? source) {
    switch (source) {
      case '1': return '隐患快报';
      case '2': return '隐患排查清单检查';
      case '3': return '标准排查清单检查';
      case '4': return '专项检查';
      case '5': return '安全检查';
      default: return '';
    }
  }

  String _getRectificationType(String? type) {
    switch (type) {
      case '1': return '立即整改';
      case '2': return '限期整改';
      default: return '';
    }
  }
}

