import 'dart:io';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';

import '../../../../../customWidget/custom_alert_dialog.dart';
import '../../../../../customWidget/picker/CupertinoDatePicker.dart';
import '../../../../../customWidget/single_image_viewer.dart';

class HomeGasTestPage extends StatefulWidget {
  const HomeGasTestPage({Key? key, required this.HOTWORK_ID}) : super(key: key);

  final String HOTWORK_ID;

  @override
  _HomeGasTestPageState createState() => _HomeGasTestPageState();
}

class _HomeGasTestPageState extends State<HomeGasTestPage> {
  String _selectData = '';
  List<String> imagePaths = [];
  List<String> signTimes = []; // 签字时间列表

  final TextEditingController _gasController = TextEditingController();
  final TextEditingController _resultController = TextEditingController();
  final TextEditingController _addressController = TextEditingController();
  bool _loading = false;

  @override
  void initState() {
    super.initState();
  }

  Future<void> _chooseDatePicker() async {
    DateTime? picked = await BottomDateTimePicker.showDate(context);
    if (picked != null) {
      setState(() {
        _selectData = DateFormat('yyyy-MM-dd HH:mm').format(picked);
      });
    }
  }

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

  Future<void> _submit(int status) async {
    if (imagePaths.isEmpty) {
      ToastUtil.showNormal(context, '请签字');
      return;
    }
    if (status == 1) {
      if (_selectData.isEmpty ||
          _gasController.text.isEmpty ||
          _resultController.text.isEmpty ||
          _addressController.text.isEmpty) {
        ToastUtil.showNormal(context, '请完善所有字段');
        return;
      }
    }

    String reasonText = '';
    if (status != 1) {
      reasonText = await CustomAlertDialog.showInput(
        context,
        title: '作废原因',
        hintText: '请输入作废原因',
        cancelText: '取消',
        confirmText: '确定',
      );
      if (reasonText.isEmpty) {
        ToastUtil.showNormal(context, '请填写作废原因');
        return;
      }
    }
    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请确认' + (status == 1 ? "通过" : "作废") + '本作业票？',
      cancelText: '取消',
      confirmText: '确定',
      barrierDismissible: false,
    );
    if (!confirmed) return;

    setState(() => _loading = true);

    final formData = {
      'HOTWORK_ID': widget.HOTWORK_ID,
      'ANALYZE_TIME': _selectData,
      'ANALYZE_GAS': _gasController.text,
      'ANALYZE_RESULT': _resultController.text,
      'ANALYZE_PLACE': _addressController.text,
      'ANALYZE_USER': SessionService.instance.username,
      'APPLY_STATUS': status,
      'STEP_REASON': reasonText ?? '',
      'SIGNTIME': signTimes.join(','),
      'CORPINFO_ID': SessionService.instance.corpinfoId,
      'USER_ID': SessionService.instance.loginUserId,
    };

    try {
      await ApiService.saveGasTest('hotwork', formData, imagePaths);
      ToastUtil.showNormal(context, status == 1 ? '保存成功' : '作废成功');
      Navigator.of(context).pop(status == 1);
    } catch (e) {
      ToastUtil.showNormal(context, e.toString());
    } finally {
      setState(() => _loading = false);
    }
  }

  Future<void> setRequest() async {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '气体检测'),
      body: SafeArea(
        child:
            _loading
                ? const Center(child: CircularProgressIndicator())
                : SingleChildScrollView(
                  padding: const EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Column(
                          children: [
                            ItemListWidget.selectableLineTitleTextRightButton(
                              label: '分析时间',
                              isEditable: true,
                              text: _selectData,
                              onTap: _chooseDatePicker,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '代表性气体：',
                              hintText: '请输入代表性气体',
                              isEditable: true,
                              controller: _gasController,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '分析结果：',
                              isEditable: true,
                              controller: _resultController,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '分析地点：',
                              isEditable: true,
                              controller: _addressController,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '分析人：',
                              isEditable: false,
                              text: SessionService.instance.username,
                            ),
                            const SizedBox(height: 20),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                CustomButton(
                                  text: '新增手写签字',
                                  height: 40,
                                  backgroundColor: Colors.blue,
                                  onPressed: _sign,
                                ),
                              ],
                            ),
                            if (imagePaths.isNotEmpty) _signListWidget(),
                          ],
                        ),
                      ),
                      const SizedBox(height: 20),
                      Row(
                        children: [
                          Expanded(
                            child: CustomButton(
                              text: '作废',
                              backgroundColor: Colors.red,
                              onPressed: () => _submit(-1),
                            ),
                          ),
                          const SizedBox(width: 20),
                          Expanded(
                            child: CustomButton(
                              text: '保存',
                              backgroundColor: Colors.blue,
                              onPressed: () => _submit(1),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
      ),
    );
  }
}
