import 'dart:io';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/sxkj_work/qtfx_work_detail/spacework_gas_list.dart';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.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/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';

class SpaceworkGasTestPage extends StatefulWidget {
  const SpaceworkGasTestPage({
    Key? key,
    required this.CONFINEDSPACE_ID,
    this.saveParams = const {},
  }) : super(key: key);

  final Map<String, dynamic> saveParams;
  final String CONFINEDSPACE_ID;

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

class _SpaceworkGasTestPageState extends State<SpaceworkGasTestPage> {
  String _selectData = '';
  List<String> imagePaths = [];
  List<String> signTimes = []; // 签字时间列表
  Map<String, dynamic> pd = {};
  final TextEditingController _PartController = TextEditingController(); // 部位
  final TextEditingController _O2Controller = TextEditingController(); // 结果
  final TextEditingController _addressController =
      TextEditingController(); // 地点

  final TextEditingController _gas1Controller = TextEditingController(); // 地点
  final TextEditingController _gas2Controller = TextEditingController(); // 地点
  final TextEditingController _gas3Controller = TextEditingController(); // 地点
  final TextEditingController _gas4Controller = TextEditingController(); // 地点

  bool _loading = false;

  @override
  void initState() {
    super.initState();
    pd['ANALYZE_USER'] = SessionService.instance.username;
    pd['CONFINEDSPACE_ID'] = widget.CONFINEDSPACE_ID;
  }

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

  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) {
        ToastUtil.showNormal(context, '请选择取样分析时间');
        return;
      }
      if (_PartController.text.isEmpty ||
          _O2Controller.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;
      }
    }
    if (FormUtils.hasValue(widget.saveParams, 'GAS_NAME1')) {
      if (_gas1Controller.text.trim().isEmpty) {
        pd['DATA1'] = 0;
      } else {
        pd['DATA1'] = _gas1Controller.text;
      }
    }
    if (FormUtils.hasValue(widget.saveParams, 'GAS_NAME2')) {
      if (_gas2Controller.text.trim().isEmpty) {
        pd['DATA2'] = 0;
      } else {
        pd['DATA2'] = _gas2Controller.text;
      }
    }
    if (FormUtils.hasValue(widget.saveParams, 'GAS_NAME3')) {
      if (_gas3Controller.text.trim().isEmpty) {
        pd['DATA3'] = 0;
      } else {
        pd['DATA3'] = _gas3Controller.text;
      }
    }
    if (FormUtils.hasValue(widget.saveParams, 'GAS_NAME4')) {
      if (_gas4Controller.text.trim().isEmpty) {
        pd['DATA4'] = 0;
      } else {
        pd['DATA4'] = _gas4Controller.text;
      }
    }

    bool isConfirm = false;

    setState(() => _loading = true);

    final formData = {
      ...pd,
      'ANALYZE_PART': _PartController.text,
      'OXYGEN_CONTENT': _O2Controller.text,
      'ANALYZE_PLACE': _addressController.text,
      'APPLY_STATUS': status,
      'STEP_REASON': reasonText ?? '',
      'SIGNTIME': signTimes.join(','),
      'CORPINFO_ID': SessionService.instance.corpinfoId,
      'USER_ID': SessionService.instance.loginUserId,
    };
    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请确认' + (status == 1 ? "通过" : "作废") + '本作业票？',
      cancelText: '取消',
      confirmText: '确定',
      barrierDismissible: false,
    );
    if (!confirmed) return;

    try {
      await ApiService.saveGasTest('confinedspace',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: [
                            if (FormUtils.hasValue(
                              widget.saveParams,
                              'GAS_NAME1',
                            ))
                              Column(
                                children: [
                                  ItemListWidget.singleLineTitleText(
                                    label: '${widget.saveParams['GAS_NAME1']}：',
                                    isEditable: true,
                                    isRequired: false,
                                    strongRequired: false,
                                    controller: _gas1Controller,
                                  ),
                                  const Divider(),
                                ],
                              ),
                            if (FormUtils.hasValue(
                              widget.saveParams,
                              'GAS_NAME2',
                            ))
                              Column(
                                children: [
                                  ItemListWidget.singleLineTitleText(
                                    label: '${widget.saveParams['GAS_NAME2']}：',
                                    isEditable: true,
                                    isRequired: false,
                                    strongRequired: false,
                                    controller: _gas2Controller,
                                  ),
                                  const Divider(),
                                ],
                              ),
                            if (FormUtils.hasValue(
                              widget.saveParams,
                              'GAS_NAME3',
                            ))
                              Column(
                                children: [
                                  ItemListWidget.singleLineTitleText(
                                    label: '${widget.saveParams['GAS_NAME3']}：',
                                    isEditable: true,
                                    isRequired: false,
                                    strongRequired: false,
                                    controller: _gas3Controller,
                                  ),
                                  const Divider(),
                                ],
                              ),
                            if (FormUtils.hasValue(
                              widget.saveParams,
                              'GAS_NAME4',
                            ))
                              Column(
                                children: [
                                  ItemListWidget.singleLineTitleText(
                                    label: '${widget.saveParams['GAS_NAME4']}：',
                                    isEditable: true,
                                    isRequired: false,
                                    strongRequired: false,
                                    controller: _gas4Controller,
                                  ),
                                  const Divider(),
                                ],
                              ),

                            ItemListWidget.selectableLineTitleTextRightButton(
                              label: '取样分析时间',
                              isEditable: true,
                              text: _selectData,
                              onTap: _chooseDatePicker,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '分析部位：',
                              hintText: '请输入分析部位',
                              isEditable: true,
                              controller: _PartController,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '氧气含量：',
                              hintText: '请输入氧气含量',
                              isEditable: true,
                              controller: _O2Controller,
                            ),

                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '分析地点：',
                              hintText: '请输入分析地点',
                              isEditable: true,
                              controller: _addressController,
                            ),
                            const Divider(),
                            ItemListWidget.singleLineTitleText(
                              label: '分析人：',
                              isEditable: false,
                              strongRequired: true,
                              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),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
      ),
    );
  }
}
