import 'package:flutter/material.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/pages/home/tap/tabList/special_wrok/sxkj_work/qtfx_work_detail/spacework_gas_list.dart';
import 'package:qhd_prevention/tools/h_colors.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';

/// 气体分析
class SpaceworkGasEdit extends StatefulWidget {
  const SpaceworkGasEdit({
    super.key,
    required this.CONFINEDSPACE_ID,
    this.addFlag = false,
  });

  final String CONFINEDSPACE_ID;
  final bool addFlag;

  @override
  State<SpaceworkGasEdit> createState() => _SpaceworkGasEditState();
}

class _SpaceworkGasEditState extends State<SpaceworkGasEdit> {
  Map<String, dynamic> pd = {};
  final TextEditingController _gasName1Controller = TextEditingController();
  final TextEditingController _gasName2Controller = TextEditingController();
  final TextEditingController _gasName3Controller = TextEditingController();
  final TextEditingController _gasName4Controller = TextEditingController();
  final TextEditingController _gasStandard1Controller = TextEditingController();
  final TextEditingController _gasStandard2Controller = TextEditingController();
  final TextEditingController _gasStandard3Controller = TextEditingController();
  final TextEditingController _gasStandard4Controller = TextEditingController();

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

  Future<void> _getData() async {
    try {
      final result = await ApiService.getConfinedspacegaswh(widget.CONFINEDSPACE_ID);
      if (FormUtils.hasValue(result, 'pd')) {
        setState(() {
          pd = result['pd'];
          _gasName1Controller.text = pd['GAS_NAME1'] ?? '';
          _gasStandard1Controller.text = pd['GAS_STANDARD1'] ?? '';
          _gasName2Controller.text = pd['GAS_NAME2'] ?? '';
          _gasStandard2Controller.text = pd['GAS_STANDARD2'] ?? '';
          _gasName3Controller.text = pd['GAS_NAME3'] ?? '';
          _gasStandard3Controller.text = pd['GAS_STANDARD3'] ?? '';
          _gasName4Controller.text = pd['GAS_NAME4'] ?? '';
          _gasStandard4Controller.text = pd['GAS_STANDARD4'] ?? '';
        });
      }
    } catch (e) {
      ToastUtil.showNormal(context, '获取数据失败: \$e');
    }
  }

  Future<void> _gasAnalyze() async {
    // 清理旧的气体信息，避免遗留空字段
    for (var key in [
      'GAS_NAME1', 'GAS_STANDARD1',
      'GAS_NAME2', 'GAS_STANDARD2',
      'GAS_NAME3', 'GAS_STANDARD3',
      'GAS_NAME4', 'GAS_STANDARD4'
    ]) {
      pd.remove(key);
    }

    // 收集输入值，仅在非空时写入 pd
    void assignIfNotEmpty(String key, String value) {
      if (value.trim().isNotEmpty) pd[key] = value.trim();
    }

    assignIfNotEmpty('GAS_NAME1', _gasName1Controller.text);
    assignIfNotEmpty('GAS_STANDARD1', _gasStandard1Controller.text);
    assignIfNotEmpty('GAS_NAME2', _gasName2Controller.text);
    assignIfNotEmpty('GAS_STANDARD2', _gasStandard2Controller.text);
    assignIfNotEmpty('GAS_NAME3', _gasName3Controller.text);
    assignIfNotEmpty('GAS_STANDARD3', _gasStandard3Controller.text);
    assignIfNotEmpty('GAS_NAME4', _gasName4Controller.text);
    assignIfNotEmpty('GAS_STANDARD4', _gasStandard4Controller.text);

    // 固定字段
    pd['CONFINEDSPACE_ID'] = widget.CONFINEDSPACE_ID;
    pd['ANALYZE_USER'] = SessionService.instance.username;

    // 校验至少填写了一项气体名称
    final hasAnyName = pd.containsKey('GAS_NAME1') || pd.containsKey('GAS_NAME2') ||
        pd.containsKey('GAS_NAME3') || pd.containsKey('GAS_NAME4');
    if (!hasAnyName) {
      ToastUtil.showNormal(context,
          widget.addFlag ? '最少填写一项气体名称' : '无气体检测信息');
      return;
    }

    // 配对校验：有名称必须有标准，反之亦然
    void checkPair(String nameKey, String stdKey, String label) {
      final hasName = pd.containsKey(nameKey);
      final hasStd = pd.containsKey(stdKey);
      if (hasName && !hasStd) {
        ToastUtil.showNormal(context, '请输入$label 的合格标准');
        throw '';
      }
      if (!hasName && hasStd) {
        ToastUtil.showNormal(context, '请输入$label 的名称');
        throw '';
      }
    }

    try {
      checkPair('GAS_NAME1', 'GAS_STANDARD1', '有毒有害气体名称1');
      checkPair('GAS_NAME2', 'GAS_STANDARD2', '有毒有害气体名称2');
      checkPair('GAS_NAME3', 'GAS_STANDARD3', '可燃气体名称1');
      checkPair('GAS_NAME4', 'GAS_STANDARD4', '可燃气体名称2');
    } catch (_) {
      return;
    }

    // 提交
    final isEdit = pd.containsKey('CONFINEDSPACEGASWH_ID') &&
        pd['CONFINEDSPACEGASWH_ID'] != null;
    final url = isEdit ? '/app/confinedspacegaswh/edit' : '/app/confinedspacegaswh/add';
    try {
      LoadingDialogHelper.show();
      final res = await ApiService.submitSpaceGas(url, pd);
      LoadingDialogHelper.hide();
      if (res != null && res['result'] == 'success') {

        Map<String, dynamic> arguments = {
              'isShow': widget.addFlag,
              'CONFINEDSPACE_ID': widget.CONFINEDSPACE_ID,
              'addFlag': 1,
              'GAS_NAME1': pd['GAS_NAME1'] ?? '',
              'GAS_NAME2': pd['GAS_NAME2'] ?? '',
              'GAS_NAME3': pd['GAS_NAME3'] ?? '',
              'GAS_NAME4': pd['GAS_NAME4'] ?? '',
            };
        pushPage(SpaceworkGasList(CONFINEDSPACE_ID: widget.CONFINEDSPACE_ID, saveParams: arguments,addFlag: true,), context);
      } else {
        ToastUtil.showNormal(context, res['message'] ?? '提交失败');
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      ToastUtil.showNormal(context, '提交异常: $e');
    }
  }

  Widget _card(Widget child) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 5),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
      ),
      child: child,
    );
  }

  Widget _buildListContent() {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: SingleChildScrollView(
        child: Column(
          children: [
            _card(
              Column(
                children: [
                  ItemListWidget.selectableLineTitleTextField(
                    label: '有毒有害气体名称1：',
                    isEditable: true,
                    controller: _gasName1Controller,
                    text: '',
                  ),
                  const Divider(),
                  ItemListWidget.selectableLineTitleTextField(
                    label: '合格标准：',
                    isEditable: true,
                    controller: _gasStandard1Controller,
                    text: '',
                  ),
                ],
              ),
            ),
            const SizedBox(height: 12),
            _card(
              Column(
                children: [
                  ItemListWidget.selectableLineTitleTextField(
                    label: '有毒有害气体名称2：',
                    isEditable: true,
                    controller: _gasName2Controller,
                    text: '',
                  ),
                  const Divider(),
                  ItemListWidget.selectableLineTitleTextField(
                    label: '合格标准：',
                    isEditable: true,
                    controller: _gasStandard2Controller,
                    text: '',
                  ),
                ],
              ),
            ),
            const SizedBox(height: 12),
            _card(
              Column(
                children: [
                  ItemListWidget.selectableLineTitleTextField(
                    label: '可燃气体名称1：',
                    isEditable: true,
                    controller: _gasName3Controller,
                    text: '',
                  ),
                  const Divider(),
                  ItemListWidget.selectableLineTitleTextField(
                    label: '合格标准：',
                    isEditable: true,
                    controller: _gasStandard3Controller,
                    text: '',
                  ),
                ],
              ),
            ),
            const SizedBox(height: 12),
            _card(
              Column(
                children: [
                  ItemListWidget.selectableLineTitleTextField(
                    label: '可燃气体名称2：',
                    isEditable: true,
                    controller: _gasName4Controller,
                    text: '',
                  ),
                  const Divider(),
                  ItemListWidget.selectableLineTitleTextField(
                    label: '合格标准：',
                    isEditable: true,
                    controller: _gasStandard4Controller,
                    text: '',
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            CustomButton(
              text: '气体分析',
              backgroundColor: Colors.green,
              onPressed: _gasAnalyze,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: h_backGroundColor(),
      appBar: MyAppbar(title: '气体名称'),
      body: SafeArea(child: _buildListContent()),
    );
  }
}
