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/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/CheckPersonSure/check_person_detail.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/Start/safeCheck_start_detail.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

class SafecheckDefendSetPage extends StatefulWidget {
  const SafecheckDefendSetPage({super.key, required this.INSPECTION_ID});

  final String INSPECTION_ID;

  @override
  State<SafecheckDefendSetPage> createState() => _SafecheckDefendSetPageState();
}

class _SafecheckDefendSetPageState extends State<SafecheckDefendSetPage> {
  late Map<String, dynamic> form = {};
  late bool chooseType = true;
  late String INSPECTION_STATUS = '-2';
  List<String> signImages = [];
  List<String> signTimes = []; // 签字时间列表
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();
  }

  Future<void> _getData() async {
    LoadingDialogHelper.show();
    try {
      final result = await ApiService.getSafeCheckStartGoEdit(
        widget.INSPECTION_ID,
      );
      // 在 await 之后检查 mounted，避免页面已经被 pop 导致 setState 报错
      if (!mounted) return;
      setState(() {
        form = result['pd'] ?? {};
      });
      LoadingDialogHelper.hide();
    } catch (e, st) {
      LoadingDialogHelper.hide();

      print('加载单条数据失败: $e\n$st');
      if (mounted) {
        ToastUtil.showNormal(context, '加载数据失败：$e');
      }
    }
  }

  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 = [];
        signTimes = [];
        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(),
    );
  }
  Future<void> _submit() async{
    if (INSPECTION_STATUS == '-2') {
      await pushPage(SafecheckStartDetail(INSPECTION_ID: form['INSPECTION_ID'] ?? '', type: 'edit'), context);
      return;
    }
    if (INSPECTION_STATUS == '3' && form['INSPECTED_EXPLAIN_REFUSE'] == '') {
      ToastUtil.showNormal(context, '请填写理由');
      return;
    }
    if (signImages.isEmpty) {
      ToastUtil.showNormal(context, '请签字');
      return;
    }
    LoadingDialogHelper.show();
    form['OPERATOR'] = SessionService.instance.loginUserId;
    form['ACTION_USER'] = SessionService.instance.username;
    form['INSPECTION_STATUS'] = INSPECTION_STATUS;
    final result = await ApiService.safeCheckDefendSubmit(form, signImages.first);
    LoadingDialogHelper.hide();
    try{
      if (result['result'] == 'success') {
        ToastUtil.showSuccess(context, '保存成功');
      }else{
        ToastUtil.showError(context, '保存失败');
      }
      Navigator.of(context).pop();
    }catch(e){}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '申辩处理'),
      body: SafeArea(
        child:
            form.isNotEmpty
                ? ListView(
                  children: [
                    Padding(
                      padding: EdgeInsets.all(12),
                      child: ItemListWidget.itemContainer(
                        horizontal: 0,
                        Column(
                          children: [
                            ItemListWidget.OneRowImageTitle(
                              label: '申辩人签字',
                              text: form['INSPECTED_SITEUSER_SIGN_TIME'],
                              onTapCallBack: (path) {
                                presentOpaque(
                                  SingleImageViewer(
                                    imageUrl:
                                        ApiService.baseImgPath +
                                        form['INSPECTED_SITEUSER_SIGN_IMG'],
                                  ),
                                  context,
                                );
                              },
                              imgPath:
                                  form['INSPECTED_SITEUSER_SIGN_IMG'] ?? '',
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '申辩时间',
                              isEditable: false,
                              text: form['INSPECTED_SITEUSER_SIGN_TIME'] ?? '',
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '申辩说明',
                              isEditable: false,
                              text: form['INSPECTED_EXPLAIN'] ?? '',
                            ),
                            const Divider(),
                            ListItemFactory.createYesNoSection(
                              title: '申辩是否成立：',
                              groupValue: chooseType,
                              isEdit: true,
                              isRequired: true,
                              horizontalPadding: 5,
                              verticalPadding: 0,
                              text: '${form['INSPECTION_SUBJECT'] ?? ''}现场检查记录',
                              onChanged: (val) {
                                setState(() {
                                  chooseType = val;
                                  INSPECTION_STATUS = val == true ? '-2' : '3';
                                });
                              },
                            ),
                            if (INSPECTION_STATUS == '3')
                              Column(
                                children: [
                                  const Divider(),
                                  ItemListWidget.multiLineTitleTextField(
                                    label: '不成立理由',
                                    isEditable: true,
                                    hintText: '请输入理由',
                                    onChanged: (val) {
                                      setState(() {
                                        form['INSPECTED_EXPLAIN_REFUSE'] = val;
                                      });
                                    },
                                  ),
                                  const Divider(),
                                  ItemListWidget.itemContainer(
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        ListItemFactory.headerTitle('确认人'),
                                        CustomButton(
                                          text: '手写签字',
                                          height: 36,
                                          backgroundColor: Colors.green,
                                          onPressed: () {
                                            _sign();
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                  if (signImages.isNotEmpty) _signListWidget(),
                                ],
                              ),
                          ],
                        ),
                      ),
                    ),
                    CustomButton(
                      text: INSPECTION_STATUS == '3' ? '提交' : '确认',
                      backgroundColor: Colors.blue,
                      onPressed: () {
                        _submit();
                      },
                    ),
                  ],
                )
                : SizedBox(),
      ),
    );
  }
}
