import 'dart:convert';
import 'dart:io';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/sxkj_work/qtfx_work_detail/spacework_gas_list.dart';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/department_picker.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/home/tap/tabList/special_wrok/dangerous_options_page.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_Wrok/MeasuresListWidget.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/sxkj_work/SpaceWorkDetailFormWidget.dart';

/// 安全措施确认
class SpaceworkSafeFuncSure extends StatefulWidget {
  const SpaceworkSafeFuncSure({
    super.key,
    required this.CONFINEDSPACE_ID,
    required this.flow,
  });

  final String CONFINEDSPACE_ID;
  final String flow;

  @override
  State<SpaceworkSafeFuncSure> createState() => _SpaceworkSafeFuncSureState();
}

class _SpaceworkSafeFuncSureState extends State<SpaceworkSafeFuncSure> {
  late bool isEditable = false;

  /// 详情
  late Map<String, dynamic> pd = {};
  late List<Map<String, dynamic>> measuresList = [];

  /// 其他安全措施
  final TextEditingController _otherController = TextEditingController();

  /// 安全防护措施列表
  List<String> imagePaths = [];
  List<String> signTimes = []; // 签字时间列表
  @override
  void initState() {
    super.initState();
    _getData();
  }

  /// 弹出单位选择
  void chooseUnitHandle(MeasureItem item) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPicker(
            onSelected: (id, name) async {
              setState(() {
                item.DEPARTMENT_ID = id;
                item.DEPARTMENT_NAME = name;
              });
              _getPersonListForUnitId(item);
            },
          ),
    ).then((_) {});
  }

  Future<void> _getPersonListForUnitId(MeasureItem item) async {
    // 拉取该单位的人员列表并缓存
    final result = await ApiService.getListTreePersonList(item.DEPARTMENT_ID);
    setState(() {
      item.userList = List<Map<String, dynamic>>.from(
        result['userList'] ?? <Map<String, dynamic>>[],
      );
    });
  }

  /// 签字
  Future<void> _sign() async {
    await NativeOrientation.setLandscape();
    FocusHelper.clearFocus(context);
    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(() {
        imagePaths.add(path);
        signTimes.add(now);
        FocusHelper.clearFocus(context);
      });
    }
  }

  Widget _signListWidget() {
    return Column(
      children:
          imagePaths.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(() {
                                imagePaths.remove(path);
                              });
                            },
                          ),
                        ),
                        const SizedBox(height: 80),
                      ],
                    ),
                  ],
                ),
              ],
            );
          }).toList(),
    );
  }

  bool _validateAndProceed(BuildContext context) {
    for (var i = 0; i < measuresList.length; i++) {
      final m = measuresList[i];

      // 1. 未签字
      if (!FormUtils.hasValue(m, 'SIGN_ITEM')) {
        ToastUtil.showNormal(context, '第${i + 1}项未签字');
        return false;
      }

      // 只有 STATUS == '1' 时才检查后续 ANSWER
      if (m['STATUS'] == '1') {
        for (var j = 1; j <= 4; j++) {
          if (FormUtils.hasValue(m, 'QUESTION${j}')) {
            if (!FormUtils.hasValue(m, 'ANSWER${j}') ||
                (m['ANSWER${j}'] as String?)!.length == 0) {
              ToastUtil.showNormal(context, '第${i + 1}项未填写第${j}项');
              return false;
            }
          }
        }
      }
    }
    return true;
  }

  /// 提交  1 提交 0暂存
  Future<void> _submit(String status) async {
    if (_otherController.text.trim().isEmpty) {
      ToastUtil.showNormal(context, '请输入其他安全措施,没有请填“无”');
      return;
    }
    if (imagePaths.isEmpty) {
      ToastUtil.showNormal(context, '请签字');
      return;
    }
    String reasonText = '';

    if (status == '1') {
      if (!_validateAndProceed(context)) {
        return;
      }
    } else {
      reasonText = await CustomAlertDialog.showInput(
        context,
        title: '作废原因',
        hintText: '请输入作废原因',
        cancelText: '取消',
        confirmText: '确定'
      );
      if (reasonText.isEmpty) {
        ToastUtil.showNormal(context, '请填写作废原因');
        return;
      }
    }
    final Map<String, dynamic> formData = {};
    // 提交参数
    formData['APPLY_STATUS'] = status;
    formData['CONFINEDSPACE_ID'] = widget.CONFINEDSPACE_ID;
    formData['DESCR'] = _otherController.text;
    formData['SIGNTIME'] = signTimes.join(',');
    formData['USER_ID'] = SessionService.instance.loginUserId;
    formData['STEP_REASON'] = reasonText;
    formData['MEASURES'] = json.encode(measuresList);

    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请确认' + (status == '1' ? "通过" : "作废") + '本作业票？',
      cancelText: '取消',
      confirmText: '确定',
      barrierDismissible: false,
    );
    if (confirmed) {
      LoadingDialogHelper.show();
      try {
        final result = await ApiService.saveSafeFunctionSure(
          'confinedspace',
          formData,
          imagePaths,
        );
        LoadingDialogHelper.hide();
        if (result['result'] == 'success') {
          ToastUtil.showSuccess(context, status == '1' ? '提交成功' : '已暂存');
          Navigator.of(context).pop(true); // 传 true 表示成功（可选）
        }
      } catch (e) {
        LoadingDialogHelper.hide();
        ToastUtil.showNormal(context, '操作失败：$e');
      }
    }
  }

  void printLongString(String text, {int chunkSize = 800}) {
    final pattern = RegExp('.{1,$chunkSize}'); // 每 chunkSize 个字符一组
    for (final match in pattern.allMatches(text)) {
      print(match.group(0));
    }
  }

  /// 初始化拉取数据
  Future<void> _getData() async {
    final data = await ApiService.getHomeworkFindById(
      'confinedspace',
      widget.CONFINEDSPACE_ID,
    );
    setState(() {
      pd = data['pd'];
      _getMeasures();
    });
  }

  Future<void> _getMeasures() async {
    final data = await ApiService.listSignSureAllMeasures(
      'confinedspace',
      widget.CONFINEDSPACE_ID,
    );
    setState(() {
      measuresList = List<Map<String, dynamic>>.from(
        data['measuresForSignList'] ?? <Map<String, dynamic>>[],
      );
    });
  }

  Future<void> _itemToSign(Map<String, dynamic> measures, int index) async {
    // 签名图片列表
    final List<Map<String, dynamic>> signImgList = measures['SIGN_ITEM'] ?? [];

    // 操作图片路径列表
    final List<ImageData> imgList = [];
    if ((measures['IMG_PATH'] as String?)?.isNotEmpty ?? false) {
      for (var path in (measures['IMG_PATH'] as String).split(',')) {
        imgList.add(ImageData(localPath: path, serverPath: path));
      }
    }
    //measures['STATUS']
    final result = await pushPage(
      DangerousOptionsPage(
        index: index,
        status: int.parse(
          FormUtils.hasValue(measures, 'STATUS') ? measures['STATUS'] : '1',
        ),
        measures: measures['PROTECTIVE_MEASURES'] ?? '',
        imgList: imgList,
        signImgList: signImgList,
      ),
      context,
    );
    if (result != null) {
      setState(() {
        // 更新返回的图片列表（local + remote）
        final returned = result['imgList'] as List<dynamic>;
        // 先映射成 ImageData 列表
        final imgDataList =
            returned.map((m) {
              return ImageData(
                localPath: m['local'] as String,
                serverPath: m['remote'] as String,
              );
            }).toList();

        // 抽取所有非空的 serverPath 并拼成逗号分隔的字符串
        final serverPathString = imgDataList
            .map((e) => e.serverPath)
            .where((s) => s.isNotEmpty)
            .map((s) => s) // 将 String? 转回 String
            .join(',');

        // 存回 measures
        measures['IMG_PATH'] = serverPathString;

        // 更新签字列表
        measures['SIGN_ITEM'] = List<Map<String, dynamic>>.from(
          result['signImgList'] as List,
        );
        // 更新状态、序号等
        measures['STATUS'] = result['status'].toString();
        index = result['index'] as int;
      });
    }
  }

  /// 安全防护措施
  Widget _setSafeDetailWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      padding: EdgeInsets.symmetric(horizontal: 5),
      child: Column(
        children: [
          if (measuresList.isNotEmpty)
            Column(
              children: [
                SizedBox(height: 5),
                ListItemFactory.createBuildSimpleSection('安全防护措施'),
                Container(
                  color: Colors.white,
                  child: MeasuresListWidget(
                    measuresList: measuresList, // List<Map<String, dynamic>>
                    baseImgPath: ApiService.baseImgPath,
                    isAllowEdit: true,
                    onSign: (item) {
                      _itemToSign(item, measuresList.indexOf(item));
                    },
                  ),
                ),
              ],
            ),
          ItemListWidget.singleLineTitleText(
            label: '其他安全措施:',
            isEditable: true,
            hintText: '请输入其他安全措施',
            controller: _otherController,
          ),
          SizedBox(height: 20),

          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(),
              CustomButton(
                text: '新增手写签字',
                height: 36,
                backgroundColor: Colors.green,
                onPressed: () {
                  _sign();
                },
              ),
            ],
          ),
          SizedBox(height: 10),
          if (imagePaths.isNotEmpty) _signListWidget(),
        ],
      ),
    );
  }

  /// 底部按钮
  Widget _bottomButtons() {
    return Row(
      spacing: 10,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: CustomButton(
            height: 45,
            textStyle: TextStyle(fontSize: 16, color: Colors.white),
            text: '作废',
            backgroundColor: Colors.red,
            onPressed: () {
              _submit('-1');
            },
          ),
        ),
        Expanded(
          child: CustomButton(
            textStyle: TextStyle(fontSize: 16, color: Colors.white),
            text: '通过',
            backgroundColor: Colors.green,
            onPressed: () {
              _submit('1');
            },
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '安全措施确认人意见'),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(12),
          child: Column(
            children: [
              SpaceWorkDetailFormWidget(
                pd: pd,
                isEditable: false,
                onChooseLevel: () {},
                onChooseSpaceName: () {},
                onAnalyzeTap: () {
                  pushPage(
                    SpaceworkGasList(
                      CONFINEDSPACE_ID: widget.CONFINEDSPACE_ID,
                      addFlag: true,
                    ),
                    context,
                  );
                },
              ),
              SizedBox(height: 20),
              _setSafeDetailWidget(),
              SizedBox(height: 20),
              _bottomButtons(),
            ],
          ),
        ),
      ),
    );
  }
}

class MeasureItem {
  final double id;
  String DEPARTMENT_ID;
  String DEPARTMENT_NAME;
  String USER_ID;
  String USER_NAME;
  List<Map<String, dynamic>> userList;
  int userIndex;
  List<Map<String, dynamic>> selectMeasures;

  MeasureItem({
    required this.id,
    this.DEPARTMENT_ID = '',
    this.DEPARTMENT_NAME = '',
    this.USER_ID = '',
    this.USER_NAME = '',
    List<Map<String, dynamic>>? userList,
    this.userIndex = -1,
    List<Map<String, dynamic>>? selectMeasures,
  }) : userList = userList ?? [],
       selectMeasures = selectMeasures ?? [];

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'DEPARTMENT_ID': DEPARTMENT_ID,
      'DEPARTMENT_NAME': DEPARTMENT_NAME,
      'USER_ID': USER_ID,
      'USER_NAME': USER_NAME,
      'userList': userList,
      'userIndex': userIndex,
      'selectMeasures': selectMeasures,
    };
  }
}
