import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:qhd_prevention/customWidget/BaiDuMap/BaiduMapWebView.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.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/app/danger_wait_list_page.dart';
import 'package:qhd_prevention/pages/app/detail_images_page.dart';
import 'package:qhd_prevention/pages/app/hidden_record_detail_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/services/location_service.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:webview_flutter/webview_flutter.dart';

class CheckRecordDetailPage extends StatefulWidget {
  const CheckRecordDetailPage(this.id, this.type, {super.key});

  final int type;
  final String id;

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

class _CheckRecordDetailPageState extends State<CheckRecordDetailPage> {
  // map markers
  List<Map<String, dynamic>> covers = [];
  double centerLat = 39.8883;
  double centerLng = 119.519;
  WebViewController? _controller;

  Map<String, dynamic> pd = {
    "LIST_NAME": "",
    "SCREENTYPENAME": "",
    "USERS": "",
    "CHECK_TIME": "",
    "DEPARTMENT_NAME": "",
    "POST_NAME": "",
    "PERIODNAME": "",
    "TYPENAME": "",
    "START_DATE": "",
    "END_DATE": "",
  };

  List<String> imageList = [];
  List<dynamic> varList = [];
  List<dynamic> hiddenList = [];

  bool _loadingDetail = true;
  bool _loadingDetailTwo = true;
  bool _loadingMap = true;

  @override
  void initState() {
    super.initState();
    // 启动时并行请求，UI 使用 setState 更新
    _fetchAll();
    _initLocation();
  }
  @override
  void dispose() {
    _controller = null;
    super.dispose();
  }
  Future<void> _fetchAll() async {
    // 并行发请求，界面加载更快
    await Future.wait([
      _getInspectRecordsDetail(),
      _getInspectRecordsDetailTwo(),
      _getMapData(),
    ]);
  }

  Future<void> _getMapData() async {
    setState(() => _loadingMap = true);
    try {
      Map data = {
        'USER_ID': SessionService.instance.loginUserId,
        'CORPINFO_ID': SessionService.instance.corpinfoId,
        'CHECKRECORD_ID': widget.id,
      };
      Map resData = {};
      if (widget.type == 1) {
        resData = await ApiService.getDangerRecordMapInfo(data);
      } else {
        resData = await ApiService.getNormalRecordMapInfo(data);
      }
      final built = buildCoversFromRes(resData);
      double lat = centerLat;
      double lng = centerLng;

      if (resData['cinfo'] != null) {
        final cinfo = resData['cinfo'];
        final latStr = (cinfo['LATITUDE'] ?? '').toString();
        final lngStr = (cinfo['LONGITUDE'] ?? '').toString();
        final parsedLat = double.tryParse(latStr);
        final parsedLng = double.tryParse(lngStr);
        if (parsedLat != null && parsedLng != null) {
          lat = parsedLat;
          lng = parsedLng;
        }
      }

      setState(() {
        covers = built;
        centerLat = lat;
        centerLng = lng;
        _loadingMap = false;
      });
    } catch (e, st) {
      debugPrint('getMapData error: $e\n$st');
      setState(() => _loadingMap = false);
    }
  }

  List<Map<String, dynamic>> buildCoversFromRes(Map res) {
    final list = <Map<String, dynamic>>[];

    final cinfo = res['cinfo'];
    if (cinfo != null &&
        cinfo['LONGITUDE'] != null &&
        cinfo['LATITUDE'] != null &&
        cinfo['LONGITUDE'].toString().isNotEmpty &&
        cinfo['LATITUDE'].toString().isNotEmpty) {
      final lat = double.tryParse(cinfo['LATITUDE'].toString());
      final lng = double.tryParse(cinfo['LONGITUDE'].toString());
      if (lat != null && lng != null) {
        list.add({
          'latitude': lat,
          'longitude': lng,
          'icon': '', // 可替换为网络图片或 data uri
          'data': {'type': 'cinfo'}
        });
      }
    }

    final check = res['checkrecord'];
    if (check != null &&
        check['LONGITUDE'] != null &&
        check['LATITUDE'] != null &&
        check['LONGITUDE'].toString().isNotEmpty &&
        check['LATITUDE'].toString().isNotEmpty) {
      final lat = double.tryParse(check['LATITUDE'].toString());
      final lng = double.tryParse(check['LONGITUDE'].toString());
      if (lat != null && lng != null) {
        list.add({
          'latitude': lat,
          'longitude': lng,
          'icon': '',
          'data': {'type': 'checkrecord'}
        });
      }
    }

    final vlist = (res['varList'] as List?) ?? [];
    for (final item in vlist) {
      try {
        if (item != null &&
            item['LONGITUDE'] != null &&
            item['LATITUDE'] != null &&
            item['LONGITUDE'].toString().isNotEmpty &&
            item['LATITUDE'].toString().isNotEmpty) {
          final lat = double.tryParse(item['LATITUDE'].toString());
          final lng = double.tryParse(item['LONGITUDE'].toString());
          if (lat != null && lng != null) {
            list.add({
              'latitude': lat,
              'longitude': lng,
              'icon': '',
              'data': {'type': 'varList', 'item': item}
            });
          }
        }
      } catch (_) {
        // 忽略单条解析错误
      }
    }

    return list;
  }

  Future<void> _getInspectRecordsDetail() async {
    setState(() => _loadingDetail = true);
    try {
      final Map<String, dynamic> result;
      if (widget.type == 1) {
        result = await ApiService.getInspectRecordsDetailYin(widget.id);
      } else {
        result = await ApiService.getInspectRecordsDetail(widget.id);
      }

      if (result['result'] == 'success') {
        final List<dynamic> qianmingList = result['qianming'] ?? [];
        // 清空旧数据，防止重复
        final List<String> newImages = [];
        for (final item in qianmingList) {
          final fp = item?["FILEPATH"]?.toString();
          if (fp != null && fp.isNotEmpty) newImages.add(fp);
        }
        setState(() {
          pd = (result['pd'] as Map<String, dynamic>?) ?? pd;
          varList = (result['varList'] as List<dynamic>?) ?? [];
          imageList = newImages;
          _loadingDetail = false;
        });
      } else {
        setState(() => _loadingDetail = false);
        ToastUtil.showNormal(context, "加载数据失败");
      }
    } catch (e, st) {
      debugPrint('getInspectRecordsDetail error: $e\n$st');
      setState(() => _loadingDetail = false);
      ToastUtil.showNormal(context, "加载数据失败");
    }
  }

  Future<void> _getInspectRecordsDetailTwo() async {
    setState(() => _loadingDetailTwo = true);
    try {
      final Map<String, dynamic> result;
      if (widget.type == 1) {
        result = await ApiService.getInspectRecordsDetailTwoYin(widget.id);
      } else {
        result = await ApiService.getInspectRecordsDetailTwo(widget.id);
      }

      if (result['result'] == 'success') {
        final List<dynamic> newList = (result['hiddenList'] as List?) ?? [];
        setState(() {
          hiddenList = newList;
          _loadingDetailTwo = false;
        });
      } else {
        setState(() => _loadingDetailTwo = false);
        ToastUtil.showNormal(context, "加载数据失败");
      }
    } catch (e, st) {
      debugPrint('getInspectRecordsDetailTwo error: $e\n$st');
      setState(() => _loadingDetailTwo = false);
      ToastUtil.showNormal(context, "加载数据失败");
    }
  }

  // UI 构建
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "检查记录详情"),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSectionTitle("检查内容"),
            _buildCheckContentTable(),
            _buildSectionTitle("其他隐患信息"),
            _buildOtherHiddenTable(),
            _buildMapSection(), // 注意这里地图高度已固定
            _buildSectionTitle("清单信息"),
            _buildInfoList(),
            _buildSignPhotos(),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
      child: Row(
        children: [
          Container(width: 4, height: 16, color: Colors.blue, margin: EdgeInsets.only(right: 10)),
          Text(title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
        ],
      ),
    );
  }

  Widget _buildCheckContentTable() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(border: Border.all(color: Colors.grey[300]!), borderRadius: BorderRadius.circular(4)),
      child: Table(
        border: TableBorder.all(color: Colors.grey[300]!),
        columnWidths: const {0: FlexColumnWidth(3), 1: FlexColumnWidth(1)},
        children: [
          TableRow(decoration: BoxDecoration(color: Colors.grey[100]), children: [
            _buildTableHeaderCell("检查内容"),
            _buildTableHeaderCell("状态"),
          ]),
          // 若 varList 为空，显示空行或提示
          if (varList.isEmpty)
            TableRow(children: [
              Padding(padding: EdgeInsets.all(12), child: Text("暂无检查内容")),
              SizedBox(),
            ])
          else
            ...varList.map((item) {
              final mi = (item is Map) ? item as Map<String, dynamic> : Map<String, dynamic>.from(item);
              return TableRow(children: [
                Padding(padding: EdgeInsets.all(8), child: Text(mi["CHECK_CONTENT"]?.toString() ?? "")),
                _buildStatusCell(mi),
              ]);
            }).toList(),
        ],
      ),
    );
  }

  Widget _buildStatusCell(Map<String, dynamic> item) {
    // 兼容字符串/数字类型
    final isnormalStr = item["ISNORMAL"]?.toString() ?? '';
    final imgCount = int.tryParse(item["IMGCOUNT"]?.toString() ?? '') ?? 0;

    String status;
    Color color = Colors.black;
    VoidCallback? onTap;

    if (isnormalStr == '0') {
      status = "合格";
      color = imgCount > 0 ? Colors.blue : Colors.black;
      if (imgCount > 0) onTap = () => _goToImgs(item["RECORDITEM_ID"]?.toString() ?? '');
    } else if (isnormalStr == '1') {
      status = "不合格";
      color = Colors.blue;
      onTap = () => _goToDetail(item["HIDDEN_ID"]?.toString() ?? '');
    } else if (isnormalStr == '2') {
      status = "不涉及";
      color = Colors.blue;
    } else {
      status = "存在未整改隐患";
      color = Colors.black;
    }

    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.all(8),
        child: Center(child: Text(status, style: TextStyle(color: color))),
      ),
    );
  }

  Widget _buildOtherHiddenTable() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      decoration: BoxDecoration(border: Border.all(color: Colors.grey[300]!), borderRadius: BorderRadius.circular(4)),
      child: Table(
        border: TableBorder.all(color: Colors.grey[300]!),
        columnWidths: const {0: FlexColumnWidth(3), 1: FlexColumnWidth(1)},
        children: [
          TableRow(decoration: BoxDecoration(color: Colors.grey[100]), children: [
            _buildTableHeaderCell("隐患描述"),
            _buildTableHeaderCell("操作"),
          ]),
          if (hiddenList.isEmpty)
            TableRow(children: [Padding(padding: EdgeInsets.all(12), child: Text("暂无数据")), SizedBox()])
          else
            ...hiddenList.map((item) {
              final mi = (item is Map) ? item as Map<String, dynamic> : Map<String, dynamic>.from(item);
              return TableRow(children: [
                Padding(padding: EdgeInsets.all(8), child: Text(mi["HIDDENDESCR"]?.toString() ?? "")),
                GestureDetector(
                  onTap: () => _goToDetail(mi["HIDDEN_ID"]?.toString() ?? ''),
                  child: Padding(
                    padding: EdgeInsets.all(8),
                    child: Center(child: Text("查看", style: TextStyle(color: Colors.blue))),
                  ),
                ),
              ]);
            }).toList(),
        ],
      ),
    );
  }
  /// 获取定位（并初始化 WebView 控制器）
  Future<void> _initLocation() async {

    // 允许多次赋值
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel('JS', onMessageReceived: (JavaScriptMessage message) {
        debugPrint('JS LOG: ${message.message}');
      })
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) async {
            debugPrint('网页加载完成: $url');
            await _injectLocationParams();
          },
          onWebResourceError: (err) {
            debugPrint('Web resource error: ${err.description}');
          },
        ),
      );

    // 加载页面（注意：如果 loadRequest 失败你可以捕获异常）
    try {
      await _controller!.loadRequest(Uri.parse('http://47.92.102.56:7811/file/fluteightmap/index.html'));

    } catch (e, st) {
      debugPrint('loadRequest 错误: $e\n$st');
    }
  }

  Future<void> _injectLocationParams() async {
    if (_controller == null) {
      debugPrint('_injectLocationParams: controller 为空，跳过注入');
      return;
    }

    final params = {
      'longitude': centerLng,
      'latitude': centerLat,
      'GSON': [],
      't': DateTime.now().millisecondsSinceEpoch,
    };

    final jsonParams = jsonEncode(params);

    try {
      await _controller!.runJavaScript('''
      (function(){
        try {
          if (typeof window.initWithData === 'function') {
            window.initWithData($jsonParams);
          } else if (typeof window.initMap === 'function') {
            window.initMap($jsonParams);
          } else {
            console.error('initWithData / initMap function not found');
          }
        } catch(e) {
          console.error('call initWithData error', e);
        }
      })();
    ''');
      debugPrint('已注入地图初始化参数');
    } catch (e) {
      debugPrint('注入位置参数失败: $e');
    }
  }

  Widget _buildTableHeaderCell(String text) {
    return Padding(padding: EdgeInsets.all(8), child: Center(child: Text(text, style: TextStyle(fontWeight: FontWeight.bold))));
  }

  Widget _buildMapSection() {
    // 给 webview 一个固定高度（与 uniapp 的 300px 对齐）
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: Container(
        height: 300,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(4), border: Border.all(color: Colors.grey[300]!)),
        child: _loadingMap
            ? Center(child: CircularProgressIndicator())
            : BaiduMapWebView(
          controller: _controller,
          isLoading: _loadingMap,
          errorMessage: null,
          onRetry: _initLocation,
        )
      ),
    );
  }

  Widget _buildInfoList() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(border: Border.all(color: Colors.grey[300]!), borderRadius: BorderRadius.circular(4)),
      child: Column(
        children: [
          _buildInfoRow("清单名称", pd["LIST_NAME"]?.toString() ?? ''),
          _buildInfoRow("排查清单类型", pd["SCREENTYPENAME"]?.toString() ?? ''),
          _buildInfoRow("检查人", pd["USERS"]?.toString() ?? ''),
          _buildInfoRow("检查时间", pd["CHECK_TIME"]?.toString() ?? ''),
          _buildInfoRow("所属部门", pd["DEPARTMENT_NAME"]?.toString() ?? ''),
          _buildInfoRow("所属岗位", pd["POST_NAME"]?.toString() ?? ''),
          _buildInfoRow("排查周期", pd["PERIODNAME"]?.toString() ?? ''),
          _buildInfoRow("清单类型", pd["TYPENAME"]?.toString() ?? ''),
          if (pd["TYPENAME"]?.toString() == "临时") _buildInfoRow("排查日期", "${pd["START_DATE"] ?? ''} - ${pd["END_DATE"] ?? ''}"),
        ],
      ),
    );
  }

  Widget _buildInfoRow(String title, String value) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
      decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey[300]!))),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text(title, style: TextStyle(fontSize: 14)),
        Text(value, style: TextStyle(fontSize: 14, color: Colors.grey[600])),
      ]),
    );
  }

  Widget _buildSignPhotos() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
      child: ListItemFactory.createTextImageItem(
        text: "签字照片",
        imageUrls: imageList,
        onImageTapped: (index) {
          presentOpaque(SingleImageViewer(imageUrl: ApiService.baseImgPath + imageList[index]), context);
        },
      ),
    );
  }

  void _goToDetail(String hiddenId) {
    if (hiddenId.isEmpty) return;
    final dynamic item = {"HIDDEN_RISKSTANDARD": "2", "HIDDEN_ID": hiddenId};
    pushPage(HiddenRecordDetailPage(DangerType.detailsHiddenInvestigationRecord, item), context);
  }

  void _goToImgs(String recordItemId) {
    if (recordItemId == null) return;
    pushPage(DetailImagesPage(recordItemId.toString()), context);
  }
}
