import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.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/NFC/home_nfc_check_danger_page.dart';
import 'package:qhd_prevention/pages/home/NFC/nfc_question_fecebook.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/services/nfc_service.dart';
import 'package:qhd_prevention/tools/tools.dart';

class HomeNfcDetailPage extends StatefulWidget {
  const HomeNfcDetailPage({
    super.key,
    required this.info,
    required this.isEdit,
  });

  final Map info;
  final bool isEdit;

  @override
  State<HomeNfcDetailPage> createState() => _HomeNfcDetailPageState();
}

class _HomeNfcDetailPageState extends State<HomeNfcDetailPage> {
  List<dynamic> items = [];
  int currentPage = 1;
  final int pageSize = 10;
  late var _total = 0;
  late var _totalResult = 0;

  bool isLoading = false; // 当前请求中
  bool hasMore = true; // 是否还有更多数据
  bool firstLoad = true; // 第一次加载标志

  final ScrollController _scrollController = ScrollController();

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

    // 监听滚动到底部触发加载更多
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent - 200 &&
          !isLoading &&
          hasMore) {
        _getTaskDetail(); // 加载下一页
      }
    });
  }

  Future<void> _loadInitial() async {
    await _getTaskDetail(refresh: true);
    firstLoad = false;
  }

  /// pageSize: 每页条数；currentPage 初始为 1
  Future<void> _getTaskDetail({bool refresh = false}) async {
    if (isLoading) return;
    setState(() {
      isLoading = true;
    });

    if (refresh) {
      currentPage = 1;
      hasMore = true;
    }

    try {
      Map data = {
        "PATROL_TASK_ID": widget.info['PATROL_TASK_ID'] ?? '',
        "PERIOD_START_TIME": widget.info['PERIOD_START_TIME'] ?? '',
        "PERIOD_END_TIME": widget.info['PERIOD_END_TIME'] ?? '',
      };
      final result = await ApiService.nfcTaskDetailList(
        pageSize,
        currentPage,
        data,
      );

      if (result == null) {
        _showMessage('请求失败：结果为 null');
        return;
      }
      printLongString(jsonEncode(result));
      if (result['result'] == 'success') {
        final dynamic rawList = result['varList'];
        setState(() {
          Map page = result['page'];
          _totalResult = page['totalResult'] as int;
          _total = result['checkedCount'] as int;
          if (refresh) {
            items = rawList;
          } else {
            items.addAll(rawList);
          }
          // 如果本次返回少于 pageSize 则说明没有更多
          if (rawList.length < pageSize) {
            hasMore = false;
          } else {
            currentPage++;
          }
        });
      } else {
        final msg = result['message'] ?? result['msg'] ?? '加载失败';
        _showMessage('请求出错：$msg');
      }
    } catch (e) {
      _showMessage('请求异常：$e');
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void _showMessage(String msg) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
  }

  Future<void> _startCheckItem(Map item, int index) async {
    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '温馨提示',
      content: '请将手机贴近设备标签',
      cancelText: '',
      confirmText: '我知道了',
      barrierDismissible: false,
    );
    if (confirmed) {
      LoadingDialogHelper.show(message: '等待设备靠近设备NFC标签');
      NfcService.instance.startScanOnceWithCallback(
        onResult: (uid, parsedText, rawMsg) async {
          _getNFCForUid(uid, parsedText);
        },
        onError: (err) {
          ToastUtil.showError(context, '$err');
          LoadingDialogHelper.hide();
        },
        timeout: Duration(seconds: 12),
      );
    }
  }

  Future<void> _getNFCForUid(String uid, String parsedText) async {
    if (uid.isEmpty || parsedText.isEmpty) {
      ToastUtil.showError(context, 'NFC设备标签数据为空');
      LoadingDialogHelper.hide();

      return;
    }
    Map result = {};
    // mapToCompactJson({'PIPELINE_AREA_ID':pd['PIPELINE_AREA_ID'],'EQUIPMENT_PIPELINE_ID':pd['EQUIPMENT_PIPELINE_ID']}),
    for (Map item in items) {
      if (parsedText.isNotEmpty && item['NFC_CODE'] == uid) {
        try {
          Map parsedData = jsonDecode(parsedText);
          if (parsedData['PIPELINE_AREA_ID'] == item['PIPELINE_AREA_ID'] &&
              parsedData['EQUIPMENT_PIPELINE_ID'] ==
                  item['EQUIPMENT_PIPELINE_ID']) {
            result = item;
          }
          LoadingDialogHelper.hide();
        } catch (e) {
          LoadingDialogHelper.hide();

          ToastUtil.showError(context, 'NFC设备数据错误');
        }
      }
    }
    if (result.isEmpty) {
      LoadingDialogHelper.hide();

      ToastUtil.showError(context, 'NFC设备不在当前任务中');
      return;
    }
    LoadingDialogHelper.hide();

    Map data = {
      ...result,
      ...widget.info,
      "NFC_CODE": uid,
      'MANUAL_CONFIRMATION': '0',
    };
    await pushPage(
      HomeNfcCheckDangerPage(info: data, facebookImages: [], isNfcError: false, isEdit: widget.isEdit,),
      context,
    );
    _getTaskDetail(refresh: true);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Widget _pendingTopCard(Map item) {
    return SizedBox(
      height: 180,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 背景图片（上部）
          ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.asset(
              'assets/images/xj_top.png',
              height: 70,
              width: double.infinity,
              fit: BoxFit.cover,
            ),
          ),

          // 标题 & 状态标签
          Positioned(
            top: 12,
            left: 12,
            child: Text(
              item['TASK_NAME']?.toString() ?? '',
              style: const TextStyle(
                color: Colors.black87,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Positioned(
            top: 12,
            right: 12,
            child: Container(
              height: 30,
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.3),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Center(
                child: Center(
                  child: Text(
                    item['PATROL_TYPE_NAME'] ?? '',
                    style: TextStyle(
                      color: Colors.blue,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
          ),

          // 白色信息区域（覆盖图片底部）
          Positioned(
            left: 0,
            right: 0,
            top: 50, // 覆盖图片底部
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 0),
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: const [
                  BoxShadow(
                    color: Colors.black12,
                    blurRadius: 4,
                    offset: Offset(0, 1),
                  ),
                ],
              ),
              child: _buildInfoGrid(item),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建信息网格
  Widget _buildInfoGrid(Map item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // const SizedBox(height: 8),
        ItemListWidget.singleLineTitleText(
          label: '负责部门',
          isEditable: false,
          text: item['DEPARTMENT_NAME'] ?? '',
        ),
        ItemListWidget.singleLineTitleText(
          label: '负责人',
          isEditable: false,
          text: item['USER_NAME'] ?? '',
        ),
        ItemListWidget.singleLineTitleText(
          // maxLines: 1,
          label: '涉及管道区域:',
          isEditable: false,
          text: item['PIPELINE_AREAS_NAMES'] ?? '',
        ),
        ItemListWidget.singleLineTitleText(
          label: '巡检周期',
          isEditable: false,
          text: item['PATROL_PERIOD_NAME'] ?? '',
        ),
        ItemListWidget.singleLineTitleText(
          label: '任务时间',
          isEditable: false,
          text: item['OPERATTIME'] ?? '',
        ),
      ],
    );
  }

  Widget _buildListItem(BuildContext context, int idx) {
    final item = items[idx];
    final bool unchecked = item['INSPECTED_FLAG'] == '0';

    return Container(
      height: widget.isEdit ? 100 : 80,
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          // 左侧状态区
          Column(
            children: [
              Stack(
                alignment: Alignment.center,
                children: [
                  Image.asset(
                    unchecked
                        ? 'assets/images/xj_wait.png'
                        : 'assets/images/xj_finish.png',
                    width: 50,
                    height: 30,
                    fit: BoxFit.cover,
                  ),
                  Positioned(
                    top: 2,
                    child: Text(
                      unchecked ? '未查' : '已查',
                      style: const TextStyle(color: Colors.white, fontSize: 14),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Image.asset('assets/images/xjjd_top.png', width: 15, height: 30),
            ],
          ),

          const SizedBox(width: 20),

          // 中间详情
          Expanded(
            child: GestureDetector(
              onTap: () async {
                if (!unchecked) {
                  Map data = {
                    ...item,
                    ...widget.info,
                    "NFC_CODE": item['PIPELINE_AREA_ID'],
                    'MANUAL_CONFIRMATION': '0',
                  };
                  await pushPage(
                    HomeNfcCheckDangerPage(
                      info: data,
                      facebookImages: [],
                      isNfcError: false,
                      isEdit: widget.isEdit,
                    ),
                    context,
                  );
                  _getTaskDetail(refresh: true);

                }
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    item['PIPELINE_AREA_NAME'] ?? '',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1, // 最多一行
                    overflow: TextOverflow.ellipsis, // 超出省略号
                  ),
                  const SizedBox(height: 4),
                  Text('NFC编码：${item['NFC_CODE'] ?? ''}'),
                  const SizedBox(height: 6),
                  unchecked
                      ? widget.isEdit
                          ? Row(
                            spacing: 10,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                child: InkWell(
                                  onTap: () => _startCheckItem(item, idx),
                                  child: Container(
                                    height: 35,
                                    // width: 120,
                                    alignment: Alignment.center,
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 1,
                                    ),
                                    decoration: BoxDecoration(
                                      gradient: const LinearGradient(
                                        colors: [
                                          Color(0xFFFFA726),
                                          Color(0xFFFF7043),
                                        ],
                                      ),
                                      borderRadius: BorderRadius.circular(5),
                                    ),
                                    child: const Text(
                                      'NFC检查',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              CustomButton(
                                onPressed: ()  async {
                                  await pushPage(
                                    NfcQuestionFecebook(
                                      info: item,
                                      taskInfo: widget.info,
                                    ),
                                    context,
                                  );
                                  _getTaskDetail(refresh: true);

                                },
                                text: '手动检查',
                                height: 35,
                                textStyle: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                ),
                                backgroundColor: Colors.blue,
                              ),
                            ],
                          )
                          : const SizedBox()
                      : Text(
                        '检查时间：${item['PATROL_TIME'] ?? ''}',
                        style: const TextStyle(fontSize: 14),
                        textAlign: TextAlign.center,
                      ),
                ],
              ),
            ),
          ),

          // 右侧箭头
          const SizedBox(width: 8),
          if (!unchecked) const Icon(Icons.chevron_right, color: Colors.grey),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: '任务详情'),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              _pendingTopCard(widget.info),
              const SizedBox(height: 60),

              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    boxShadow: const [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 4,
                        offset: Offset(0, 1),
                      ),
                    ],
                  ),
                  // 白色容器内部：统计行 + 列表（统计行放在列表顶部）
                  child: Column(
                    children: [
                      // 统计行（放在容器顶部，作为视觉上的头部）
                      Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 10,
                        ),
                        child: Builder(
                          builder: (context) {
                            return Container(
                              width: double.infinity,
                              padding: const EdgeInsets.symmetric(
                                horizontal: 5,
                                vertical: 8,
                              ),

                              child: Row(
                                children: [
                                  Text(
                                    '已查点位 $_total / $_totalResult ',
                                    style: const TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  const Spacer(),
                                  if (isLoading)
                                    const SizedBox(
                                      width: 18,
                                      height: 18,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                      ),
                                    )
                                  else
                                    GestureDetector(
                                      onTap:
                                          () => _getTaskDetail(refresh: true),
                                      child: Row(
                                        children: const [
                                          Icon(
                                            Icons.refresh,
                                            size: 16,
                                            color: Colors.grey,
                                          ),
                                          SizedBox(width: 4),
                                          Text(
                                            '刷新',
                                            style: TextStyle(
                                              fontSize: 12,
                                              color: Colors.grey,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                ],
                              ),
                            );
                          },
                        ),
                      ),

                      // 列表区域（占用剩余空间）
                      Expanded(
                        child: RefreshIndicator(
                          onRefresh: () => _getTaskDetail(refresh: true),
                          child:
                              firstLoad && isLoading
                                  ? const Center(
                                    child: Padding(
                                      padding: EdgeInsets.all(16.0),
                                      child: CircularProgressIndicator(),
                                    ),
                                  )
                                  : items.isEmpty
                                  ? ListView(
                                    // 保持可下拉刷新
                                    controller: _scrollController,
                                    physics:
                                        const AlwaysScrollableScrollPhysics(),
                                    children: [
                                      const SizedBox(height: 40),
                                      Center(
                                        child: Text(
                                          isLoading ? '加载中...' : '暂无数据',
                                        ),
                                      ),
                                    ],
                                  )
                                  : ListView.builder(
                                    controller: _scrollController,
                                    physics:
                                        const AlwaysScrollableScrollPhysics(),
                                    itemCount:
                                        items.length + 1, // 多一个用于加载状态/底部提示
                                    itemBuilder: (ctx, idx) {
                                      if (idx < items.length) {
                                        return _buildListItem(ctx, idx);
                                      } else {
                                        // 底部加载/没有更多提示
                                        if (hasMore) {
                                          return const Padding(
                                            padding: EdgeInsets.symmetric(
                                              vertical: 12,
                                            ),
                                            child: Center(
                                              child:
                                                  CircularProgressIndicator(),
                                            ),
                                          );
                                        } else {
                                          return const Padding(
                                            padding: EdgeInsets.symmetric(
                                              vertical: 12,
                                            ),
                                            child: Center(child: Text('没有更多了')),
                                          );
                                        }
                                      }
                                    },
                                  ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
