import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/NFC/home_nfc_detail_page.dart';
import 'package:qhd_prevention/pages/home/NFC/nfc_check_danger_detail.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';

/// OptionData 模型
class OptionData {
  final String value;
  final String label;
  final IconData icon;
  final Color color;

  const OptionData({
    required this.value,
    required this.label,
    required this.icon,
    required this.color,
  });

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is OptionData &&
              runtimeType == other.runtimeType &&
              value == other.value &&
              label == other.label &&
              icon == other.icon &&
              color == other.color;

  @override
  int get hashCode =>
      value.hashCode ^ label.hashCode ^ icon.hashCode ^ color.hashCode;
}

class HomeNfcCheckDangerPage extends StatefulWidget {
  const HomeNfcCheckDangerPage({
    super.key,
    required this.info,
    required this.facebookImages,
    required this.isNfcError,
    required this.isEdit
  });

  final Map info;
  final List<String> facebookImages;
  // nfc异常上报
  final bool isNfcError;
  final bool isEdit;

  @override
  State<HomeNfcCheckDangerPage> createState() => _HomeNfcCheckDangerPageState();
}

class _HomeNfcCheckDangerPageState extends State<HomeNfcCheckDangerPage> {
  late Map<String, dynamic> pd = {};
  OptionData? selectType; // 初始为 null（未选择）
  late bool unchecked = true;

  final List<OptionData> _options = const [
    OptionData(
      value: "option1",
      label: "合格",
      icon: Icons.check_circle_rounded,
      color: Colors.green,
    ),
    OptionData(
      value: "option2",
      label: "不合格",
      icon: Icons.check_circle_rounded,
      color: Colors.green,
    ),
    OptionData(
      value: "option3",
      label: "不涉及",
      icon: Icons.check_circle_rounded,
      color: Colors.green,
    ),
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    unchecked = widget.info['INSPECTED_FLAG'] == '0';
    if (!unchecked) { // 已经巡检过
      for (OptionData data in _options) {
        if (data.label == widget.info['INSPECTION_RESULT']) {
          selectType = data;
        }
      }
    }
    if (selectType != null && selectType?.label == '不合格') { // 不合格的话要获取上传过的隐患记录
      _getCheckRecord();
    }

  }
  Future<void> _getCheckRecord() async{
    Map data = {'PATROL_RECORD_DETAIL_ID': widget.info['PATROL_RECORD_DETAIL_ID']};
    final result = await ApiService.nfcDangerRecord(data);
    if (result['result'] == 'success') {
      setState(() {
        pd = result['pd'];
        List hImgs = result['hImgs'];
        List gzImageList = result['rImgs'];
        List<nfcImgData> imgs = [];
        List<nfcImgData> videos = [];
        if (hImgs.isNotEmpty) {
          for (Map item in hImgs) {
            String path = item['FILEPATH'];
            if (path.contains('.mp4')) {
              videos.add(nfcImgData(path: '${ApiService.baseImgPath}$path', id: item['IMGFILES_ID']));
            }else{
              imgs.add(nfcImgData(path: '${ApiService.baseImgPath}$path', id: item['IMGFILES_ID']));
            }
          }
          pd['imgList'] = imgs;
          pd['videoList'] = videos;
        }
        if (gzImageList.isNotEmpty) {
          List<nfcImgData> zgImgs = [];
          for (Map item in gzImageList) {
            String path = item['FILEPATH'];
            zgImgs.add(nfcImgData(path: '${ApiService.baseImgPath}$path', id: item['IMGFILES_ID']));
          }
          pd['gzImageList'] = zgImgs;
        }
      });
    }

  }
  Future<void> _submit() async {
    // 如果未选择任何选项就不提交
    if (selectType == null) {
      // 可选：提示用户选择
      ToastUtil.showNormal(context, '请先选择检查结果');
      return;
    }
    Map data = {
      ...widget.info,
      ...pd,
      'INSPECTION_RESULT': selectType?.label ?? '',
      'TYPE': '0', // 记录类型(0-正常检查记录 1-超期未检查记录)
    };
    LoadingDialogHelper.show();


    data['CHECK_CONTENT'] = widget.info['INSPECTION_CONTENT'];
    final result = await ApiService.nfcChekSubmit(data);
    if (result['result'] == 'success') {
      Map p = result['pd'];
      String HIDDEN_ID = p['HIDDEN_ID'] ?? '';
      // 如果选中的是不合格,需要上传相关图片和视频
      if (selectType?.label == '不合格') {
        List<nfcImgData> imgList = pd['imgList'] ?? [];
        List<nfcImgData> _videos = pd['videoList'] ?? [];
        List<nfcImgData> zgImgList = pd['gzImageList'] ?? [];
        for (int i = 0; i < imgList.length; i++) {
          nfcImgData data = imgList[i];
          if (data.id.isEmpty) {
            await _reloadFeedBack(imgList[i].path, '3', HIDDEN_ID);
          }
        }
        for (int i = 0; i < _videos.length; i++) {
          nfcImgData data = _videos[i];
          if (data.id.isEmpty) {
            await _reloadFeedBack(_videos[i].path, '3', HIDDEN_ID);
          }
        }
        for (int i = 0; i < zgImgList.length; i++) {
          nfcImgData data = zgImgList[i];
          if (data.id.isEmpty) {
            await _reloadFeedBack(zgImgList[i].path, '4', HIDDEN_ID);
          }
        }
      }
      if (widget.isNfcError) { // 如果手动检查上传nfc异常，多退一个路由
        if (widget.facebookImages.isNotEmpty) {
          // 手动上报 nfc 异常图片（按顺序上传）
          final List<String> uploaded = [];
          for (int i = 0; i < widget.facebookImages.length; i++) {
            String imagePath = await _reloadFeedBack(widget.facebookImages[i], '30', widget.info['EQUIPMENT_PIPELINE_ID']);
            if (imagePath.isNotEmpty) {
              uploaded.add(imagePath);
            }
          }
          if (uploaded.isNotEmpty) {
            data['PHOTO_URL'] = uploaded.join(',');
          }
        }
        Navigator.of(context).pop();

      }
      LoadingDialogHelper.hide();
      ToastUtil.showSuccess(context, '提交成功');
      Navigator.of(context).pop();

    } else {
      // 可选：根据返回显示错误
      ToastUtil.showNormal(context, result['result']?.toString() ?? '提交失败');
    }
  }

  Future<String> _reloadFeedBack(String imagePath, String type, String FOREIGN_KEY) async {
    try {
      Map data = {
        'TYPE': type,
        'FOREIGN_KEY': FOREIGN_KEY,
      };
      final raw = await ApiService.addNFCImgFiles(imagePath, data);
      if (raw['result'] == 'success') {
        Map pd = raw['pd'];
        return pd['FILEPATH'] ?? "";
      } else {
        return "";
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      debugPrint('加载首页数据失败：$e');
      return "";
    }
  }

  void _pushDangerDetail() async {
    // pushPage 可能返回 pd，保持原逻辑：等待详情页返回新的 pd
    final result = await pushPage<Map<String, dynamic>>(
      NfcCheckDangerDetail(info: pd, unchecked: unchecked, isEdit: widget.isEdit),
      context,
    );
    if (result != null && result.isNotEmpty) {
      setState(() {
        // 将选中项设置为“不合格”
        selectType = _options[1];
        pd = result;
      });
    }
  }

  Widget _pendingTopCard(Map item) {
    return SizedBox(
      height: 180,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.asset(
              'assets/images/xj_top.png',
              height: 70,
              width: double.infinity,
              fit: BoxFit.cover,
            ),
          ),

          // 标题 & 状态标签
          Positioned(
            top: 12,
            left: 12,
            child: Text(
              item['TASK_NAME']?.toString() ?? '',
              style: const TextStyle(
                color: Colors.black87,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Positioned(
            top: 12,
            right: 12,
            child: Container(
              height: 30,
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.7),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Center(
                child: Text(
                  item['PATROL_TYPE_NAME'] ?? '',
                  style: const TextStyle(color: Colors.white, fontSize: 14),
                ),
              ),
            ),
          ),

          // 白色信息区域（盖住图片部分）
          Positioned(
            left: 0,
            right: 0,
            top: 50, // 盖住图片底部
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 0),
              padding: const EdgeInsets.all(5),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: const [
                  BoxShadow(
                    color: Colors.black12,
                    blurRadius: 4,
                    offset: Offset(0, 1),
                  ),
                ],
              ),
              child: _buildInfoGrid(item),
            ),
          ),
        ],
      ),
    );
  }

  // 构建单选按钮（现在 option 为 OptionData）
  Widget _buildOptionButton({
    required BuildContext context,
    required OptionData option,
    required double screenWidth,
    required dynamic item,
    VoidCallback? onImageTap,
  }) {
    final String value = option.value;
    final String label = option.label;
    final icon = option.icon;
    final color = option.color;
    final bool isSelected = selectType?.value == option.value;
    final buttonWidth = (screenWidth - 60) / 3 - 10; // 计算按钮宽度

    return GestureDetector(
      onTap: () {
        setState(() {
          if (widget.isEdit) {
            if (value != "option2") {
              selectType = option;
            } else {
              // 选择“不合格”需要进入详情页面
              _pushDangerDetail();
            }
          }else { // 查看状态只有不合格可点击
            if (value == "option2") {
              _pushDangerDetail();
            }
          }
        });
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: buttonWidth,
        padding: const EdgeInsets.symmetric(vertical: 12),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            IntrinsicWidth(
              child: Row(
                children: [
                  Icon(icon, color: isSelected ? color : Colors.grey, size: 25),
                  const SizedBox(width: 2),
                  Flexible(
                    child: Row(
                      children: [
                        Text(
                          label,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight:
                            isSelected ? FontWeight.bold : FontWeight.normal,
                            color: isSelected ? color : Colors.grey[600],
                          ),
                        ),
                        if (label == '不合格' && !unchecked)
                          Column(
                            children: [Icon(Icons.edit_note, color: Colors.red, size: 20,), const SizedBox(height: 10,)],
                          )

                      ],
                    )
                  ),
                ],
              ),
            ),
            const SizedBox(width: 6),
            if ((value == "option1" && item["REFERENCE_BASIS"] == "option1") ||
                (value == "option2" &&
                    item["REFERENCE_BASIS"] == "option2" &&
                    item.containsKey("ids") &&
                    item["ids"].toString().isNotEmpty))
              GestureDetector(
                onTap: () {
                  if (onImageTap != null) {
                    onImageTap();
                  }
                },
                behavior: HitTestBehavior.opaque,
                child: Transform.translate(
                  offset: const Offset(0, -6),
                  child: Image.asset(
                    "assets/images/gantan-blue.png",
                    width: 15,
                    height: 15,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建信息网格
  Widget _buildInfoGrid(Map item) {
    final screenWidth = MediaQuery.of(context).size.width;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ItemListWidget.singleLineTitleText(
          label: '检查项：',
          isEditable: false,
          text: item['EQUIPMENT_NAME'] ?? '',
        ),
        ItemListWidget.singleLineTitleText(
          label: '检查内容：',
          isEditable: false,
          text: item['INSPECTION_CONTENT'] ?? '',
        ),
        const SizedBox(height: 8),
        // 单选按钮组
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: _options.map((option) {
            return _buildOptionButton(
              context: context,
              option: option,
              screenWidth: screenWidth,
              item: item,
              onImageTap: () {
              },
            );
          }).toList(),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final bool canSubmit = selectType != null; // 只有选中后才可以提交

    return Scaffold(
      appBar: MyAppbar(title: '检查项'),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _pendingTopCard(widget.info),
              const Spacer(),
              if (widget.isEdit)
              CustomButton(
                enabled: canSubmit,
                text: '提交',
                backgroundColor: Colors.blue,
                onPressed: canSubmit ? _submit : null,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
