import 'dart:convert';
import 'dart:io';
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_person_picker.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/lsyd_work/ElectricityDetailFormWidget.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/lsyd_work/qtfx_work_detail/electricity_gas_list.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/lsyd_work/qtfx_work_detail/electricity_gas_list.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/lsyd_work/szaq_work_detail/SafeFunctionDialog.dart';

/// 设置安全措施确认人
class ElectricitySetSafeDetail extends StatefulWidget {
  const ElectricitySetSafeDetail({
    super.key,
    required this.ELECTRICITY_ID,
    required this.flow,
  });

  final String ELECTRICITY_ID;
  final String flow;

  @override
  State<ElectricitySetSafeDetail> createState() =>
      _ElectricitySetSafeDetailState();
}

class _ElectricitySetSafeDetailState extends State<ElectricitySetSafeDetail> {
  late bool isEditable = false;

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

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

  String measuresListToJson() {
    final List<Map<String, dynamic>> jsonList =
        measuresListCopy.map((item) => item.toJson()).toList();
    return jsonEncode(jsonList);
  }

  Widget _chooseItem(MeasureItem item) {
    return Column(
      children: [
        ItemListWidget.selectableLineTitleTextRightButton(
          label: "确认单位",
          isEditable: true,
          text: item.DEPARTMENT_NAME ?? '请选择',
          onTap: () => chooseUnitHandle(item),
        ),
        Divider(height: 8, color: Colors.grey.shade200),
        ItemListWidget.selectableLineTitleTextRightButton(
          label: '确认人',
          isEditable: true,
          text: item.USER_NAME ?? '请选择',
          onTap: () => choosePersonHandle(item),
        ),
        Divider(height: 8, color: Colors.grey.shade200),
        // 安全措施
        ItemListWidget.OneRowButtonTitle(
          label: '安全措施：',
          buttonText: '选择安全措施',
          onTap: () {
            showSafeFunctionDialog(
              context,
              _getAvailableMeasures(item), // 只传可用的项
              initialSelected: item.selectMeasures, // 保留当前已选的
              (selected) {
                setState(() {
                  item.selectMeasures = selected;
                });
              },
            );
          },
        ),
      ],
    );
  }

  /// 弹出单位选择
  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>>[],
      );
    });
  }

  /// 弹出人员选择，需先选择单位
  void choosePersonHandle(MeasureItem item) async {
    String unitId = item.DEPARTMENT_ID;
    final personList = item.userList;
    if (!unitId.isNotEmpty) {
      ToastUtil.showNormal(context, '请先选择确认单位');
      return;
    }
    if (personList.isEmpty) {
      // 一般这种情况是因为重新编辑没有缓存对应部门的负责人，所以先拉取一下接口
      await _getPersonListForUnitId(item);
      final list = item.userList;

      if (list.isEmpty) {
        // 如果还是没数据，说明该部门没有可选的人
        ToastUtil.showNormal(context, '暂无数据，请选择其他单位');
      } else {
        choosePersonHandle(item);
      }
      return;
    }
    DepartmentPersonPicker.show(
      context,
      personsData: personList,
      onSelected: (userId, name) {
        setState(() {
          item.USER_NAME = name;
          item.USER_ID = userId;
          print(json.encode(measuresListCopy));
        });
      },
    ).then((_) {});
  }

  /// 签字
  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(() {
        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(),
    );
  }

  /// 作废  -1  通过 1
  Future<void> _submit(String status) async {
    if (imagePaths.isEmpty) {
      ToastUtil.showNormal(context, '请签字');
      return;
    }
    List<Map<String, dynamic>> signers = [];
    String reasonText = '';

    if (status == '1') {
      int index = 0;
      for (var item in measuresListCopy) {
        if (item.USER_ID.isEmpty) {
          ToastUtil.showNormal(context, '第${index + 1}项未设置确认人');
          return;
        }
        if (item.selectMeasures.isEmpty) {
          ToastUtil.showNormal(context, '第${index + 1}项未选择安全措施');
          return;
        }
        final userId = item.USER_ID;
        final selectMeasures = item.selectMeasures as List<dynamic>? ?? [];

        for (var item in selectMeasures) {
          signers.add({
            'BUS_ELECTRICITY_MEASURES_ID': item['BUS_ELECTRICITY_MEASURES_ID'],
            'USER_ID': userId,
          });
        }

        index++;
      }
      // 检查长度是否一致
      if (signers.length != measuresList.length) {
        // 使用 ScaffoldMessenger 弹出提示
        ToastUtil.showNormal(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['ELECTRICITY_ID'] = widget.ELECTRICITY_ID;
    formData['SIGNTIME'] = signTimes.join(',');
    formData['USER_ID'] = SessionService.instance.loginUserId;
    formData['APPLY_STATUS'] = status;
    formData['STEP_REASON'] = reasonText;
    formData['PREPARERS'] = json.encode(signers);
    printLongString('submit---:${json.encode(formData)}');
    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请确认' + (status == '1' ? "通过" : "作废") + '本作业票？',
      cancelText: '取消',
      confirmText: '确定',
      barrierDismissible: false,
    );
    if (confirmed) {
      LoadingDialogHelper.show();
      try {
        final result = await ApiService.saveSafeFunctionSure(
          'electricity',
          formData,
          imagePaths,
        );
        LoadingDialogHelper.hide();
        if (result['result'] == 'success') {
          ToastUtil.showSuccess(context, '保存成功');
          Navigator.of(context).pop(true);
        }else{
          ToastUtil.showNormal(context, '操作失败：${result['msg'] ?? '未知错误'}');
        }
      } 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(
      'electricity',
      widget.ELECTRICITY_ID,
    );
    setState(() {
      pd = data['pd'];
      _getMeasures();
    });
  }

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

  void removeMeasuresListCopy(int index) {
    setState(() {
      measuresListCopy.removeAt(index);
    });
  }

  void addMeasuresListCopy() {
    setState(() {
      measuresListCopy.add(
        MeasureItem(
          id: Random().nextDouble(),
          DEPARTMENT_ID: '',
          DEPARTMENT_NAME: '',
          USER_ID: '',
          USER_NAME: '',
          userList: [],
          userIndex: -1,
          selectMeasures: [],
        ),
      );
    });
  }

  /// 计算当前 item 可选的安全措施
  List<Map<String, dynamic>> _getAvailableMeasures(MeasureItem current) {
    // 把除了 current 之外，已经被选走的措施 ID 全部搜集起来
    final usedIds = <dynamic>{};
    for (var item in measuresListCopy) {
      if (item == current) continue;
      for (var m in item.selectMeasures) {
        usedIds.add(m['BUS_ELECTRICITY_MEASURES_ID']);
      }
    }
    // 返回：所有 measuresList 中，ID 不在 usedIds 或者正好属于 current 的那几条
    List<Map<String, dynamic>> list =
        measuresList.where((m) {
          final id = m['BUS_ELECTRICITY_MEASURES_ID'];
          final isCurrentSelected = current.selectMeasures.any(
            (sm) => sm['BUS_ELECTRICITY_MEASURES_ID'] == id,
          );
          return !usedIds.contains(id) || isCurrentSelected;
        }).toList();

    return list;
  }

  /// 安全防护措施
  Widget _setSafeDetailWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      padding: EdgeInsets.symmetric(horizontal: 5),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ListItemFactory.createBuildSimpleSection('安全防护措施'),
              CustomButton(
                text: '添加',
                padding: EdgeInsets.symmetric(horizontal: 15),
                backgroundColor: Colors.blue,
                height: 32,
                onPressed: () => addMeasuresListCopy(),
              ),
            ],
          ),
          ...measuresListCopy.asMap().entries.map((entry) {
            int index = entry.key;
            MeasureItem item = entry.value;
            return Padding(
              padding: EdgeInsets.all(0),
              child: Stack(
                children: [
                  Container(
                    color: Colors.white,

                    child: Padding(
                      padding: EdgeInsets.all(12),
                      child: Container(
                        padding: EdgeInsets.all(2),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(5),
                          border: Border.all(color: Colors.grey.shade300),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 部门 picker
                            _chooseItem(item),

                            ...item.selectMeasures.asMap().entries.map((e) {
                              int idx = e.key;
                              String txt = e.value['PROTECTIVE_MEASURES'];
                              return Padding(
                                padding: EdgeInsets.only(
                                  top: 4,
                                  left: 12,
                                  right: 12,
                                  bottom: 12,
                                ),
                                child: Text('${idx + 1}. $txt'),
                              );
                            }),
                          ],
                        ),
                      ),
                    ),
                  ),
                  if (index != 0)
                    Positioned(
                      top: 0,
                      right: 0,
                      child: GestureDetector(
                        onTap: () => removeMeasuresListCopy(index),
                        child: Stack(
                          alignment: AlignmentDirectional.center,
                          children: [
                            Container(
                              decoration: BoxDecoration(
                                color: Colors.red,
                                borderRadius: BorderRadius.circular(10),
                              ),
                              width: 20,
                              height: 20,
                            ),
                            Icon(Icons.close, color: Colors.white, size: 15),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            );
          }),
          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: [
              // _card(_defaultDetail()),
              ElectricityDetailFormWidget(
                pd: pd,
                isEditable: false,
                onChooseLevel: () {},
                onChooseHotworkUser: () {},
                onAnalyzeTap: () {
                  pushPage(
                    ElectricityGasList(ELECTRICITY_ID: widget.ELECTRICITY_ID),
                    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,
    };
  }
}
