import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/big_video_viewer.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/date_picker_dialog.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'dart:convert';
import 'package:video_player/video_player.dart';

import '../../customWidget/ItemWidgetFactory.dart';
import '../../customWidget/full_screen_video_page.dart';
import '../../customWidget/single_image_viewer.dart';
import '../../customWidget/video_player_widget.dart';
import '../../http/ApiService.dart';
import '../../tools/tools.dart';
import 'danger_wait_list_page.dart';


class HiddenDangerAcceptancePage extends StatefulWidget {
  const HiddenDangerAcceptancePage(this.dangerType, this.item, {super.key,required this.onClose});

  final Function(String) onClose; // 回调函数
  final DangerType dangerType;
  final item;

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

class _HiddenDangerAcceptancePageState extends State<HiddenDangerAcceptancePage> {
  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;
  final TextEditingController miaoShuController = TextEditingController();
  // 整改后图片
  List<String> gaiHouImages = [];
  String dataTime="";

  // 是否整改
  bool _accepted = true;

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

  @override
  void dispose() {
    _videoController?.dispose();
    miaoShuController.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
          ?  Container(color: Colors.white,child: Center(child: CircularProgressIndicator(),))
          : LayoutBuilder(
        builder: (context, constraints) {
          return Container(color: Colors.white,child: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),
                    _buildInfoItem('隐患级别', pd['HIDDENLEVELNAME'] ?? ''),
                    Divider(height: 1),

                    if (pd['HIDDEN_CATEGORY']?.isNotEmpty == true)
                      Column(children: [
                        _buildInfoItem('隐患类别', pd['HIDDEN_CATEGORY_NAME'] ?? ''),
                        Divider(height: 1),
                      ],),

                    _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']=="0" ? '无':'有'),
                      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']=="0" ? '无':'有'),
                      Divider(height: 1),
                      if(pd['HAVEPLAN']=="1")
                        ListItemFactory.createTextImageItem(
                          text: "计划图片",
                          imageUrls: files2,
                          onImageTapped: (index) {
                            presentOpaque(
                              SingleImageViewer(imageUrl: ApiService.baseImgPath +files2[index]),
                              context,
                            );
                          },
                        ),


                      // 隐患整改
                      _danner_type_wait(),

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

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


  /// 隐患整改
  Widget _danner_type_wait() {
    return SizedBox(
      child: Column(
        children: [
          _getRepairState(),
          // 整改选项
          // _accepted ? _getRepairState() : _noAccepet_repair(_accepted),

          const SizedBox(height: 20),
          CustomButton(
            text: "提交",
            backgroundColor: Colors.blue,
            onPressed: () {
              // ToastUtil
              //接口请求
              // _submitToServer();

              // _accepted ? _normalRectificationSubmission() : _rectificationSubmission();
              _addHazardAcceptance();
            },
          ),
        ],
      ),
    );
  }


  Widget _getRepairState() {
    return  Column(

        children: [

          ListItemFactory.createBuildSimpleSection("隐患验收",horPadding:0),
          Divider(height: 1),

          ListItemFactory.createYesNoSection(
            horizontalPadding: 0,
            title: '是否合格',
            yesLabel: '是',
            noLabel: '否',
            groupValue: _accepted,
            onChanged: (val) {
              setState(() {
                _accepted = val;
              });
            },
          ),

          // _accepted ? _getRepairState() : _noAccepet_repair(_accepted),
          if(_accepted)
          Column(children: [
            Divider(),
            Container(
              height: 130,
              padding: EdgeInsets.only(top: 15,bottom: 15),
              child: Column(
                children: [
                  Row(
                    children: [HhTextStyleUtils.mainTitle("验收描述", fontSize: 15)],
                  ),
                  TextField(
                    controller: miaoShuController,
                    keyboardType: TextInputType.multiline,
                    maxLines: null, // 不限制行数，输入多少文字就撑开多少行
                    style: TextStyle(fontSize: 15),
                    decoration: InputDecoration(
                      hintText: '请对隐患进行详细描述（必填项）',
                      border: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            Divider(height: 1),
            GestureDetector(
              onTap: () async {

                DateTime? picked = await BottomDateTimePicker.showDate(context, allowPast: false,);
                if (picked != null) {
                  setState(() {
                    dataTime = DateFormat('yyyy-MM-dd HH:mm').format(picked);
                  });
                }

              },
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 0),
                child: ListItemFactory.createRowSpaceBetweenItem(
                  leftText: "验收日期",
                  rightText: dataTime.isEmpty?"请选择":dataTime,
                  isRight: true,
                ),
              ),
            ),
            Divider(),
            RepairedPhotoSection(
              title: "验收照片",
              maxCount: 4,
              mediaType: MediaType.image,
              onChanged: (files) {
                // 上传 files 到服务器
                gaiHouImages.clear();
                for(int i=0;i<files.length;i++){
                  gaiHouImages.add(files[i].path);
                }
              },
              onAiIdentify: () {

              },
            ),
          ],),


        ],

    );
  }

  // #region 不整改
  Widget _noAccepet_repair(bool _accept) {
    return Column(

    );
  }

  Future<void> _addHazardAcceptance() async {
    try {

      String type="1";
      String miaoshu="";
      if(_accepted){
        type="1";

         miaoshu=miaoShuController.text.trim();
        if(miaoshu.isEmpty){
          ToastUtil.showNormal(context, "请填验收描述");
          return;
        }


        if(dataTime.isEmpty){
          ToastUtil.showNormal(context, "请选择验收时间");
          return;
        }


        if(gaiHouImages.isEmpty){
          ToastUtil.showNormal(context, "请上传验收照片");
          return;
        }
      } else{
        type="0";
      }


      LoadingDialogHelper.show();

      final data = await ApiService.addHazardAcceptance( type, miaoshu, dataTime,widget.item['HIDDEN_ID'] ?? '');
      if (data['result'] == 'success') {

       String hiddenCheckId="";
       try{
         data['check']['HIDDENCHECK_ID'];
       }catch(e){
         hiddenCheckId="";
       }

        for(int i=0;i<gaiHouImages.length;i++){
          _addImgFiles(gaiHouImages[i],"5",hiddenCheckId) ;

        }
        setState(() {
          LoadingDialogHelper.hide();
          ToastUtil.showNormal(context, "提交成功");
          Navigator.of(context).pop();
          widget.onClose('关闭详情'); // 触发回调
        });

      }else{
        LoadingDialogHelper.hide();
      }

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


  Future<String> _addImgFiles(String imagePath,String type,String id) async {
    try {

      final raw = await ApiService.addImgFiles( imagePath, type, id);
      if (raw['result'] == 'success') {
        return raw['imgPath'];
      }else{
        // _showMessage('反馈提交失败');
        return "";
      }

    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载首页数据失败：$e');
      return "";
    }
  }


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

      default: return '';
    }
  }

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

