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/custom_button.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/HotWorkDetailFormWidget.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/dh_work/qtfx_work_detail/hotwork_gas_list.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_Wrok/MeasuresListWidget.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 '../HighWorkDetailFormWidget.dart';

/// 监护人签字
class HighworkJhrDetail extends StatefulWidget {
  const HighworkJhrDetail({
    super.key,
    required this.HIGHWORK_ID,
    required this.flow,
  });

  final String HIGHWORK_ID;
  final String flow;

  @override
  State<HighworkJhrDetail> createState() => _HighworkJhrDetailState();
}

class _HighworkJhrDetailState extends State<HighworkJhrDetail> {
  late bool isEditable = false;

  /// 详情
  late Map<String, dynamic> pd = {};

  /// 安全防护措施列表
  late List<Map<String, dynamic>> measuresList = [];
  late Map<String, dynamic> signs = {};

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

  /// 签字
  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;
    }
    String reasonText = '';

    if (status == '1') {
    } else {
      reasonText = await CustomAlertDialog.showInput(
        context,
        title: '作废原因',
        hintText: '请输入作废原因',
        cancelText: '取消',
        confirmText: '确定'
      );
      if (reasonText.isEmpty) {
        ToastUtil.showNormal(context, '请填写作废原因');
        return;
      }
    }

    final Map<String, dynamic> formData = {};
    // 提交参数
    formData['HIGHWORK_ID'] = widget.HIGHWORK_ID;
    formData['SIGNTIME'] = signTimes.join(',');
    formData['USER_ID'] = SessionService.instance.loginUserId;
    formData['APPLY_STATUS'] = status;
    formData['STEP_REASON'] = reasonText;

    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请确认' + (status == '1' ? "通过" : "作废") + '本作业票？',
      cancelText: '取消',
      confirmText: '确定',
      barrierDismissible: false,
    );
    if (confirmed) {
      LoadingDialogHelper.show();
      try {
        final result = await ApiService.saveSafeFunctionSure(
          'highwork',
          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');
      }
    }
  }

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

      _getSigns(pd['HIGHWORK_ID'] ?? '');
      _getMeasures(pd['HIGHWORK_ID'] ?? '');
    });
  }

  Future<void> _getMeasures(String homework_id) async {
    final data = await ApiService.listSignFinishMeasures(
      'highwork',
      homework_id.length > 0 ? homework_id : widget.HIGHWORK_ID,
    );
    setState(() {
      measuresList = List<Map<String, dynamic>>.from(
        data['finishMeasuresList'] ?? <Map<String, dynamic>>[],
      );
    });
  }

  Future<void> _getSigns(String homework_id) async {
    final data = await ApiService.listSignFinished(
      'highwork',
      homework_id.length > 0 ? homework_id : widget.HIGHWORK_ID,
    );
    setState(() {
      signs = data['signs'] ?? {};
    });
  }

  /// 其他安全防护措施
  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: false,
                    isShowSign: true,
                  ),
                ),
              ],
            ),
          if (FormUtils.hasValue(signs, 'MEASURES_CONFIRM'))
            Column(
              children: [
                SizedBox(height: 20),
                ListItemFactory.createBuildSimpleSection('其他安全防护措施'),
                Container(
                  color: Colors.white,
                  child: OtherMeasuresWidget(
                    otherMeasures: signs['MEASURES_CONFIRM'],
                    baseImgPath: ApiService.baseImgPath,
                  ),
                ),
              ],
            ),
          SizedBox(height: 20),

          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ListItemFactory.createBuildSimpleSection('监护人'),
              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()),
              HighWorkDetailFormWidget(
                pd: pd,
                isEditable: false,
                onChooseLevel: () {},
              ),
              SizedBox(height: 20),
              _setSafeDetailWidget(),
              SizedBox(height: 20),
              _bottomButtons(),
            ],
          ),
        ),
      ),
    );
  }
}
