import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.dart';
import 'package:qhd_prevention/customWidget/bottom_picker_two.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/date_picker_dialog.dart';
import 'package:qhd_prevention/customWidget/department_person_picker.dart';
import 'package:qhd_prevention/customWidget/department_picker.dart';
import 'package:qhd_prevention/customWidget/department_picker_hidden_type.dart';
import 'package:qhd_prevention/customWidget/department_picker_two.dart';
import 'package:qhd_prevention/customWidget/full_screen_video_page.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.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 'package:qhd_prevention/tools/tools.dart';
import '../../../customWidget/photo_picker_row.dart';
import '../../../http/ApiService.dart';

class nfcImgData {
  final String path;
  final String id;

  const nfcImgData({
    required this.path,
    required this.id,
  });


}

class NfcCheckDangerDetail extends StatefulWidget {
  const NfcCheckDangerDetail({super.key, required this.info, required this.unchecked, required this.isEdit});
  final bool unchecked;
  final Map<String, dynamic> info;
  final bool isEdit;

  @override
  State<NfcCheckDangerDetail> createState() => _NfcCheckDangerDetailState();
}

class _NfcCheckDangerDetailState extends State<NfcCheckDangerDetail> {
  late Map<String, dynamic> pd = {};

  //隐患级别
  late List<dynamic> _hazardLeveLlist = [];
  late List<dynamic> _hiddenTypeList = [];
  late bool _isDanger = false; //true 1 false 2

  // 存储各单位的人员列表
  Map<String, dynamic> _personCache = {};

  // 隐患图片
  late List<nfcImgData> imgList = [];
  late List<nfcImgData> _videos = [];

  // 整改图片
  late List<nfcImgData> zgImgList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    pd = widget.info;
    if (pd.isNotEmpty) {
      imgList = pd['imgList'] ?? [];
      _videos = pd['videoList'] ?? [];
      zgImgList = pd['gzImageList'] ?? [];
      _isDanger = pd['RECTIFICATIONTYPE'] == '1';
    }
    _getHazardLevel();
  }

  Future<void> _getHazardLevel() async {
    final resultLevel = await ApiService.getHiddenLevelsListTwo();
    List<dynamic> levelList = resultLevel['list'] as List;
    String parentId = '';
    for (var item in levelList) {
      if ((item['BIANMA'] as String).contains(
        SessionService.instance.loginUser?["PROVINCE"] ?? '',
      )) {
        parentId = item['DICTIONARIES_ID'];
        break;
      }
    }
    final result = await ApiService.getHiddenTypeList(parentId);
    final nodes = result['zTreeNodes'] as String;
    SessionService.instance.departmentHiddenTypeJsonStr = nodes;
    setState(() {
      _hiddenTypeList = json.decode(nodes) as List;
    });

    try {
      final result = await ApiService.getHazardLevel();
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['list'] ?? [];
        setState(() {
          _hazardLeveLlist = newList;
        });
      }
    } catch (e) {
      print('Error fetching data: $e');
    }
  }
  String _getIDForPath(String path, List<nfcImgData> imgList) {
    for (nfcImgData data in imgList) {
      if (data.path == path) {
        return data.id;
      }
    }
    return '';
  }
  nfcImgData _getImageDataForPath(String path, List<nfcImgData> list) {
    for (nfcImgData data in list) {
      if (data.path == path) {
        return data;
      }
    }
    return nfcImgData(path: '', id: '');
  }
  Future<void> _pickHazardType() async {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPickerHiddenType(
            onSelected: (result) {
              try {
                final Map m = Map.from(result);
                final ids = List<String>.from(m['id'] ?? []);
                final names = List<String>.from(m['name'] ?? []);
                setState(() {
                  pd['HIDDENTYPE'] = ids;
                  pd['HIDDENTYPE_NAME'] = names.join('/');
                });
                FocusHelper.clearFocus(context);
              } catch (_) {}
            },
          ),
    );
  }

  Future<void> chooseDangerLevel() async {
    FocusScope.of(context).unfocus();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      Map _hazardLeve = {};
      String choice = await BottomPickerTwo.show<String>(
        context,
        items: _hazardLeveLlist,
        itemBuilder: (item) => Text(item["NAME"], textAlign: TextAlign.center),
        initialIndex: 0,
      );
      if (choice != null) {
        for (int i = 0; i < _hazardLeveLlist.length; i++) {
          if (choice == _hazardLeveLlist[i]["NAME"]) {
            _hazardLeve = _hazardLeveLlist[i];
          }
        }
        setState(() {
          pd['HIDDENLEVELNAME'] = _hazardLeve["NAME"];
          pd['HIDDENLEVEL'] = _hazardLeve["BIANMA"];
        });
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "隐患登记"),
      body: Column(
        children: [
          // 详情滚动区域
          _pageDetail(),
        ],
      ),
    );
  }

  /// 弹出单位选择
  void chooseUnitHandle(String typeStr) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPicker(
            onSelected: (id, name) async {
              setState(() {
                pd['RECTIFICATIONDEPT'] = id;
                pd['RECTIFICATIONDEPTNAME'] = name;
              });
              FocusHelper.clearFocus(context);
              _getPersonListForUnitId(typeStr);
            },
          ),
    ).then((_) {});
  }

  Future<void> _getPersonListForUnitId(String typeStr) async {
    String unitId = pd['RECTIFICATIONDEPT'] ?? '';
    // 拉取该单位的人员列表并缓存
    final result = await ApiService.getListTreePersonList(unitId);
    setState(() {
      _personCache[typeStr] = List<Map<String, dynamic>>.from(
        result['userList'] as List,
      );
    });
    FocusHelper.clearFocus(context);
  }

  /// 弹出人员选择，需先选择单位
  void choosePersonHandle(String typeStr) async {
    final personList = _personCache[typeStr];
    if (!FormUtils.hasValue(_personCache, typeStr)) {
      ToastUtil.showNormal(context, '请先选择单位');
      return;
    }

    DepartmentPersonPicker.show(
      context,
      personsData: personList!,
      onSelectedWithIndex: (userId, name, index) {
        setState(() {
          pd['RECTIFICATIONOR'] = userId;
          pd['RECTIFICATIONORNAME'] = name;
        });
        FocusHelper.clearFocus(context);
      },
    ).then((_) {});
  }

  Widget _buildSectionContainer({required Widget child}) {
    return Container(
      margin: const EdgeInsets.only(top: 10),
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: child,
    );
  }

  Widget _pageDetail() {
    return Expanded(
      child: SingleChildScrollView(
        padding: const EdgeInsets.only(bottom: 20),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 8),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              ItemListWidget.itemContainer(
                horizontal: 5,
                Column(
                  children: [
                    RepairedPhotoSection(
                      title: "隐患照片",
                      maxCount: 4,
                      initialMediaPaths: imgList.map((item) => item.path).toList(),
                      mediaType: MediaType.image,
                      isEdit: widget.isEdit,
                      isShowAI: true,
                      onMediaAdded: (localPath) {
                        imgList.add(nfcImgData(path: localPath, id: ''));
                      },
                      onMediaRemoved: (localPath) async {
                        if (localPath.startsWith('http')) {
                           final result = await _removeFileWithType('img', _getIDForPath(localPath, imgList));
                           if (result) {
                             setState(() {
                               imgList.remove(_getImageDataForPath(localPath, imgList));
                             });
                           }
                        }else{
                          setState(() {
                            imgList.remove(_getImageDataForPath(localPath, imgList));
                          });
                        }
                      },
                      onMediaTapped: (path) {
                        presentOpaque(SingleImageViewer(imageUrl: path), context);
                      },
                      onChanged: (v) {},
                      onAiIdentify: () {
                        // AI 识别逻辑
                        if (imgList.isEmpty) {
                          ToastUtil.showNormal(context, "请先上传一张图片");
                          return;
                        }
                        if (imgList.length > 1) {
                          ToastUtil.showNormal(context, "识别暂时只能上传一张图片");
                          return;
                        }
                        nfcImgData data = imgList.first;
                        _identifyImg(data.path);
                      },
                    ),
                    RepairedPhotoSection(
                      title: "隐患视频",
                      maxCount: 1,
                      isEdit: widget.isEdit,
                      initialMediaPaths: _videos.map((item) => item.path).toList(),
                      mediaType: MediaType.video,
                      onChanged: (v) {},
                      onMediaRemoved: (localPath) async {
                        if (localPath.startsWith('http')) {
                          final result = await _removeFileWithType('img', _getIDForPath(localPath, _videos));
                          if (result) {
                            setState(() {
                              _videos.remove(_getImageDataForPath(localPath, _videos));
                            });
                          }
                        }else{
                          setState(() {
                            _videos.remove(_getImageDataForPath(localPath, _videos));
                          });
                        }
                      },
                      onMediaTapped: (path) {
                        showDialog(
                          context: context,
                          barrierColor: Colors.black54,
                          builder: (_) => VideoPlayerPopup(videoUrl: path),
                        );                      },
                      onMediaAdded: (localPath) {
                        _videos.add(nfcImgData(path: localPath, id: ''));
                      },
                      onAiIdentify: () {},
                    ),
                  ],
                ),
              ),

              ItemListWidget.multiLineTitleTextField(
                label: '隐患描述',
                isEditable: widget.isEdit,
                isRequired: false,
                text: pd['HIDDENDESCR'] ?? '',
                hintText: '请对隐患进行详细描述（必填项）',
                onChanged: (v) {
                  setState(() {
                    pd['HIDDENDESCR'] = v;
                  });
                },
              ),
              const Divider(),

              ItemListWidget.multiLineTitleTextField(
                label: '隐患部位',
                isEditable: widget.isEdit,
                isRequired: false,
                // controller: TextEditingController(text: pd['HIDDENPART'] ?? ''),
                text: pd['HIDDENPART'] ?? '',
                hintText: '请对隐患部位进行详细描述（必填项）',
                onChanged: (v) {
                  setState(() {
                    pd['HIDDENPART'] = v;
                  });
                },
              ),
              const Divider(),

              ItemListWidget.selectableLineTitleTextRightButton(
                label: '隐患级别',
                isRequired: false,
                isEditable: widget.isEdit,
                text: pd['HIDDENLEVELNAME'] ?? '',
                onTap: chooseDangerLevel,
              ),
              const Divider(),
              ItemListWidget.selectableLineTitleTextRightButton(
                label: '隐患类型',
                isEditable: widget.isEdit,
                isRequired: false,
                text: pd['HIDDENTYPE_NAME'] ?? '',
                onTap: _pickHazardType,
              ),
              const Divider(),

              ListItemFactory.createYesNoSection(
                title: "是否立即整改",
                horizontalPadding: 0,
                verticalPadding: 0,
                text: _isDanger ? '立即整改' : '限期整改',
                isEdit: widget.isEdit,
                yesLabel: "是",
                noLabel: "否",
                groupValue: _isDanger,

                onChanged: (val) {
                  setState(() {
                    _isDanger = val;
                  });
                },
              ),
              const Divider(),
              if (_isDanger)
                Column(
                  children: [
                    ItemListWidget.multiLineTitleTextField(
                      label: '整改描述',
                      isEditable: widget.isEdit,
                      isRequired: false,
                      text: pd['RECTIFYDESCR'] ?? '',
                      hintText: '请对隐患进行详细描述（必填项）',
                      onChanged: (v) {
                        setState(() {
                          pd['RECTIFYDESCR'] = v;

                        });
                      },
                    ),
                    const Divider(),
                    RepairedPhotoSection(
                      horizontalPadding: 12,
                      title: "整改后图片",
                      maxCount: 4,
                      isEdit: widget.isEdit,
                      initialMediaPaths: zgImgList.map((item) => item.path).toList(),
                      mediaType: MediaType.image,
                      isShowAI: false,
                      onMediaTapped: (path) {
                        presentOpaque(SingleImageViewer(imageUrl: path), context);
                      },
                      onMediaAdded: (localPath) {
                        zgImgList.add(nfcImgData(path: localPath, id: ''));
                      },
                      onMediaRemoved: (localPath) async {
                        if (localPath.startsWith('http')) {
                          final result = await _removeFileWithType('img', _getIDForPath(localPath, zgImgList));
                          if (result) {
                            setState(() {
                              zgImgList.remove(_getImageDataForPath(localPath, zgImgList));
                            });
                          }
                        }else{
                          setState(() {
                            zgImgList.remove(_getImageDataForPath(localPath, zgImgList));
                          });
                        }
                      },
                      onChanged: (v) {},
                      onAiIdentify: () {},
                    ),
                  ],
                ),
              if (!_isDanger)
                Column(
                  children: [
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '整改责任部门',
                      isEditable: widget.isEdit,
                      isRequired: false,
                      text: pd['RECTIFICATIONDEPTNAME'] ?? '',
                      onTap: () {
                        chooseUnitHandle('key');
                      },
                    ),
                    const Divider(),
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '整改责任人',
                      isEditable: widget.isEdit,
                      isRequired: false,
                      text: pd['RECTIFICATIONORNAME'] ?? '',
                      onTap: () {
                        choosePersonHandle('key');
                      },
                    ),
                    const Divider(),
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '整改期限',
                      isEditable: widget.isEdit,
                      isRequired: false,
                      text: pd['RECTIFICATIONDEADLINE'] ?? '',
                      onTap: () {
                        showDialog(
                          context: context,
                          builder:
                              (_) => HDatePickerDialog(
                                initialDate: DateTime.now(),
                                onCancel: () => Navigator.of(context).pop(),
                                onConfirm: (selected) {
                                  Navigator.of(context).pop();
                                  setState(() {
                                    pd['RECTIFICATIONDEADLINE'] = DateFormat(
                                      'yyyy-MM-dd',
                                    ).format(selected);
                                  });
                                },
                              ),
                        );
                      },
                    ),
                    const Divider(),
                  ],
                ),

              SizedBox(height: 30),
              CustomButton(
                onPressed: () {
                  if (widget.isEdit) {
                    _riskListCheckAppAdd();
                  }else{
                    Navigator.pop(context, pd);
                  }
                },
                text: widget.isEdit ? "确定" : "返回",
                backgroundColor: Colors.blue,
              ),
              SizedBox(height: 30),
            ],
          ),
        ),
      ),
    );
  }
  Future<bool> _removeFileWithType(String type, String id) async{
    if (id.isEmpty) {
      return true;
    }
    final result = await ApiService.onImageRemoved(id);
    if (result['result'] == 'success') {
      return true;
    }else{
      return false;
    }
    // return
  }
  Future<void> _riskListCheckAppAdd() async {
    if (imgList.isEmpty) {
      ToastUtil.showNormal(context, '请上传隐患图片');
      return;
    }
    final textRules = <Map<String, dynamic>>[
      {'value': pd['HIDDENDESCR'] ?? '', 'message': '请填隐患描述'},
      {'value': pd['HIDDENPART'] ?? '', 'message': '请填隐患部位'},
      {'value': pd['HIDDENLEVEL'] ?? '', 'message': '请选择隐患级别'},
      {'value': pd['HIDDENTYPE_NAME'] ?? '', 'message': '请选择隐患类型'},
    ];
    for (Map rule in textRules) {
      String value = rule['value'];
      if (value.isEmpty) {
        ToastUtil.showNormal(context, rule['message']);
        return;
      }
    }
    if (_isDanger) {
      if (!FormUtils.hasValue(pd, 'RECTIFYDESCR')) {
        ToastUtil.showNormal(context, '请填整改描述');
        return;
      }
      if (zgImgList.length == 0) {
        ToastUtil.showNormal(context, '请上传整改后图片');
        return;
      }
    } else {
      if (!FormUtils.hasValue(pd, 'RECTIFICATIONDEPT')) {
        ToastUtil.showNormal(context, '请选择整改部门');
        return;
      }
      if (!FormUtils.hasValue(pd, 'RECTIFICATIONOR')) {
        ToastUtil.showNormal(context, '请选择整改人');
        return;
      }
      if (!FormUtils.hasValue(pd, 'RECTIFICATIONDEADLINE')) {
        ToastUtil.showNormal(context, '请选择整改期限');
        return;
      }
    }

    final HIDDENTYPE = pd['HIDDENTYPE'];
    if (HIDDENTYPE is List) {
      pd['HIDDENTYPE1'] = HIDDENTYPE.length > 0 ? HIDDENTYPE[0] : "";
      pd['HIDDENTYPE2'] = HIDDENTYPE.length > 1 ? HIDDENTYPE[1] : "";
      pd['HIDDENTYPE3'] = HIDDENTYPE.length > 2 ? HIDDENTYPE[2] : "";
    }
    pd['CREATOR'] = SessionService.instance.loginUserId;
    pd['SOURCE'] = '6';
    pd['RECTIFICATIONTYPE'] = _isDanger ? '1' : '2';
    pd['imgList'] = imgList;
    pd['videoList'] = _videos;
    pd['gzImageList'] = zgImgList;

    Navigator.pop(context, pd);
  }

  Future<void> _identifyImg(String imagePath) async {
    try {
      LoadingDialogHelper.show();
      final raw = await ApiService.identifyImg(imagePath);
      if (raw['result'] == 'success') {
        final dynamic parsedRes = raw;
        final aiHiddens = parsedRes['aiHiddens'];

        String hiddenDescr = '';
        String rectificationSuggestions = '';
        String legalBasis = '';

        if (aiHiddens is List) {
          for (var item in aiHiddens) {
            dynamic obj = item;
            if (item is String) {
              try {
                obj = json.decode(item);
              } catch (e) {
                // 解析失败跳过
                continue;
              }
            }

            if (obj is Map) {
              hiddenDescr += (obj['hiddenDescr']?.toString() ?? '') + ';';
              rectificationSuggestions +=
                  (obj['rectificationSuggestions']?.toString() ?? '') + ';';
              legalBasis += (obj['legalBasis']?.toString() ?? '') + ';';
            }
          }
        }

        // 将结果赋回（如果 pd 是 Map）
        setState(() {
          pd['HIDDENDESCR'] = hiddenDescr;
          pd['LEGALBASIS'] = legalBasis;
          pd['RECTIFYDESCR'] = rectificationSuggestions;
        });
        LoadingDialogHelper.hide();
      } else {
        ToastUtil.showNormal(context, "识别失败");
        LoadingDialogHelper.hide();
        // _showMessage('反馈提交失败');
        // return "";
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载首页数据失败：$e');
      // return "";
      LoadingDialogHelper.hide();
    }
  }

  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,
    );
  }
}
