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/SafeCheckFormView.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 SafecheckDangerDetail extends StatefulWidget {
  const SafecheckDangerDetail({
    super.key,
    required this.INSPECTION_ID,
    required this.INSPECTION_INSPECTOR_ID,
    required this.isEdit,
  });

  final String INSPECTION_ID;
  final String INSPECTION_INSPECTOR_ID;
  final bool isEdit;

  @override
  State<SafecheckDangerDetail> createState() => _SafecheckDangerDetailState();
}

class _SafecheckDangerDetailState extends State<SafecheckDangerDetail> {
  String msg = 'add';
  bool _isEdit = false;
  List<String> signImages = [];
  List<String> signTimes = []; // 签字时间列表
  Map<String, dynamic> inspectedForm = {};
  List<Map<String, dynamic>> inspectorRules = [
    {'name': 'INSPECTION_STATUS', 'message': '核实结果不能为空'},
    {'name': 'INSPECTION_ID', 'message': '安全检查ID不能为空'},
    {'name': 'INSPECTION_USER_ID', 'message': '检查人不能为空'},
  ];
  Map<String, dynamic> form = {};

  @override
  void initState() {
    super.initState();
    _isEdit = widget.isEdit;

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getData();
    });
  }

  Future<void> _getData() async {
    try {
      final result = await ApiService.getSafeCheckSureList(
        widget.INSPECTION_ID,
      );
      // 在 await 之后检查 mounted，避免页面已经被 pop 导致 setState 报错
      if (!mounted) return;
      setState(() {
        form = result['pd'] ?? {};
        inspectedForm = {
          'INSPECTION_EXPLAIN_ID': '', // 安全检查人员主键ID
          'INSPECTION_STATUS': '3',
          'INSPECTION_ID': widget.INSPECTION_ID ?? '', // 安全检查ID
          'INSPECTED_EXPLAIN': '', // 申辩内容
          'INSPECTED_EXPLAIN_FILENAME': '', // 申辩附件名称
          'INSPECTED_SITEUSER_SIGN_IMG': '', // 被检查单位现场负责人签字
          'INSPECTED_SITEUSER_SIGN_TIME': '',
        };

      });
    } catch (e, st) {
      print('加载单条数据失败: $e\n$st');
      if (mounted) {
        ToastUtil.showNormal(context, '加载数据失败：$e');
      }
    }
  }

  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: [],
        ),
      );

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

  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: [
            SafeCheckFormView(
              form: form,
              isEdit: false,
              onHiddenShow: (item, index) {
                _openDrawer(item, index);
              },
            ),

              Column(
                children: [
                  SizedBox(height: 10),
                  ItemListWidget.itemContainer(
                    horizontal: 0,
                    Column(
                      children: [
                        ItemListWidget.singleLineTitleText(
                          label: '被检查单位现场负责人意见：',
                          isEditable: false,
                          text: FormUtils.hasValue(form, 'INSPECTED_EXPLAIN') ? '申辩' : '同意',
                        ),
                        const Divider(),
                        if (FormUtils.hasValue(form, 'INSPECTED_EXPLAIN'))
                          Column(
                            children: [
                              ItemListWidget.multiLineTitleTextField(
                                label: '申辩说明',
                                isEditable: false,
                                text: form['INSPECTED_EXPLAIN'] ?? '',
                              ),
                              const Divider(),

                            ],
                          ),
                        ItemListWidget.OneRowImageTitle(
                          label: '被检查单位现场负责人签字',
                          text: form['INSPECTED_SITEUSER_SIGN_TIME'] ?? '',
                          onTapCallBack: (path) {
                            presentOpaque(SingleImageViewer(imageUrl: path), context);
                          },
                          imgPath: form['INSPECTED_SITEUSER_SIGN_IMG'] ?? '',
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  width: 150,
                  child: CustomButton(
                    text: '返回',
                    textStyle: TextStyle(color: Colors.white, fontSize: 17),
                    backgroundColor: Colors.blue,
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

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