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/item_list_widget.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dz_work/SpecialWorkFormBaseWork.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.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';

/// 本地路径 + 线上路径模型
class ImageData {
  String localPath;
  String serverPath;

  ImageData({required this.localPath, required this.serverPath});
}

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

  final String HOISTING_ID;
  final String flow;

  @override
  State<HoistworkAqjdDetail> createState() => _HoistworkAqjdDetailState();
}

class _HoistworkAqjdDetailState extends State<HoistworkAqjdDetail> {
  late bool isEditable = false;

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

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

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

  /// 拍照或选图后的回调
  Future<void> _onImageAdded(String localPath) async {
    // 上传到服务器
    final res = await ApiService.uploadSaveFile(localPath);
    final url = res['FILE_PATH'] as String;
    setState(() {
      imgList.add(ImageData(localPath: localPath, serverPath: url));
    });
  }

  /// 删除图片处理：调用删除接口并更新列表
  Future<void> _onImageRemoved(ImageData item) async {
    if (item.serverPath != null) {
      await ApiService.deleteSaveFile(item.serverPath!);
    }
    setState(() {
      imgList.remove(item);
    });
  }

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

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

  /// 作废  -1  通过 1
  Future<void> _submit(String status) async {
    if (signImages.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;
      }
    }
    // 抽取所有非空的 serverPath 并拼成逗号分隔的字符串
    final serverPathString = imgList
        .map((e) => e.serverPath)
        .where((s) => s.isNotEmpty)
        .map((s) => s) // 将 String? 转回 String
        .join(',');

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

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

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

  Future<void> _getMeasures(String homework_id) async {
    final data = await ApiService.listSignFinishMeasures(
      'hoisting',
      homework_id.length > 0 ? homework_id : widget.HOISTING_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(
      'hoisting',
      homework_id.length > 0 ? homework_id : widget.HOISTING_ID,
    );
    setState(() {
      signs = data['signs'] ?? {};
    });
  }

  /// 底部按钮
  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(
            spacing: 12,
            children: [
              // _setSafeDetailWidget(),
              SpecialWorkFormBaseWork(
                pd: pd,
                measuresList: measuresList,
                signs: signs,
                baseImgPath: ApiService.baseImgPath,
                isEditable: false,
                onChooseLevel: () {},
                onAnalyzeTap: () {},
              ),
              ItemListWidget.itemContainer(
                Column(
                  children: [
                    RepairedPhotoSection(
                      title: '上传图片',
                      maxCount: 2,
                      mediaType: MediaType.image,
                      onChanged: (paths) {},
                      onMediaAdded: _onImageAdded,
                onMediaTapped: (path) {
                  presentOpaque(SingleImageViewer(imageUrl: path), context);
                },
                      onMediaRemoved: (path) {
                        final item = imgList.firstWhere(
                          (e) => e.localPath == path,
                        );
                        _onImageRemoved(item);
                      },
                      onAiIdentify: () {},
                    ),
                    ItemListWidget.itemContainer(
                      Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              ListItemFactory.headerTitle('安全交底人'),
                              CustomButton(
                                text: '新增手写签字',
                                height: 36,
                                backgroundColor: Colors.green,
                                onPressed: () {
                                  _sign();
                                },
                              ),
                            ],
                          ),
                          if (signImages.isNotEmpty) _signListWidget(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              _bottomButtons(),
            ],
          ),
        ),
      ),
    );
  }
}
