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/tools/tools.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/my_appbar.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/mbcd_work/BlindboardFormBaseWork.dart';

/// 审批部门意见
class BlindboardSpbmDetail extends StatefulWidget {
  const BlindboardSpbmDetail({
    super.key,
    required this.BLINDBOARD_ID,
    required this.flow,
  });

  final String BLINDBOARD_ID;
  final String flow;

  @override
  State<BlindboardSpbmDetail> createState() => _BlindboardSpbmDetailState();
}

class _BlindboardSpbmDetailState extends State<BlindboardSpbmDetail> {
  late bool isEditable = false;

  /// 详情
  late Map<String, dynamic> pd = {};
  late List<dynamic> boardList = [];
  final TextEditingController _contentController = TextEditingController();

  /// 安全防护措施列表
  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> _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 = '';
    String DESCR = _contentController.text.trim();

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

    // 存回 measures
    final Map<String, dynamic> formData = {};
    // 提交参数
    formData['BLINDBOARD_ID'] = widget.BLINDBOARD_ID;
    formData['SIGNTIME'] = signTimes.join(',');
    formData['USER_ID'] = SessionService.instance.loginUserId;
    formData['APPLY_STATUS'] = status;
    formData['STEP_REASON'] = reasonText;
    formData['DESCR'] = 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(
          'blindboard',
          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(
      'blindboard',
      widget.BLINDBOARD_ID,
    );
    setState(() {
      pd = data['pd'];
      boardList = data['boardList'];

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

  Future<void> _getMeasures(String homework_id) async {
    final data = await ApiService.listSignFinishMeasures(
      'blindboard',
      homework_id.length > 0 ? homework_id : widget.BLINDBOARD_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(
      'blindboard',
      homework_id.length > 0 ? homework_id : widget.BLINDBOARD_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(),
              BlindboardFormBaseWork(
                boardList: boardList,
                pd: pd,
                measuresList: measuresList,
                signs: signs,
                baseImgPath: ApiService.baseImgPath,
                isEditable: false,
                onChooseLevel: () {},
                onAnalyzeTap: () {},
              ),
              ItemListWidget.itemContainer(
                Column(
                  children: [
                    ListItemFactory.createBuildMultilineInput(
                      '审批部门负责人意见',
                      '请输入意见',
                      _contentController,
                      isRequired: true,
                    ),
                    Divider(),
                    Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text('* ', style: TextStyle(color: Colors.red)),
                                ListItemFactory.headerTitle('审批部门负责人'),
                              ],
                            ),
                            CustomButton(
                              text: '新增手写签字',
                              height: 36,
                              backgroundColor: Colors.green,
                              onPressed: () {
                                _sign();
                              },
                            ),
                          ],
                        ),
                        if (signImages.isNotEmpty) _signListWidget(),
                      ],
                    ),
                  ],
                ),
              ),
              _bottomButtons(),
            ],
          ),
        ),
      ),
    );
  }
}
