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/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/detail_images_page.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/hidden_record_detail_page.dart';
import 'package:qhd_prevention/pages/app/hidden_danger_management/danger_wait_list_page.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';

import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.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> {
  // 模拟数据
  // List<Map<String, dynamic>> varList = [
  //   {"RISKPOINT_ID": "1", "CHECK_CONTENT": "安全设备检查", "ISNORMAL": "0", "IMGCOUNT": 2, "RECORDITEM_ID": "1001"},
  //   {"RISKPOINT_ID": "2", "CHECK_CONTENT": "消防设施检查", "ISNORMAL": "1", "HIDDEN_ID": "2001"},
  //   {"RISKPOINT_ID": "3", "CHECK_CONTENT": "电气线路检查", "ISNORMAL": "2"},
  // ];

  // List<Map<String, dynamic>> otherHiddenList = [
  //   {"HIDDEN_ID": "3001", "HIDDENDESCR": "应急通道堵塞"},
  //   {"HIDDEN_ID": "3002", "HIDDENDESCR": "安全标识缺失"},
  // ];

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



  // 地图相关
  // final LatLng _center = const LatLng(39.8883, 119.519);
  // final Set<Marker> _markers = {};
  double _scale = 13.0;

  int _currentImageIndex = 0;
  bool _showImageViewer = false;


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

  @override
  void initState() {
    super.initState();
    // 添加地图标记
    // _markers.add(Marker(
    //   markerId: MarkerId("checkpoint"),
    //   position: _center,
    //   icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
    // ));


    _getInspectRecordsDetail();
    _getInspectRecordsDetailTwo();
  }

  Future<void> _getInspectRecordsDetail() async {
    try {

      final Map<String, dynamic> result;
      if(widget.type==1){
        result = await ApiService.getInspectRecordsDetailYin(widget.id);
      }else{
        result = await ApiService.getInspectRecordsDetail(widget.id);
      }
      // final result = await ApiService.getInspectRecordsDetail(widget.id);
      if (result['result'] == 'success') {
        final List<dynamic> qianmingList = result['qianming'] ?? [];
        setState(() {
          pd= result['pd'];
          varList = result['varList'] ?? [];
          for(int i=0;i<qianmingList.length;i++){
            imageList.add(qianmingList[i]["FILEPATH"] as String);
          }

        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    }
  }

  Future<void> _getInspectRecordsDetailTwo() async {
    try {

      final Map<String, dynamic> result;
      if(widget.type==1){
        result = await ApiService.getInspectRecordsDetailTwoYin(widget.id);
      }else{
        result = await ApiService.getInspectRecordsDetailTwo(widget.id);
      }
      // final result = await ApiService.getInspectRecordsDetailTwo(widget.id);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['hiddenList'] ?? [];
        setState(() {
          hiddenList.addAll(newList);


        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }
    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "检查记录详情"),
      // _buildAppBar(),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSectionTitle("检查内容"),
            _buildCheckContentTable(),
            _buildSectionTitle("其他隐患信息"),
            _buildOtherHiddenTable(),
            // _buildMapSection(),
            _buildSectionTitle("清单信息"),
            _buildInfoList(),
            _buildSignPhotos(),
          ],
        ),
      ),
    );
  }

  // AppBar _buildAppBar() {
  //   return AppBar(
  //     leading: IconButton(
  //       icon: Icon(Icons.arrow_back, color: Colors.white),
  //       onPressed: () => Navigator.pop(context),
  //     ),
  //     title: Text("检查记录详情", style: TextStyle(color: Colors.white)),
  //     backgroundColor: Colors.blue,
  //     centerTitle: true,
  //   );
  // }

  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.map((item) => TableRow(
    children: [
    Padding(
    padding: EdgeInsets.all(8),
    child: Text(item["CHECK_CONTENT"]),
    ),
    _buildStatusCell(item)
    ],
    )),
    ],
    ),
    );
  }

  Widget _buildStatusCell(Map<String, dynamic> item) {
    String status;
    Color color = Colors.black;
    VoidCallback? onTap;

    switch (item["ISNORMAL"]) {
      case 0:
        status = "合格";
        color = Colors.blue;
        if (item["IMGCOUNT"] > 0) {
          onTap = () => _goToImgs(item["RECORDITEM_ID"]);
        }
        break;
      case 1:
        status = "不合格";
        color = Colors.blue;
        onTap = () => _goToDetail(item["HIDDEN_ID"]);
        break;
      case 2:
        status = "不涉及";
        color = Colors.blue;
        break;
      default:
        status = "存在未整改隐患";
    }

    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("操作"),
      ],
    ),
    ...hiddenList.map((item) => TableRow(
    children: [
    Padding(
    padding: EdgeInsets.all(8),
    child: Text(item["HIDDENDESCR"]),
    ),
    GestureDetector(
    onTap: () => _goToDetail(item["HIDDEN_ID"]),
    child: Padding(
    padding: EdgeInsets.all(8),
    child: Center(
    child: Text(
    "查看",
    style: TextStyle(color: Colors.blue),
    ),
    ),
    ),
    ),
    ],
    )),
    ],
    ),
    );
    }

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

  // Widget _buildMapSection() {
  //   return Container(
  //     height: 300,
  //     margin: EdgeInsets.symmetric(vertical: 10),
  //     child: GoogleMap(
  //       initialCameraPosition: CameraPosition(
  //         target: _center,
  //         zoom: _scale,
  //       ),
  //       markers: _markers,
  //     ),
  //   );
  // }

  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"]?? ''),
          _buildInfoRow("排查清单类型", pd["SCREENTYPENAME"]?? ''),
          _buildInfoRow("检查人", pd["USERS"]?? ''),
          _buildInfoRow("检查时间", pd["CHECK_TIME"]?? ''),
          _buildInfoRow("所属部门", pd["DEPARTMENT_NAME"]?? ''),
          _buildInfoRow("所属岗位", pd["POST_NAME"]?? ''),
          _buildInfoRow("排查周期", pd["PERIODNAME"]?? ''),
          _buildInfoRow("清单类型", pd["TYPENAME"]?? ''),
          if (pd["TYPENAME"] == "临时")
            _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) {
    dynamic item={"HIDDEN_RISKSTANDARD":"2","HIDDEN_ID":hiddenId};
    pushPage(HiddenRecordDetailPage(DangerType.detailsHiddenInvestigationRecord,item), context);
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => Scaffold(
    //       appBar: AppBar(title: Text("隐患详情")),
    //       body: Center(child: Text("隐患ID: $hiddenId")),
    //     ),
    //   ),
    // );
  }

  void _goToImgs(String recordItemId) {
    pushPage(DetailImagesPage(recordItemId), context);
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => Scaffold(
    //       appBar: AppBar(title: Text("图片详情")),
    //       body: Center(child: Text("记录项ID: $recordItemId")),
    //     ),
    //   ),
    // );

  }




}