import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.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/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/department_person_picker.dart';
import 'package:qhd_prevention/customWidget/department_picker.dart';
import 'package:qhd_prevention/customWidget/dotted_border_box.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/KeyProjects/SafeCheck/custom/MultiTextFieldWithTitle.dart';
import 'package:qhd_prevention/pages/KeyProjects/SafeCheck/custom/safeCheck_table.dart';
import 'package:qhd_prevention/pages/KeyProjects/SafeCheck/custom/safe_drawer_page.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/quick_report_page.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/Start/safeCheck_drawer_page.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/dh_work_detai/hotwork_apply_detail.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

class SafecheckStartDetail extends StatefulWidget {
  const SafecheckStartDetail({
    super.key,
    required this.INSPECTION_ID,
    required this.type,
  });

  final String INSPECTION_ID;
  final String type;

  @override
  State<SafecheckStartDetail> createState() => _SafecheckStartDetailState();
}

class _SafecheckStartDetailState extends State<SafecheckStartDetail> {
  String msg = 'add';
  bool _isEdit = false; // 禁止修改
  /// 被检查单位负责人
  late List<dynamic> personList = [];

  /// 打回信息
  late List<dynamic> inspectorVerifyList = [];

  /// 检查类型
  late List<dynamic> typeList = [];

  /// 被检查单位
  late List<dynamic> toCheckUnitList = [];

  bool? chooseTitleType = null;
  late List<dynamic> inspectorList = [];

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

  // 存储多行输入的内容
  List<String> multiTexts = [];

  List<String> delInspectors = [];
  List<String> delSituations = [];
  List<String> delHiddens = [];
  List<String> delHiddenFiles = [];

  List<String> signImages = [];
  List<String> signTimes = []; // 签字时间列表
  List<Map<String, String>> rules = [
    {'name': 'INSPECTION_SUBJECT', 'message': '请选择检查题目'},
    {'name': 'INSPECTED_DEPARTMENT_ID', 'message': '请选择被检查单位'},
    {'name': 'INSPECTED_SITEUSER_ID', 'message': '请选择被检查单位现场负责人'},
    {'name': 'INSPECTION_TYPE', 'message': '请选择检查类型不能为空'},
    {'name': 'INSPECTION_PLACE', 'message': '请输入检查场所'},
    {'name': 'INSPECTION_TIME_START', 'message': '请选择检查开始时间'},
    {'name': 'INSPECTION_TIME_END', 'message': '请选择作业结束时间'},
  ];

  Map<String, dynamic> form = {
    'INSPECTION_SOURCE': '5',
    // 检查来源（4-监管端 5-企业端）
    'hiddenList': [
      {
        'ISRELEVANT': '2',
        'SOURCE': '5', // 隐患来源
        'RECTIFICATIONTYPE': '2',
      },
    ],
    'INSPECTION_STATUS': '0',

    // 状态(0.暂存 1.检查人待确认、2.被检查人待确认、3.归档 -1.检查人异议打回 -2被检查人申辩)
    'INSPECTION_USER_SIGN_TIME': '',
    'INSPECTION_USER_OPINION': '',
  };

  @override
  void initState() {
    super.initState();
    form['INSPECTION_ID'] = widget.INSPECTION_ID;
    form['hiddenList'] = [];
    if (widget.INSPECTION_ID.isNotEmpty) {
      msg = 'edit';
    } else {
      _isEdit = true;
    }
    if (widget.type == 'look') {
      _isEdit = false;
    }
    if (_isEdit) {
      inspectorList.add({
        'INSPECTION_INSPECTOR_ID': '', //检查人员主键
        'INSPECTION_DEPARTMENT_ID':
            SessionService.instance.loginUser?['DEPARTMENT_ID'] ??
            '', //检查人员部门ID
        'INSPECTION_DEPARTMENT_NAME':
            SessionService.instance.loginUser?['DEPARTMENT_NAME'] ?? '',
        'INSPECTION_USER_ID': SessionService.instance.loginUserId, //检查人员ID
        'INSPECTION_USER_INDEX': '',
        'INSPECTION_USER_NAME': SessionService.instance.username,
      });
      form['inspectorList'] = inspectorList;
      _getAllRequest();
    } else {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _getData();
      });
    }
  }

  Future<void> _getData() async {
    try {
      final result = await ApiService.getSafeCheckStartGoEdit(
        widget.INSPECTION_ID,
      );
      // 在 await 之后检查 mounted，避免页面已经被 pop 导致 setState 报错
      if (!mounted) return;
      setState(() {
        form = result['pd'] ?? {};
        inspectorList =
            FormUtils.hasValue(form, 'inspectorList')
                ? form['inspectorList']
                : [];
        inspectorVerifyList =
            FormUtils.hasValue(form, 'inspectorVerifyList')
                ? form['inspectorVerifyList']
                : [];

        if (FormUtils.hasValue(form, 'INSPECTION_STATUS') &&
            int.parse(form['INSPECTION_STATUS']) < 1 &&
            widget.type != 'look') {
          _isEdit = true;
        }
        chooseTitleType = form['INSPECTION_SUBJECT'] == '安全' ? true : false;
        _syncMultiTextsFromForm();
      });
    } catch (e, st) {
      print('加载单条数据失败: $e\n$st');
      if (mounted) {
        ToastUtil.showNormal(context, '加载数据失败：$e');
      }
    }
  }

  Future<void> _getAllRequest() async {
    try {
      final typeListData = await ApiService.getSafeCheckTypeList();
      if (!mounted) return;
      setState(() {
        typeList = jsonDecode(typeListData['zTreeNodes'] ?? '[]');
      });
    } catch (e) {
      print('加载 typeList 失败: $e');
    }
  }

  Future<void> _chooseType() async {
    final choice = await BottomPicker.show<String>(
      context,
      items: typeList.map((val) => val['name'] as String).toList(),
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: 0,
    );
    if (choice != null) {
      // 用户点击确定并选择了 choice
      setState(() {
        form['INSPECTION_TYPE_NAME'] = choice;
        final data = FormUtils.findMapForKeyValue(typeList, 'name', choice);
        form['INSPECTION_TYPE'] = data['id'];

        FocusHelper.clearFocus(context);
      });
    }
  }

  Future<void> _openDrawer(Map<String, dynamic> hiddenForm, int index) async {
    try {
      final result = await openCustomDrawer<Map>(
        context,
        SafeCheckDrawerPage(
          initialHidden: hiddenForm,
          editType:
              _isEdit
                  ? (index < 0 ? SafeCheckEditType.add : SafeCheckEditType.edit)
                  : SafeCheckEditType.see,
          toCheckUnitList: toCheckUnitList,
        ),
      );

      if (result != null && mounted) {
        setState(() {
          if (index < 0) {
            // 新增
            form['hiddenList'].add(result);
            print(form);
          } else {
            // 修改
            form['hiddenList'][index] = result;
          }
        });
      }
    } catch (e) {
      print("打开抽屉失败: $e");
      ToastUtil.showNormal(context, "打开抽屉失败");
    }
  }

  Future<T?> openCustomDrawer<T>(BuildContext context, Widget child) {
    return Navigator.of(context).push<T>(
      PageRouteBuilder(
        opaque: false,
        barrierDismissible: true,
        barrierColor: Colors.black54,
        pageBuilder: (_, __, ___) {
          return Align(
            alignment: Alignment.centerRight,
            child: FractionallySizedBox(
              widthFactor: 4 / 5,
              child: Material(color: Colors.white, child: child),
            ),
          );
        },
        transitionsBuilder: (_, anim, __, child) {
          return SlideTransition(
            position: Tween(
              begin: const Offset(1, 0),
              end: Offset.zero,
            ).animate(CurvedAnimation(parent: anim, curve: Curves.easeOut)),
            child: child,
          );
        },
      ),
    );
  }

  /// 将 form['situationList']（若存在）转换为 List<String>
  List<String> _situationListToStrings() {
    final List<dynamic> cur = List<dynamic>.from(form['situationList'] ?? []);
    if (cur.isEmpty) return ['']; // 保持至少一行，和 uni-app 行为一致
    return cur.map((e) {
      if (e is Map && e['SITUATION'] != null) return e['SITUATION'].toString();
      return '';
    }).toList();
  }

  /// 将 List<String> 转换成 situationList（保留已存在的 INSPECTION_SITUATION_ID）
  List<Map<String, dynamic>> _stringsToSituationList(List<String> texts) {
    final List<dynamic> existing = List<dynamic>.from(
      form['situationList'] ?? [],
    );
    final List<Map<String, dynamic>> out = [];

    for (int i = 0; i < texts.length; i++) {
      final s = texts[i] ?? '';
      if (i < existing.length && existing[i] is Map) {
        // 保留已有项的其他字段（如 INSPECTION_SITUATION_ID），只覆盖 SITUATION
        final Map<String, dynamic> copy = Map<String, dynamic>.from(
          existing[i],
        );
        copy['SITUATION'] = s;
        // 若没有 INSPECTION_SITUATION_ID 字段，确保它存在（保持原 uni-app 结构）
        copy['INSPECTION_SITUATION_ID'] = copy['INSPECTION_SITUATION_ID'] ?? '';
        out.add(copy);
      } else {
        // 新增项
        out.add({'INSPECTION_SITUATION_ID': '', 'SITUATION': s});
      }
    }

    // 如果用户删除了行，要把超出的 existing id 记录到 delSituations（可选）
    // 下面为示例：把被删除的旧 ID 收集到 delSituations，便于编辑时提交删除列表
    if (existing.isNotEmpty && existing.length > texts.length) {
      for (int j = texts.length; j < existing.length; j++) {
        final ex = existing[j];
        if (ex is Map) {
          final id = (ex['INSPECTION_SITUATION_ID'] ?? '').toString();
          if (id.isNotEmpty) {
            delSituations.add(id);
          }
        }
      }
    }

    return out;
  }

  /// 在加载数据之后调用：把已存在的 form['situationList'] 同步到 multiTexts（用于 MultiTextFieldWithTitle）
  void _syncMultiTextsFromForm() {
    final List<String> arr = _situationListToStrings();
    setState(() {
      multiTexts = arr;
    });
  }

  // ------------ 提交入口 ------------
  Future<void> _submit() async {
    if (!_isEdit) {
      Navigator.of(context).pop();
      return;
    }

    // 基于 rules 验证
    for (final r in rules) {
      final name = r['name'] ?? '';
      final message = r['message'] ?? '请完善表单';
      final v = form[name];
      if (v == null || v.toString().isEmpty || v.toString() == '请选择') {
        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, message);
        break;
      }
    }
    // situationList 每项 SITUATION 非空
    final situations = (form['situationList'] as List<dynamic>?) ?? [];
    for (var i = 0; i < situations.length; i++) {
      final s = Map<String, dynamic>.from(situations[i]);
      if ((s['SITUATION'] ?? '').toString().trim().isEmpty) {
        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, '请填写第${i + 1}项检查情况');
        return;
      }
    }

    // 检查 inspectorList 中是否有重复 INSPECTION_USER_ID
    final List<Map<String, dynamic>> inspectors =
        ((form['inspectorList'] as List<dynamic>?) ?? [])
            .map((e) => Map<String, dynamic>.from(e))
            .toList();
    final seenIds = <String>{};
    for (final it in inspectors) {
      final id = (it['INSPECTION_USER_ID'] ?? '').toString();
      if (id.isNotEmpty) {
        if (seenIds.contains(id)) {
          LoadingDialogHelper.hide();
          ToastUtil.showNormal(context, '检查人重复！请检查数据');
          return;
        }
        seenIds.add(id);
      } else {
        // 如果某个检查人没选 ID，也视为错误（对应 uniapp 的校验）
        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, '有检查人未选择数据，请选择');
        return;
      }
    }

    // 根据 hiddenList 构建需要上传的文件数组
    final origHiddenList = (form['hiddenList'] as List<dynamic>?) ?? [];
    final List<List<Map<String, dynamic>>> hiddenFilesPerHidden = [];

    for (var i = 0; i < origHiddenList.length; i++) {
      final hidden = Map<String, dynamic>.from(origHiddenList[i] as Map);
      final List<Map<String, dynamic>> fileList = [];

      // hiddenImgs (多张)
      final hiddenImgs = (hidden['hiddenImgs'] as List<dynamic>?) ?? [];
      for (var j = 0; j < hiddenImgs.length; j++) {
        final img = hiddenImgs[j];
        if (img is String) {
          fileList.add({'type': 3, 'FILEPATH': img});
        } else if (img is Map) {
          final hasId = (img['IMGFILES_ID'] ?? '').toString().isNotEmpty;
          if (!hasId) {
            fileList.add({
              'type': 3,
              'FILEPATH': img['FILEPATH'] ?? img['path'] ?? '',
            });
          }
        }
      }

      // zgImgs (整改图)
      final zgImgs = (hidden['zgImgs'] as List<dynamic>?) ?? [];
      for (var j = 0; j < zgImgs.length; j++) {
        final img = zgImgs[j];
        if (img is String) {
          fileList.add({'type': 4, 'FILEPATH': img});
        } else if (img is Map) {
          final hasId = (img['IMGFILES_ID'] ?? '').toString().isNotEmpty;
          if (!hasId) {
            fileList.add({
              'type': 4,
              'FILEPATH': img['FILEPATH'] ?? img['path'] ?? '',
            });
          }
        }
      }

      // hiddenVideos (只取第一个)
      final hiddenVideos = (hidden['hiddenVideos'] as List<dynamic>?) ?? [];
      if (hiddenVideos.isNotEmpty) {
        final v = hiddenVideos[0];
        if (v is String) {
          fileList.add({'type': 102, 'FILEPATH': v});
        } else if (v is Map) {
          final hasId = (v['IMGFILES_ID'] ?? '').toString().isNotEmpty;
          if (!hasId) {
            fileList.add({
              'type': 102,
              'FILEPATH': v['FILEPATH'] ?? v['path'] ?? '',
            });
          }
        }
      }

      hiddenFilesPerHidden.add(fileList);
    }

    // 确保当前登录用户在 inspectorList 中（依据 SessionService）
    final loginUser = SessionService.instance.loginUser ?? {};
    final loginUserId = SessionService.instance.loginUserId ?? '';
    final idx = inspectors.indexWhere((item) {
      return (item['INSPECTION_USER_ID'] ?? '') ==
          (loginUser['USER_ID'] ?? loginUserId);
    });
    if (idx < 0) {
      inspectors.add({
        'INSPECTION_INSPECTOR_ID': '',
        'INSPECTION_DEPARTMENT_ID': loginUser['DEPARTMENT_ID'] ?? '',
        'INSPECTION_DEPARTMENT_NAME': loginUser['DEPARTMENT_NAME'] ?? '',
        'INSPECTION_USER_ID': loginUser['USER_ID'] ?? loginUserId,
        'INSPECTION_USER_INDEX': '',
        'INSPECTION_USER_NAME': loginUser['NAME'] ?? '',
      });
    }
    printLongString(origHiddenList.toString());
    String HIDDENJSON = jsonEncode(origHiddenList);
    // 准备 form 字段（JSON 字符串等）
    form['INSPECTORJSON'] = jsonEncode(inspectors);
    form['SITUATIONJSON'] = jsonEncode(situations);
    form['HIDDENJSON'] = HIDDENJSON;
    form['delInspectors'] = delInspectors.join(',');
    form['delSituations'] = delSituations.join(',');
    form['delHiddens'] = delHiddens.join(',');
    form['delHiddenFiles'] = delHiddenFiles.join(',');
    form['CREATOR'] = loginUser['USER_ID'] ?? loginUserId;
    form['CORPINFO_ID'] = SessionService.instance.corpinfoId ?? '';
    form['ACTION_USER'] = loginUser['NAME'] ?? '';

    LoadingDialogHelper.show(); // 显示 loading

    try {
      // 若需要签字（INSPECTION_USER_OPINION）则使用 multipart 带签字提交
      final needSignature =
          (form['INSPECTION_USER_OPINION'] ?? '').toString().isNotEmpty;
      Map<String, dynamic>? res;

      if (needSignature) {
        if (signImages.isEmpty) {
          LoadingDialogHelper.hide();
          ToastUtil.showNormal(context, '您还未签字');
          return;
        }
        final signPath = signImages[0];
        // 请求接口
        res = await ApiService.SafeCheckStartGoEditMsg(signPath, msg, form);
      } else {
        // 无签字不需要带上图片
        res = await ApiService.SafeCheckStartGoEditMsg('', msg, form);
      }

      if (res != null && (res['result'] == 'success')) {
        final pd = res['pd'] ?? {};
        final List<dynamic> returnedHiddenList = pd['hiddenList'] ?? [];

        // 如果没有附件需要上传，直接完成
        final hasFiles = hiddenFilesPerHidden.any((lst) => lst.isNotEmpty);
        // 先处理 punishForm（如果每个隐患有 punishForm）
        final returnedHiddenMapList =
            returnedHiddenList
                .map((e) => Map<String, dynamic>.from(e))
                .toList();

        for (var i = 0; i < returnedHiddenMapList.length; i++) {
          if (i < origHiddenList.length) {
            final hidden = Map<String, dynamic>.from(origHiddenList[i] as Map);
            final punishForm = hidden['punishForm'];
            if (punishForm != null && punishForm is Map) {
              final hid =
                  returnedHiddenMapList[i]['HIDDEN_ID']?.toString() ?? '';
              if (hid.isNotEmpty) {
                punishForm['HIDDEN_ID'] = hid;
                try {
                  await fnSubmit(Map<String, dynamic>.from(punishForm));
                } catch (e) {
                  // 如果罚单提交失败，你可以 choose 抛出或记录后继续
                  print('罚单提交失败: $e');
                }
              }
            }
          }
        }

        if (hasFiles) {
          await uploadHiddenFiles(hiddenFilesPerHidden, returnedHiddenMapList);
        }

        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, '提交成功');
        Navigator.of(context).pop();
      } else {
        LoadingDialogHelper.hide();
        final msgErr =
            res != null
                ? (res['msg'] ?? res['msaesge'] ?? res['message'] ?? '提交失败')
                : '提交失败';
        ToastUtil.showNormal(context, msgErr.toString());
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      ToastUtil.showNormal(context, '提交异常：$e');
    } finally {}
  }

  // ---------- 上传附件 ----------
  Future<void> uploadHiddenFiles(
    List<List<Map<String, dynamic>>> hiddenFilesPerHidden,
    List<Map<String, dynamic>> returnedHiddenList,
  ) async {
    for (var i = 0; i < hiddenFilesPerHidden.length; i++) {
      final filesForHidden = hiddenFilesPerHidden[i];
      if (filesForHidden.isEmpty) continue;

      final hiddenId =
          i < returnedHiddenList.length
              ? (returnedHiddenList[i]['HIDDEN_ID']?.toString() ?? '')
              : '';
      if (hiddenId.isEmpty) continue;

      for (final f in filesForHidden) {
        final filePath = f['FILEPATH']?.toString() ?? '';
        final type = f['type']?.toString() ?? '';
        if (filePath.isEmpty) continue;

        bool uploaded = false;
        int tries = 0;
        while (!uploaded && tries < 3) {
          tries++;
          try {
            // 直接调用你提供的 addNormalImgFiles，第二个参数传 { 'TYPE': type, 'FOREIGN_KEY': hiddenId }
            final resp = await ApiService.addNormalImgFiles(filePath, {
              'TYPE': type,
              'FOREIGN_KEY': hiddenId,
            });
            if (resp != null &&
                (resp['result'] == 'success' || resp['result'] == 'ok')) {
              uploaded = true;
              // 可记录 resp 里的返回信息
            } else {
              // 失败但继续重试
              await Future.delayed(Duration(milliseconds: 500));
            }
          } catch (e) {
            print('上传文件失败 (尝试 $tries): $e -- path=$filePath');
            await Future.delayed(Duration(milliseconds: 500));
          }
        }

        if (!uploaded) {
          // 若最终仍未上传成功：记录或提示（这里打印日志）
          print('最终上传失败: $filePath -> hiddenId=$hiddenId');
          // 你也可以按需求抛出异常中止整个提交
        }
      }
    }
  }

  Future<void> _sign() async {
    await NativeOrientation.setLandscape();
    final path = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => MineSignPage()),
    );
    await NativeOrientation.setPortrait();
    if (path != null) {
      final now = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());
      setState(() {
        signImages.add(path);
        signTimes.add(now);
        FocusHelper.clearFocus(context);
      });
    }
  }

  /// 移除检查人员
  void _removeCheckPerson(int index) async {
    CustomAlertDialog.showConfirm(
      context,
      title: "提示",
      content: '确定移除检查人员吗',
      cancelText: '取消',
      confirmText: '确定',
      onConfirm: () {
        setState(() {
          inspectorList.removeAt(index);
          form['inspectorList'] = inspectorList;
        });
      },
    );
  }

  // ========== 罚单提交方法
  Future<bool> fnSubmit(Map<String, dynamic>? ordForm) async {
    if (ordForm == null) return false;

    final Map<String, String> punishRules = {
      'REASON': '请填写处罚原因',
      'AMOUT': '请填写处罚金额',
      'DATE': '请选择下发处罚时间',
    };
    // 校验
    for (final entry in punishRules.entries) {
      final key = entry.key;
      final msg = entry.value;
      final val = ordForm[key];
      if (val == null || val.toString().trim().isEmpty) {
        ToastUtil.showNormal(context, msg);
        return false;
      }
    }

    final requestData = Map<String, dynamic>.from(ordForm);
    requestData['CORPINFO_ID'] = SessionService.instance.corpinfoId ?? '';
    requestData['CREATOR'] = SessionService.instance.loginUserId ?? '';
    requestData['OPERATOR'] = SessionService.instance.loginUserId ?? '';

    try {
      LoadingDialogHelper.show();
      final res = await ApiService.safeCheckPunishSubmit(requestData);
      LoadingDialogHelper.hide();
      if (FormUtils.hasValue(res, 'result') && res['result'] == 'success') {
        return true;
      } else {
        final msg =
            res != null
                ? (res['msg'] ?? res['msaesge'] ?? res['message'] ?? '提交失败')
                : '提交失败';
        ToastUtil.showNormal(context, msg);
        return false;
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      ToastUtil.showNormal(context, '罚单提交异常：$e');
      return false;
    }
  }

  Widget _personUnitItem(Map item, int index) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.all(5),
          child: DottedBorderBox(
            child: SizedBox(
              child: Column(
                children: [
                  ItemListWidget.selectableLineTitleTextRightButton(
                    isRequired: index == 0 ? false : _isEdit,
                    label: '${index + 1}.检查人员单位：',
                    isEditable: index == 0 ? false : _isEdit,
                    onTapClean: () {
                      setState(() {});
                    },
                    text: item['INSPECTION_DEPARTMENT_NAME'] ?? '请选择',
                    onTap: () {
                      chooseUnitHandle('$index');
                    },
                  ),
                  Divider(),
                  ItemListWidget.selectableLineTitleTextRightButton(
                    isRequired: index == 0 ? false : _isEdit,
                    label: '${index + 1}.检查人员：',
                    isEditable: index == 0 ? false : _isEdit,
                    text: item['INSPECTION_USER_NAME'] ?? '请选择',
                    onTap: () {
                      choosePersonHandle('$index');
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
        if (index > 0 && _isEdit)
          Positioned(
            top: 0,
            left: 0,
            child: GestureDetector(
              onTap: () => _removeCheckPerson(index),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(12),
                ),
                padding: const EdgeInsets.all(4),
                child: const Icon(Icons.close, size: 10, color: Colors.white),
              ),
            ),
          ),
      ],
    );
    // 删除按钮（叠加在左上角）
  }

  Widget _personSignItem(Map item, int index) {
    return SizedBox(
      child: Column(
        children: [
          ItemListWidget.multiLineTitleTextField(
            label: '检查人意见:',
            isEditable: false,
            text: item['opinion'] ?? '',
          ),
          const Divider(),
          ItemListWidget.OneRowImageTitle(
            label: '检查人签字',
            text: item['time'] ?? '',
            onTapCallBack: (path) {
              presentOpaque(SingleImageViewer(imageUrl: path), context);
            },
            imgPath: item['img'] ?? '',
          ),
          const Divider(),
          Column(
            children: [
              if (form['INSPECTION_STATUS'] == '3')
                ItemListWidget.multiLineTitleTextField(
                  label: '被检查单位现场负责人意见:',
                  isEditable: false,
                  text: item['INSPECTED_EXPLAIN'] ?? '',
                ),
              if (FormUtils.hasValue(form, 'INSPECTED_EXPLAIN'))
                ItemListWidget.multiLineTitleTextField(
                  label: '申辩说明',
                  isEditable: false,
                  text: form['INSPECTED_EXPLAIN'] ?? '',
                ),
              if (form['INSPECTION_STATUS'] == '3')
                ItemListWidget.OneRowImageTitle(
                  label: '检查人签字',
                  text: form['INSPECTED_SITEUSER_SIGN_TIME'] ?? '',
                  onTapCallBack: (path) {
                    presentOpaque(SingleImageViewer(imageUrl: path), context);
                  },
                  imgPath: item['INSPECTED_SITEUSER_SIGN_IMG'] ?? '',
                ),
            ],
          ),
        ],
      ),
    );
  }

  void _delHiddenForm(Map<String, dynamic> item, int index) async {
    final ok = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '确定移除发现问题吗？',
    );
    if (ok) {
      setState(() {
        /* 删除逻辑 */
        final List<dynamic> rawHiddenList =
            (form['hiddenList'] as List<dynamic>?) ?? [];
        final List<Map<String, dynamic>> hiddenList =
            rawHiddenList
                .map((e) => Map<String, dynamic>.from(e as Map))
                .toList();
        hiddenList.removeAt(index);
        form['hiddenList'] = hiddenList;
      });
      FocusHelper.clearFocus(context);
    }
  }

  /// 弹出单位选择
  void chooseUnitHandle(String typeStr) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPicker(
            onSelected: (id, name) async {
              setState(() {
                if (typeStr == '被检查单位') {
                  form['INSPECTED_DEPARTMENT_ID'] = id;
                  form['INSPECTED_DEPARTMENT_NAME'] = name;
                } else {
                  final int index = int.parse(typeStr);
                  inspectorList[index]['INSPECTION_DEPARTMENT_NAME'] = name;
                  inspectorList[index]['INSPECTION_DEPARTMENT_ID'] = id;
                }
              });
              FocusHelper.clearFocus(context);
              _getPersonListForUnitId(typeStr);
            },
          ),
    ).then((_) {});
  }

  Future<void> _getPersonListForUnitId(String typeStr) async {
    String unitId = form['INSPECTED_DEPARTMENT_ID'] ?? '';
    if (typeStr != '被检查单位') {
      final int index = int.parse(typeStr);
      unitId = inspectorList[index]['INSPECTION_DEPARTMENT_ID'] ?? '';
    }

    // 拉取该单位的人员列表并缓存
    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(() {
          if (typeStr == '被检查单位') {
            form['INSPECTED_SITEUSER_INDEX'] = index;
            form['INSPECTED_SITEUSER_ID'] = userId;
            form['INSPECTED_SITEUSER_NAME'] = name;
          } else {
            final int i = int.tryParse(typeStr.trim()) as int;
            Map item = inspectorList[i];
            item['INSPECTION_USER_INDEX'] = '$index';
            item['INSPECTION_USER_NAME'] = name;
            item['INSPECTION_USER_ID'] = userId;
          }
        });
        FocusHelper.clearFocus(context);
      },
    ).then((_) {});
  }

  /// 添加检查人员
  void _addInspector() {
    setState(() {
      inspectorList.add({
        'INSPECTION_INSPECTOR_ID': '', //检查人员主键
        'INSPECTION_DEPARTMENT_ID': '', //检查人员部门ID
        'INSPECTION_DEPARTMENT_NAME': '',
        'INSPECTION_USER_ID': '', //检查人员ID
        'INSPECTION_USER_INDEX': '',
        'INSPECTION_USER_NAME': '',
      });
      form['inspectorList'] = inspectorList;
    });
  }

  Widget _signListWidget() {
    return Column(
      children:
          signImages.map((path) {
            return Column(
              children: [
                const SizedBox(height: 10),
                const Divider(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      child: // 用一个 ConstrainedBox 限制最大尺寸，并改为 BoxFit.contain
                          ConstrainedBox(
                        constraints: const BoxConstraints(
                          maxWidth: 200,
                          maxHeight: 150,
                        ),
                        child: Image.file(
                          File(path),
                          // 改为完整显示
                          fit: BoxFit.contain,
                        ),
                      ),
                      onTap: () {
                        presentOpaque(
                          SingleImageViewer(imageUrl: path),
                          context,
                        );
                      },
                    ),
                    Column(
                      children: [
                        Container(
                          padding: const EdgeInsets.only(right: 5),
                          child: CustomButton(
                            text: 'X',
                            height: 30,
                            padding: const EdgeInsets.symmetric(horizontal: 10),
                            backgroundColor: Colors.red,
                            onPressed: () {
                              setState(() {
                                signImages.remove(path);
                              });
                            },
                          ),
                        ),
                        const SizedBox(height: 80),
                      ],
                    ),
                  ],
                ),
              ],
            );
          }).toList(),
    );
  }

  Widget _mainWidget() {
    return ListView(
      children: [
        Column(
          children: [
            ItemListWidget.itemContainer(
              horizontal: 0,
              Column(
                children: [
                  ListItemFactory.createYesNoSection(
                    title: '检查题目：',
                    groupValue: chooseTitleType,
                    yesLabel: '安全',
                    noLabel: '综合',
                    isEdit: _isEdit,
                    isRequired: true,
                    horizontalPadding: 5,
                    verticalPadding: 0,
                    text: '${form['INSPECTION_SUBJECT'] ?? ''}现场检查记录',
                    onChanged: (val) {
                      setState(() {
                        chooseTitleType = val;
                        form['INSPECTION_SUBJECT'] = val == true ? '安全' : '综合';
                      });
                    },
                  ),
                  const Divider(),
                  ItemListWidget.selectableLineTitleTextRightButton(
                    isRequired: _isEdit,
                    label: '被检查单位',
                    isEditable: _isEdit,

                    text:
                        _isEdit
                            ? form['INSPECTED_DEPARTMENT_NAME'] ?? '请选择'
                            : form['INSPECTED_DEPARTMENT_NAMES'] ?? '',
                    onTap: () => chooseUnitHandle('被检查单位'),
                  ),

                  const Divider(),

                  ItemListWidget.selectableLineTitleTextRightButton(
                    isRequired: _isEdit,
                    label: '被检查单位现场负责人',
                    isEditable: _isEdit,

                    text: form['INSPECTED_SITEUSER_NAME'] ?? '请选择',
                    onTap: () => choosePersonHandle('被检查单位'),
                  ),
                  const Divider(),

                  ItemListWidget.singleLineTitleText(
                    label: '检查场所：',
                    isEditable: _isEdit,
                    text: form['INSPECTION_PLACE'],
                    hintText: '请输入检查场所',
                    onChanged: (val) {
                      setState(() {
                        form['INSPECTION_PLACE'] = val;
                      });
                    },
                  ),
                  const Divider(),

                  ItemListWidget.selectableLineTitleTextRightButton(
                    label: '检查类型:',
                    onTap: () {
                      _chooseType();
                    },
                    isEditable: _isEdit,
                    text: form['INSPECTION_TYPE_NAME'] ?? '',
                  ),
                  const Divider(),

                  ItemListWidget.selectableLineTitleTextRightButton(
                    label: '检查开始时间:',
                    isEditable: _isEdit,
                    text: form['INSPECTION_TIME_START'] ?? '',
                    onTap: () async {
                      DateTime? picked = await BottomDateTimePicker.showDate(
                        context,
                      );
                      if (picked != null) {
                        setState(() {
                          form['INSPECTION_TIME_START'] = DateFormat(
                            'yyyy-MM-dd HH:mm:ss',
                          ).format(picked);
                        });
                        FocusHelper.clearFocus(context);
                      }
                    },
                  ),
                  const Divider(),

                  ItemListWidget.selectableLineTitleTextRightButton(
                    label: '检查结束时间:',
                    isEditable: _isEdit,
                    text: form['INSPECTION_TIME_END'] ?? '',
                    onTap: () async {
                      DateTime? picked = await BottomDateTimePicker.showDate(
                        context,
                      );
                      if (picked != null) {
                        setState(() {
                          form['INSPECTION_TIME_END'] = DateFormat(
                            'yyyy-MM-dd HH:mm:ss',
                          ).format(picked);
                        });
                        FocusHelper.clearFocus(context);
                      }
                    },
                  ),
                  if (!_isEdit)
                    Column(
                      children: [
                        const Divider(),
                        ItemListWidget.selectableLineTitleTextRightButton(
                          label: '记录填写时间:',
                          isEditable: _isEdit,
                          text: form['CREATTIME'] ?? '',
                        ),
                      ],
                    ),

                  const Divider(),
                  MultiTextFieldWithTitle(
                    label: "检查情况:",
                    // 更合适的标题
                    isEditable: _isEdit,
                    // 使用父组件的编辑状态
                    hintText: "请输入检查情况...",
                    texts: multiTexts,
                    onTextsChanged: (texts) {
                      setState(() {
                        multiTexts = texts; // 保存到状态变量
                        form['situationList'] = _stringsToSituationList(texts);
                      });
                    },
                  ),

                  const Divider(),
                  ItemListWidget.itemContainer(
                    Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            ListItemFactory.headerTitle('检查人员'),
                            if (_isEdit)
                              CustomButton(
                                text: "   添加   ",
                                height: 30,
                                padding: const EdgeInsets.symmetric(
                                  vertical: 2,
                                  horizontal: 5,
                                ),
                                backgroundColor: Colors.blue,
                                onPressed: () {
                                  _addInspector();
                                },
                              ),
                          ],
                        ),
                        SizedBox(height: 10),
                        ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: inspectorList.length,
                          itemBuilder: (context, index) {
                            return _personUnitItem(inspectorList[index], index);
                          },
                        ),
                      ],
                    ),
                  ),

                  const Divider(),
                  ItemListWidget.itemContainer(
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        ListItemFactory.headerTitle('发现问题'),
                        if (_isEdit)
                          CustomButton(
                            text: "   添加   ",
                            height: 30,
                            padding: const EdgeInsets.symmetric(
                              vertical: 2,
                              horizontal: 5,
                            ),
                            backgroundColor: Colors.blue,
                            onPressed: () {
                              _openDrawer({}, -1); // 添加括号和 await
                              FocusHelper.clearFocus(context);
                            },
                          ),
                      ],
                    ),
                  ),
                  HiddenListTable(
                    hiddenList: form['hiddenList'] ?? [],
                    forbidEdit: _isEdit,
                    baseImgPath: ApiService.baseImgPath,
                    personSignImg: form['PERSON_SIGN_IMG'] ?? '',
                    personSignTime: form['PERSON_SIGN_TIME'] ?? '',
                    showHidden: (item, idx) {
                      _openDrawer(item, idx);
                    },
                    removeHidden: (item, idx) {
                      _delHiddenForm(item, idx);
                    },
                    context: context,
                  ),
                  if (widget.type == 'look' && inspectorVerifyList.isNotEmpty)
                    Column(
                      children: [
                        const Divider(),
                        ItemListWidget.singleLineTitleText(
                          label: '打回信息',
                          isEditable: false,
                        ),
                        const Divider(),
                        ItemListWidget.singleLineTitleText(
                          label: '打回人',
                          isEditable: false,
                          text:
                              inspectorVerifyList.first['INSPECTION_USER_NAME'],
                        ),
                        const Divider(),
                        ItemListWidget.singleLineTitleText(
                          label: '打回信息',
                          isEditable: false,
                          text:
                              inspectorVerifyList
                                  .first['INSPECTION_USER_OPINION'],
                        ),
                        const Divider(),
                        ItemListWidget.OneRowImageTitle(
                          label: '检查人签字',
                          text:
                              inspectorVerifyList
                                  .first['INSPECTION_USER_SIGN_TIME'] ??
                              '',
                          onTapCallBack: (path) {
                            presentOpaque(
                              SingleImageViewer(imageUrl: path),
                              context,
                            );
                          },
                          imgPath:
                              inspectorVerifyList
                                  .first['INSPECTION_USER_SIGN_IMG'] ??
                              '',
                        ),
                      ],
                    ),
                  if (_isEdit && widget.type != 'detail')
                    Column(
                      children: [
                        ItemListWidget.multiLineTitleTextField(
                          label: '核实意见',
                          isEditable: _isEdit,
                          isRequired: false,
                          hintText: '检查人意见',
                          onChanged: (val) {
                            form['INSPECTION_USER_OPINION'] = val;
                          },
                          text: form['INSPECTION_USER_OPINION'] ?? '',
                        ),
                        if (form['INSPECTION_USER_OPINION']
                                .toString()
                                .isNotEmpty &&
                            _isEdit)
                          ItemListWidget.itemContainer(
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                ListItemFactory.headerTitle('签字'),
                                CustomButton(
                                  text: '手写签字',
                                  height: 36,
                                  backgroundColor: Colors.green,
                                  onPressed: () {
                                    _sign();
                                  },
                                ),
                              ],
                            ),
                          ),
                      ],
                    ),
                  if (signImages.isNotEmpty) _signListWidget(),

                  if (widget.type == 'detail')
                    Column(
                      children: [
                        const Divider(),
                        if (inspectorList.isNotEmpty)
                          Column(
                            children: [
                              ItemListWidget.selectableLineTitleTextRightButton(
                                label: '检查人员核实结果',
                                isEditable: false,
                                text: ' ',
                              ),
                              SizedBox(height: 5),
                              ListView.builder(
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                                itemCount: inspectorList.length,
                                itemBuilder: (context, index) {
                                  return _personSignItem(
                                    inspectorList[index],
                                    index,
                                  );
                                },
                              ),
                            ],
                          ),
                      ],
                    ),
                ],
              ),
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (_isEdit) ...[
                  SizedBox(
                    width: 150,
                    child: CustomButton(
                      text: '提交',
                      textStyle: TextStyle(color: Colors.white, fontSize: 17),
                      backgroundColor: Colors.blue,
                      onPressed: _submit,
                    ),
                  ),
                ] else ...[
                  SizedBox(
                    width: 150,
                    child: CustomButton(
                      text: '返回',
                      textStyle: TextStyle(color: Colors.white, fontSize: 17),
                      backgroundColor: Colors.blue,
                      onPressed: () => Navigator.pop(context),
                    ),
                  ),
                ],
              ],
            ),
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "安全检查发起", actions: []),

      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 12),
          child: form.isNotEmpty ? _mainWidget() : SizedBox(),
        ),
      ),
    );
  }
}
