import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:geolocator/geolocator.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/danger_image_updata_page.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/hazard_registration_page.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';

import 'package:qhd_prevention/tools/h_colors.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';

class DangerProjectPage extends StatefulWidget {
  const DangerProjectPage(this.item, this.type, this.checkrecordId, {super.key});

  final String checkrecordId;
  final int type;
  final item;
  @override
  State<DangerProjectPage> createState() => _DangerProjectPageState();
}

class _DangerProjectPageState extends State<DangerProjectPage> {
  // 单选按钮的值
  // String? _selectedValue;

  // 单选按钮选项
  final List<Map<String, dynamic>> _options = [
    {
      "value": "option1",
      "label": "合格",
      "icon": Icons.check_circle_rounded,
      "color": Colors.green,
    },
    {
      "value": "option2",
      "label": "不合格",
      "icon": Icons.check_circle_rounded,
      "color": Colors.green,
    },
    {
      "value": "option3",
      "label": "不涉及",
      "icon": Icons.check_circle_rounded,
      "color": Colors.green,
    },
  ];

  List<dynamic> listDates = [];
  List<dynamic> listDatesSelect = [];
  String unqualifiedInspectionItemID="";
  Map<String, dynamic> nullResult={};
  List<dynamic> upDataItemList=[];

  String yinHuanText="";

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

    SessionService.instance.setUnqualifiedInspectionItemIDJson("");

    _getData();



  }

  void _getData(){
    listDates.clear();
    switch(widget.type  ){
      case 1://隐患排查
        _getInvestigationItemsYinHuan();
        break;
      case 2://标准排查
        _getInvestigationItems();
        break;

    }
  }

  Future<void> _getInvestigationItemsYinHuan( ) async {
    try {

      final result = await ApiService.getInvestigationItemsYinHuan(widget.item);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        final List<dynamic> newListTwo = result['records'] ?? [];
        setState(() {

          listDates.addAll(newList);

          if(newListTwo.isNotEmpty){
            listDatesSelect.addAll(newListTwo);
          }


          // listDatesTwo.addAll(newListTwo);option1
          for(int i=0;i<listDates.length;i++){
            if(newListTwo.isNotEmpty){
              for(int m=0;m<newListTwo.length;m++){
                if(newListTwo.isNotEmpty&&newListTwo[m]["LISTCHECKITEM_ID"]!=null){
                  if( newListTwo[m]["LISTCHECKITEM_ID"]==listDates[i]["LISTCHECKITEM_ID"]){

                    if(listDatesSelect.isNotEmpty){
                      switch(listDatesSelect[m]["ISNORMAL"] ){
                        case 0:
                          (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "option1";
                          break;
                        case 1:
                          (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "option2";
                          break;
                        case 2:
                          (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "option3";
                          break;
                      }
                    }else {
                      (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "";
                    }

                    if(listDatesSelect[m].containsKey("HIDDEN_ID")){
                      (listDates[i] as Map<String, dynamic>)["ids"] = listDatesSelect[m]["HIDDEN_ID"];
                      SessionService.instance.setUnqualifiedInspectionItemIDJson(listDatesSelect[m]["HIDDEN_ID"]);
                    }else{
                      (listDates[i] as Map<String, dynamic>)["ids"] = "";
                    }

                  }else{
                    (listDates[i] as Map<String, dynamic>)["ids"] = "";
                  }
                }else{
                  (listDates[i] as Map<String, dynamic>)["ids"] = "";
                }
              }
            }else{
              (listDates[i] as Map<String, dynamic>)["ids"] = "";
            }
          }


        });

      }else{
        ToastUtil.showNormal(context, result['msg']);
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');

    }
  }

  Future<void> _getInvestigationItems( ) async {
    try {

      final result = await ApiService.getInvestigationItems(widget.item);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        final List<dynamic> newListTwo = result['records'] ?? [];
        setState(() {
          listDates.addAll(newList);

          if(newListTwo.isNotEmpty){
            listDatesSelect.addAll(newListTwo);
          }


          for(int i=0;i<listDates.length;i++){
            if(newListTwo.isNotEmpty){
              for(int m=0;m<newListTwo.length;m++){
                if(newListTwo.isNotEmpty&&newListTwo[m]["CUSTOM_ITEM_ID"]!=null){
                  if( newListTwo[m]["CUSTOM_ITEM_ID"]==listDates[i]["CUSTOM_ITEM_ID"]){

                    if(listDatesSelect.isNotEmpty){
                      switch(listDatesSelect[m]["ISNORMAL"] ){
                        case 0:
                          (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "option1";
                          break;
                        case 1:
                          (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "option2";
                          break;
                        case 2:
                          (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "option3";
                          break;
                      }
                    }else {
                      (listDates[i] as Map<String, dynamic>)["REFERENCE_BASIS"] = "";
                    }

                    if(listDatesSelect[m].containsKey("HIDDEN_ID")){
                      (listDates[i] as Map<String, dynamic>)["ids"] = listDatesSelect[m]["HIDDEN_ID"];
                      SessionService.instance.setUnqualifiedInspectionItemIDJson(listDatesSelect[m]["HIDDEN_ID"]);
                    }else{
                      (listDates[i] as Map<String, dynamic>)["ids"] = "";
                    }

                  }else{
                    (listDates[i] as Map<String, dynamic>)["ids"] = "";
                  }
                }else{
                  (listDates[i] as Map<String, dynamic>)["ids"] = "";
                }
              }
            }else{
              (listDates[i] as Map<String, dynamic>)["ids"] = "";
            }



          }

        });

      }else{
        ToastUtil.showNormal(context, result['msg']);
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');

    }
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      backgroundColor: h_backGroundColor(),
      appBar: MyAppbar(title: "排查项"),
      body: SafeArea(
        child:Column(
          children: [
            Expanded(child:  listDates.isEmpty
                ? NoDataWidget.show()
                : ListView.separated(
              itemCount: listDates.length,
              separatorBuilder: (_, __) => const SizedBox(),
              itemBuilder: (context, index) {
                final item = listDates[index];
                return GestureDetector(
                  // onTap: () => _selectItem(item),
                  child: _itemCell(screenWidth,item),
                );
              },
            )),
            // 下一步按钮
            Container(
              margin: const EdgeInsets.only(bottom: 20),
              height: 50,
              decoration: BoxDecoration(
                color: Colors.green ,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black12,
                    blurRadius: 6,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child:
              SizedBox(
                width: screenWidth - 30,
                height: 50,
                child: TextButton(
                onPressed:  _submit,//_selectedValue != null ? _submit : null,
                child: Text(
                  "提交",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                ),
              ),
            ),

          ],
        ),

        // _itemCell(screenWidth),
      ),
    );
  }



  Widget _itemCell(final screenWidth,final item) {
    return  Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 内容卡片
          Card(
            color: Colors.white,
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if(widget.type==1)
                  Text(
                    "存在风险:${item["RISK_DESCR"]}",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[700],
                      height: 1.5,
                    ),
                  ),
                  // 问题描述
                  Text(
                    "检查内容:${item["CHECK_CONTENT"]}",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[700],
                      height: 1.5,
                    ),
                  ),
                  if(widget.type==2)
                  Text(
                    "检查标准:${item["CHECK_STANDARD"]}",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[700],
                      height: 1.5,
                    ),
                  ),

                  // 单选按钮组
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children:
                    _options.map((option) {
                      return _buildOptionButton(
                        context: context,
                        value: option['value'],
                        label: option['label'],
                        icon: option['icon'],
                        color: option['color'],
                        screenWidth: screenWidth,
                        item: item,
                        onImageTap: () {
                             if(item["REFERENCE_BASIS"]=="option1") {
                               _getAlreadyUpImages(item);
                             }else if(item["REFERENCE_BASIS"]=="option2") {
                              _goUnqualifiedPage(item);
                             }
                        },
                      );
                    }).toList(),
                  ),

                    if(item["REFERENCE_BASIS"]=="option1"&& widget.type==2)
                    Card(
                      color: const Color(0xFFF1F1F1),
                      child:   Container(
                        width: screenWidth,
                        padding: EdgeInsets.all(10),
                        child: Text(item["CHECK_QUALIFIED"],style:TextStyle(color: Colors.black,fontSize: 12)),
                    )
                  ),


                ],
              ),
            ),
          ),
          // Spacer(),

        ],
      ),
    );
  }
  Future<void> _getAlreadyUpImages(Map item) async {
    try {
      final result = await ApiService.getAlreadyUpImages(item["RECORDITEM_ID"]);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['imgs'] ?? [];
          List<PhotoItem> imgList = [];
          for (Map item in newList) {
            String id = item['IMGFILES_ID'] ?? '';
            String filePath = item['FILEPATH'] ?? '';
            imgList.add(
              PhotoItem(
                id: id, // 新图片没有ID
                filePath: ApiService.baseImgPath+filePath,
                type: "1",
              ),
            );
          }

        pushPage(DangerImageUpdataPage(item["RECORDITEM_ID"], imgList: imgList), context);

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

  // 构建单选按钮
  Widget _buildOptionButton({
    required BuildContext context,
    required String value,
    required String label,
    required IconData icon,
    required Color color,
    required double screenWidth,
    required dynamic item,
    VoidCallback? onImageTap,
  }) {
    final isSelected = item["REFERENCE_BASIS"] == value;
    final buttonWidth = (screenWidth - 60) / 3 - 10; // 计算按钮宽度

    return GestureDetector(
      onTap: () {
        setState(() {
          if(value!="option2") {
            SessionService.instance.setUnqualifiedInspectionItemIDJson("");
            // _selectedValue = value;
            item["REFERENCE_BASIS"]=value;
          }else{
            _goUnqualifiedPage(item);
            // pushPage(HazardRegistrationPage(item), context);
          }
        });
      },
      child: Container(
        width: buttonWidth,
        padding: const EdgeInsets.symmetric(vertical: 12),

        child: Expanded(child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(children: [
              Icon(icon, color: isSelected ? color : Colors.grey, size: 30),
              const SizedBox(width: 8),
              Text(
                label,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                  color: isSelected ? color : Colors.grey[600],
                ),
              ),
            ],),
            if((value=="option1"&&item["REFERENCE_BASIS"]=="option1")||
                (value=="option2"&&item["REFERENCE_BASIS"]=="option2"&&item.containsKey("ids")&&item["ids"].toString().isNotEmpty))
            // 添加图片点击处理
              GestureDetector(
                onTap: () {

                  // 防止事件冒泡到父级 GestureDetector
                  if (onImageTap != null) {
                    onImageTap();
                  }
                },
                behavior: HitTestBehavior.opaque, // 确保透明区域也能点击
                child: Transform.translate(
                  offset: Offset(0, -6), // Y轴负值向上移动
                  child: Image.asset(
                    "assets/images/gantan-blue.png",
                    width: 15,
                    height: 15,
                  ),
                ),
              ),
          ],
        )),
      ),
    );
  }


  void _goUnqualifiedPage(item) {
    // String hiddenId=SessionService.instance.unqualifiedInspectionItemID.toString();
    String hiddenId=item["ids"];
    if(hiddenId.isNotEmpty) {
      switch(widget.type  ){
        case 1://隐患排查
          _getTemporaryStorageOfHiddenYinHuan(item,hiddenId);
          break;
        case 2://标准排查
          _getTemporaryStorageOfHidden(item,hiddenId);
          break;

      }

    }else{
      pushPage(HazardRegistrationPage(
          item,nullResult,widget.type,
          onClose: (String departmentId,String yinHuanText) {
            setState(() {
              this.yinHuanText=yinHuanText;
              item["REFERENCE_BASIS"]="option2";
              // _selectedValue="option2";
              // unqualifiedInspectionItemID=departmentId;
              item["ids"]=departmentId;
            });

        },
      ), context);
    }
  }

  Future<void> _getTemporaryStorageOfHiddenYinHuan(Map item,String hiddenId) async {

    try {
      final result = await ApiService.getTemporaryStorageOfHiddenYinHuan(hiddenId);
      if (result['result'] == 'success') {
        try{
          dynamic pd=result["pd"];
          if(pd["HIDDEN_CATEGORY"]!=null){
            if(pd["HIDDEN_CATEGORY"]=='aa0b9abb642146588bc71a12272942db'){
              result["pd"]["HIDDEN_CATEGORY_NAME"]= "技术负责人登记隐患";
            }else if(pd["HIDDEN_CATEGORY"]=='355ff0ead356428fa83a01330cfe10c6'){
              result["pd"]["HIDDEN_CATEGORY_NAME"]= "主要负责人登记隐患";
            }else if(pd["HIDDEN_CATEGORY"]=='a92911891ea847cc8f4cfac2455170bd'){
              result["pd"]["HIDDEN_CATEGORY_NAME"]= "其他隐患";
            }else if(pd["HIDDEN_CATEGORY"]=='44f8ce46372d4616a654cd07f1ec9a48'){
              result["pd"]["HIDDEN_CATEGORY_NAME"]= "操作负责人登记隐患";
            }

          }
        }catch(e){
          print('数据获取失败：$e');
        }

        pushPage(HazardRegistrationPage(
          item,result,widget.type,
          onClose: (String departmentId,String yinHuanText) {
            setState(() {
              this.yinHuanText=yinHuanText;
              item["REFERENCE_BASIS"]="option2";
              // _selectedValue="option2";
              // unqualifiedInspectionItemID=departmentId;
              item["ids"]=departmentId;
            });

          },
        ), context);

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

  Future<void> _getTemporaryStorageOfHidden(Map item,String hiddenId) async {

    try {
      final result = await ApiService.getTemporaryStorageOfHidden(hiddenId);
      if (result['result'] == 'success') {

        pushPage(HazardRegistrationPage(
          item,result,widget.type,
          onClose: (String departmentId,String yinHuanText) {
            setState(() {
              this.yinHuanText=yinHuanText;
              item["REFERENCE_BASIS"]="option2";
              // _selectedValue="option2";
              // unqualifiedInspectionItemID=departmentId;
              item["ids"]=departmentId;
            });

          },
        ), context);

        // final List<dynamic> newList = result['imgs'] ?? [];
        // List<PhotoItem> imgList = [];
        // for (Map item in newList) {
        //   String id = item['IMGFILES_ID'] ?? '';
        //   String filePath = item['FILEPATH'] ?? '';
        //   imgList.add(
        //     PhotoItem(
        //       id: id, // 新图片没有ID
        //       filePath: ApiService.baseImgPath+filePath,
        //       type: "1",
        //     ),
        //   );
        // }
        // pushPage(DangerImageUpdataPage(item["RECORDITEM_ID"], imgList: imgList), context);

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



  void _submit() {
    // if (_selectedValue == null) return;
    LoadingDialogHelper.show();
    _submitInvestigationItems();
    // 这里可以添加导航到下一页的代码
    // Navigator.push(context, MaterialPageRoute(builder: (_) => NextPage()));
  }


  Future<void> _submitInvestigationItems() async {

    //获取定位
    Position position = await _determinePosition();
    String longitude=position.longitude.toString();
    String latitude=position.latitude.toString();

    upDataItemList.clear();
    bool hasNoSelectItem=false;
    String ids="";
    for(int i=0;i<listDates.length;i++){
     final item=listDates[i];
     // final itemTwo=listDatesTwo[i];
      if(item["REFERENCE_BASIS"]=="option1"){
        upDataItemList.add( {
          "CUSTOM_ITEM_ID": item["CUSTOM_ITEM_ID"],
          "LISTCHECKITEM_ID": item["LISTCHECKITEM_ID"],

          "RECORDITEM_ID": item["RECORDITEM_ID"],
          "ISNORMAL": "0",
          "CHECK_RESULT": item["CHECK_QUALIFIED"],
        });
      }else if(item["REFERENCE_BASIS"]=="option2"){
        upDataItemList.add( {
          "CUSTOM_ITEM_ID": item["CUSTOM_ITEM_ID"],
          "LISTCHECKITEM_ID": item["LISTCHECKITEM_ID"],

          "RECORDITEM_ID": item["RECORDITEM_ID"],
          "ISNORMAL": "1",
          "CHECK_RESULT":yinHuanText.isNotEmpty?yinHuanText:item["CHECK_QUALIFIED"],
        });
        // upDataItemList.add(UpDataItem.fromJson(itemTwo["CUSTOM_ITEM_ID"], itemTwo["CUSTOM_ITEM_ID"], "1",
        //     yinHuanText.isNotEmpty?yinHuanText:item["CHECK_QUALIFIED"]));
      }else if(item["REFERENCE_BASIS"]=="option3"){
        upDataItemList.add( {
          "CUSTOM_ITEM_ID": item["CUSTOM_ITEM_ID"],
          "LISTCHECKITEM_ID": item["LISTCHECKITEM_ID"],

          "RECORDITEM_ID": item["RECORDITEM_ID"],
          "ISNORMAL": "2",
          "CHECK_RESULT":"",
        });
        // upDataItemList.add(UpDataItem.fromJson(itemTwo["CUSTOM_ITEM_ID"], itemTwo["CUSTOM_ITEM_ID"], "2", ""));
      }else{
        hasNoSelectItem=true;
      }

      if(item["ids"].toString().isNotEmpty) {
        if (ids.isEmpty) {
          ids = item["ids"];
        } else {
          ids = "$ids," + item["ids"];
        }
      }

    
    }
    
    if(hasNoSelectItem){
      ToastUtil.showNormal(context, "还有位选择的排查项");
      LoadingDialogHelper.hide();
      return;
    }
    String itemsString= jsonEncode(upDataItemList);
   String CHECKRECORD_ID= widget.checkrecordId?? "";
    try {

      final Map<String, dynamic> result;
      if(widget.type==1){
           result = await ApiService.submitInvestigationItemsYinHuan(
               widget.item,longitude,latitude,itemsString,ids,CHECKRECORD_ID);
      }else{
           result = await ApiService.submitInvestigationItems(
               widget.item,longitude,latitude,itemsString,ids,CHECKRECORD_ID);
      }

      if (result['result'] == 'success') {
        setState(() {
          ToastUtil.showNormal(context, "提交成功");
          Navigator.pop(context);
          LoadingDialogHelper.hide();
        });


      } else {
        ToastUtil.showNormal(context, "加载数据失败");
        LoadingDialogHelper.hide();
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    }
  }

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // 检查定位服务是否启用
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    // 获取权限
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // 获取当前位置
    return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }

  String truncateText(String text, {int maxLength = 17}) {
    if (text.length <= maxLength) return text;
    return '${text.substring(0, maxLength)}...';
  }


}


// 模拟数据模版
class UpDataItem {
  final String CUSTOM_ITEM_ID;
  final String RECORDITEM_ID;
  final String ISNORMAL;
  final String CHECK_RESULT;

  UpDataItem(
      this.CUSTOM_ITEM_ID,
      this.RECORDITEM_ID,
      this.ISNORMAL,
      this.CHECK_RESULT,
      );

  factory UpDataItem.fromJson(
      String CUSTOM_ITEM_ID,
      String RECORDITEM_ID,
      String ISNORMAL,
      String CHECK_RESULT,
      ) {
    return UpDataItem(
      CUSTOM_ITEM_ID,  // 直接传递参数，不使用命名参数语法
      RECORDITEM_ID,
      ISNORMAL,
      CHECK_RESULT,
    );
  }
}
