import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/sxkj_work/qtfx_work_detail/spacework_gas_test_page.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 '../../home_gas_test_page.dart';
/// 气体分析详情
class SpaceworkGasList extends StatefulWidget {
   SpaceworkGasList({
    super.key,
    required this.CONFINEDSPACE_ID,
    this.addFlag = false,
    this.saveParams = const {},
  });
  Map<String, dynamic> saveParams;
  final String CONFINEDSPACE_ID;
  final bool addFlag;

  @override
  State<SpaceworkGasList> createState() => _SpaceworkGasListState();
}

class _SpaceworkGasListState extends State<SpaceworkGasList> {
  late List list = [];
  bool isLoading = true;

  Future<void> _getListData() async {

    final data = await ApiService.workGasList('confinedspace' ,widget.CONFINEDSPACE_ID);
    setState(() {
      list = data['varList'] ?? [];
      isLoading = false;
    });
  }

  void _deleteItem(String id) async {
    final ok = await CustomAlertDialog.showConfirm(
      context,
      title: '温馨提示',
      content: '确定要删除这条记录？',
      cancelText: '取消',
    );
    if (ok) {
      final result = await ApiService.workGasDelete('electricity',id);
      if (result['result'] == 'success') {
        _getListData();
        ToastUtil.showNormal(context, '删除成功');
      }
    }

  }


  Widget _buildListItem(Map item) {
    final images = (item['SIGN_PATH'] as String?)?.split(',') ?? [];
    final baseImgPath = ApiService.baseImgPath;

    return Container(
      color: Colors.white,
      margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 5),

      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('分析时间: ${item['ANALYZE_TIME'] ?? ''}'),
                Text('代表性气体: ${item['ANALYZE_GAS'] ?? ''}'),
              ],
            ),
            const SizedBox(height: 6),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('分析数据: ${item['ANALYZE_RESULT'] ?? ''}'),
                if ((item['ANALYZE_PLACE'] ?? '').toString().isNotEmpty)
                  Text('分析地点: ${item['ANALYZE_PLACE']}'),
              ],
            ),
            const SizedBox(height: 6),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text('分析人:'),
                const SizedBox(width: 8),
                Expanded(
                  child: Wrap(
                    spacing: 8,
                    runSpacing: 4,
                    children: List.generate(images.length, (i) {
                      final img = baseImgPath + images[i];
                      return GestureDetector(
                        onTap: () {
                          presentOpaque(
                            SingleImageViewer(imageUrl: img),
                            context,
                          );
                        },
                        child: Image.network(
                          img,
                          width: 50,
                          height: 30,
                          fit: BoxFit.fill,
                        ),
                      );
                    }),
                  ),
                ),
                if (widget.addFlag)
                  TextButton(
                    onPressed: () =>
                        _deleteItem(item['CONFINEDSPACEGAS_ID'].toString()),
                    style: TextButton.styleFrom(
                      backgroundColor: Colors.red,
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      minimumSize: const Size(0, 32),
                    ),
                    child: const Text(
                      '删除',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildListContent() {
    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (list.isEmpty) {
      return NoDataWidget.show();
    }

    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (context, index) {
        final item = list[index];
        return _buildListItem(item);
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _getListData();
  }
  void _pyshAddGas() async {
    await pushPage(SpaceworkGasTestPage(CONFINEDSPACE_ID: widget.CONFINEDSPACE_ID,saveParams: widget.saveParams,), context);
    _getListData();

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: MyAppbar(
        title: '受限空间气体分析详情',
        actions: [
          if (widget.addFlag)
            TextButton(
              onPressed: () {
                _pyshAddGas();
              },
              child: const Text('添加', style: TextStyle(color: Colors.white, fontSize: 16)),
            )
        ],
      ),
      body: _buildListContent(),
    );
  }
}
