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/photo_picker_row.dart'
    show RepairedPhotoSection, MediaType;
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.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/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/dt_work/SpecialWorkFormBaseWork.dart';

/// 作业人意见
class BreakgroundZyrDetail extends StatefulWidget {
  const BreakgroundZyrDetail({
    super.key,
    required this.BREAKGROUND_ID,
    required this.flow,
  });

  final String BREAKGROUND_ID;
  final String flow;

  @override
  State<BreakgroundZyrDetail> createState() => _BreakgroundZyrDetailState();
}

class _BreakgroundZyrDetailState extends State<BreakgroundZyrDetail> {
  late bool isEditable = false;

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

  final TextEditingController _contentController = TextEditingController();

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

  /// 作业简图
  List<ImageData> workImages = [];

  /// 签名
  List<String> signImages = [];
  List<String> signTimes = []; // 签字时间列表

  @override
  void initState() {
    super.initState();
    _getData();
    _contentController.addListener(() {
      setState(() {
        pd['WORK_CONTENT'] = _contentController.text;
      });
    });
  }

  /// 签字
  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') {
      if (workImages.isEmpty) {
        ToastUtil.showNormal(context, '请上传缩略图');
        return;
      }
      if (_contentController.text.isEmpty) {
        ToastUtil.showNormal(context, '请输入作业内容、范围、方式');
        return;
      }
    } else {
      reasonText = await CustomAlertDialog.showInput(
        context,
        title: '作废原因',
        hintText: '请输入作废原因',
        cancelText: '取消',
        confirmText: '确定'
      );
      if (reasonText.isEmpty) {
        ToastUtil.showNormal(context, '请填写作废原因');
        return;
      }
    }

    // 存回 measures
    final Map<String, dynamic> formData = {};
    // 提交参数
    formData['BREAKGROUND_ID'] = widget.BREAKGROUND_ID;
    formData['SIGNTIME'] = signTimes.join(',');
    formData['USER_ID'] = SessionService.instance.loginUserId;
    formData['APPLY_STATUS'] = status;
    formData['STEP_REASON'] = reasonText;
    formData['CONIMG_PATH'] = workImages
        .map((e) => e.serverPath)
        .toList()
        .join(',');
    formData['WORK_CONTENT'] = _contentController.text;
    formData['DESCR'] = pd['DESCR'] ?? '无';
    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请确认' + (status == '1' ? "通过" : "作废") + '本作业票？',
      cancelText: '取消',
      confirmText: '确定',
      barrierDismissible: false,
    );
    if (confirmed) {
      LoadingDialogHelper.show();
      try {
        final result = await ApiService.saveSafeFunctionSure(
          'breakground',
          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(
      'breakground',
      widget.BREAKGROUND_ID,
    );
    setState(() {
      pd = data['pd'];

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

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

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

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

  /// 底部按钮
  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: [
              SpecialWorkFormBaseWork(
                pd: pd,
                measuresList: measuresList,
                signs: signs,
                baseImgPath: ApiService.baseImgPath,
                isEditable: false,
                onChooseLevel: () {},
                onAnalyzeTap: () {},
              ),
              // Container(
              //   decoration: BoxDecoration(
              //     color: Colors.white,
              //     borderRadius: BorderRadius.circular(5),
              //   ),
              //   child: Column(
              //     children: [
              //
              //     ],
              //   )
              // ),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Column(
                  children: [
                    ItemListWidget.multiLineTitleTextField(
                      label: '作业内容、范围、方式：',
                      isEditable: true,
                      controller: _contentController,
                      hintText: '请输入动土内容、范围、公式',
                      text: pd['WORK_CONTENT'] ?? '',
                    ),
                    Divider(),

                    RepairedPhotoSection(
                      title: '作业内容、范围、方式简图',
                      maxCount: 100,
                      mediaType: MediaType.image,
                      onChanged: (paths) {},
                      isShowNum: false,
                      isRequired: true,
                      onMediaAdded: _onImageAdded,
                onMediaTapped: (path) {
                  presentOpaque(SingleImageViewer(imageUrl: path), context);
                },
                      onMediaRemoved: (path) {
                        final item = workImages.firstWhere(
                          (e) => e.localPath == path,
                        );
                        _onImageRemoved(item);
                      },
                      onAiIdentify: () {},
                    ),
                  ],
                ),
              ),
              ItemListWidget.itemContainer(
                Column(
                  children: [
                    Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            ListItemFactory.headerTitle('作业人'),
                            CustomButton(
                              text: '新增手写签字',
                              height: 36,
                              backgroundColor: Colors.green,
                              onPressed: () {
                                _sign();
                              },
                            ),
                          ],
                        ),
                        if (signImages.isNotEmpty) _signListWidget(),
                      ],
                    ),
                  ],
                ),
              ),
              _bottomButtons(),
            ],
          ),
        ),
      ),
    );
  }
}

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

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