import 'package:flutter/material.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_deawer.dart';
import 'package:qhd_prevention/pages/app/hidden_danger_management/hidden_danger_acceptance_page.dart';
import 'package:qhd_prevention/pages/app/hidden_danger_management/pending_rectification_detail_page.dart';


import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/h_colors.dart';
import 'package:qhd_prevention/tools/tools.dart';
import '../../http/ApiService.dart';

import '/customWidget/search_bar_widget.dart';


enum DangerType {

  detailsHiddenInvestigationRecord("排查隐患记录", "排查隐患记录-详情"),

  ristRecord("隐患记录", "隐患记录-详情"),
  wait("待整改隐患", "隐患整改"),
  expired("超期未整改", "超期未整改-详情"),
  waitAcceptance("隐患验收", "隐患验收-详情"),
  acceptance("已验收隐患", "已验收隐患"),
  acceptanced("已验收隐患", "已验收隐患-详情");


  final String displayName;
  final String detailTitle;

  const DangerType(this.displayName, this.detailTitle);
}
class DangerWaitListPage extends StatefulWidget {
  const DangerWaitListPage(this.dangerType, this.appItem,{super.key});
  final DangerType dangerType;
  final int appItem;

  @override
  State<DangerWaitListPage> createState() => _DangerWaitListPageState();
}

class _DangerWaitListPageState extends State<DangerWaitListPage> {

  int _page = 1;
  String searchKey="";
  int _totalPage=1;
  late List<dynamic> _list = [];
  bool _isLoading = false;
  bool _hasMore = true;

  String treeJson="";
  // late DangerWaitBean waitBean;




  // 隐患等级颜色
  final List<Color> _fxColors = [
    const Color(0xFFFCE6D2),
    const Color(0xFFFDF2CE),
  ];
  final TextEditingController _searchController = TextEditingController();

  // 隐患等级文本
  final List<String> _levelTexts = ["重大隐患","一般隐患"];

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

    getListData(widget.appItem,false,"");
    SessionService.instance.setDangerWaitInfo("");

  }

  void getListData(int type,bool addList,String keyWord){
    switch(widget.appItem  ){
      case 1://隐患记录
        _getDangerRecord(-1,_page,"","","","","","","","",keyWord,addList);
        _getListTree();
        break;
      case 2://待整改隐患
        _getDangerRecord(2,_page,"","","","","","","","",keyWord,addList);
        break;
      case 3://超期未整改
        _getDangerRecord(5,_page,"","","","","-1","","","",keyWord,addList);
        break;
      case 4://隐患验收
        _getDangerRecord(3,_page,"","","","","","3","","",keyWord,addList);
        break;
      case 5://已验收隐患
        _getDangerRecord(4,_page,"","","","","","4","","1",keyWord,addList);
        break;

    }
  }



  @override
  Widget build(BuildContext context) {
    // 取屏幕宽度
    final double screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: MyAppbar(
        title: widget.dangerType.displayName,
        actions: [
          if (1 == widget.appItem)
            Builder(
              builder: (innerContext) {
                return TextButton(
                  onPressed: () {
                    // 通过 innerContext 拿到 ScaffoldState，打开右侧抽屉
                    Scaffold.of(innerContext).openEndDrawer();
                  },
                  child: Text(
                    "查询",
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                );
              },
            ),
        ],
      ),

      //弹窗
      endDrawer: Drawer(
        // 用 Container 限制宽度为屏幕的 3/5
        child: Container(
          width: screenWidth * 3 / 5,
          color: Colors.white,
          child:  DangerWaitDrawer(
             treeJson,
                onClose: (String selectedCategoryId,String selectedDepartmentId,String investigationMethodOption,
                    String hazardLevelOption,String dangerStatusOption,String startDate,String endDate) {

                  _page=1;
                  _getDangerRecord(-1,_page,startDate,endDate,hazardLevelOption,investigationMethodOption,
                      dangerStatusOption,selectedCategoryId,selectedDepartmentId,"",searchKey,false);

              },
          ),
        ),
      ),

      body: SafeArea(
        child: NotificationListener<ScrollNotification>(
          onNotification: _onScroll,
          child:_vcDetailWidget()
        )
      ),
      backgroundColor: Colors.white,
    );
  }

  Widget _vcDetailWidget() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.all(10),
          child: SearchBarWidget(
            controller: _searchController,
            onSearch: (keyboard) {
              // 输入请求接口
              _page=1;
              searchKey=keyboard;
              getListData(widget.appItem,false,keyboard);
            },
          ),
        ),
        Container(
          height: 5,
          color: h_backGroundColor(),
        ),
        Expanded(
          child:  _list.isEmpty
              ? NoDataWidget.show()
              : ListView.separated(
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemCount: _list.length,
              itemBuilder: (context, index) {
                final item = _list[index];
                return _fxitemCell(item);
              },
          ),
        ),
      ],
    );
  }

  Widget _fxitemCell(final item) {
    // int level = item['level'] as int;
    // // 确保level在有效范围内 (1-4)
    // level = level.clamp(1, 4) - 1;
    int level =1;
    if('hiddenLevel0001'==item['HIDDENLEVEL']){
      level =1;
    }else{
      level =0;
    }

    // 使用GestureDetector包裹整个列表项以添加点击事件
    return GestureDetector(
      onTap: () {
        // 点击后跳转到详情页面
        // pushDetailByType(
        //   type: item.type,
        //   context: context,
        // );

        switch(widget.appItem  ){
          case 1://隐患记录
            pushPage(HiddenRecordDetailPage(widget.dangerType,item), context);
            break;
          case 2://待整改隐患
            // _getDangerRecord(2,_page,"","","","","","","","",keyWord,addList);
          // pushPage(PendingRectificationDetailPage(widget.dangerType,item), context);
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => PendingRectificationDetailPage(
                widget.dangerType,item,
                onClose: (result) {
                  print('详情页面已关闭，返回结果: $result');
                  _page=1;
                  getListData(widget.appItem,false,"");
                  SessionService.instance.setDangerWaitInfo("");
                  // reRefreshData();
                },
              ),
            ),
          );
            break;
          case 3://超期未整改
            // _getDangerRecord(5,_page,"","","","","-1","","","",keyWord,addList);
            pushPage(HiddenRecordDetailPage(widget.dangerType,item), context);

            break;
          case 4://隐患验收
            // pushPage(HiddenRecordDetailPage(widget.dangerType,item), context);
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => HiddenDangerAcceptancePage(
                  widget.dangerType,item,
                  onClose: (result) {
                    print('详情页面已关闭，返回结果: $result');
                    _page=1;
                    getListData(widget.appItem,false,"");
                    SessionService.instance.setDangerWaitInfo("");
                    // reRefreshData();
                  },
                ),
              ),
            );

            break;
          case 5://已验收隐患
            pushPage(HiddenRecordDetailPage(widget.dangerType,item), context);
            break;

        }
      },
      child: Container(
        // height: 100,
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 15), // 添加水平内边距
        child:
        IntrinsicHeight(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 左侧信息列
              Expanded(

                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item['HIDDENDESCR'] ?? '',
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 5),
                    // Text(
                    //   item['label1'] ?? '',
                    //   style: TextStyle(fontSize: 14, color: Colors.grey),
                    // ),
                    // SizedBox(height: 5),
                    // Text(
                    //   item['label2'] ?? '',
                    //   style: TextStyle(fontSize: 14, color: Colors.grey),
                    // ),
                    SizedBox(height: 5),
                    Text(
                      // item['label2'] ?? '',
                      _getSourceDangers(item),
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                    SizedBox(height: 5),
                    Text(
                      item['CREATORNAME'] ?? '',
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  ],
                ),
              ),

              // 右侧风险等级和箭头
              Padding(
                padding: EdgeInsets.only(top: 0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 风险等级标签
                    Row(
                      children: [
                        Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: _fxColors[level],
                            borderRadius: BorderRadius.circular(2),
                          ),
                          child: Text(
                            _levelTexts[level],
                            style: TextStyle(fontSize: 12),
                          ),
                        ),
                        SizedBox(width: 30),
                      ],
                    ),
                    SizedBox(height: 12), // 添加间距
                    Row(
                      children: [
                        SizedBox(width: 110),
                        Icon(Icons.arrow_forward_ios_rounded, size: 16),
                      ],
                    ),
                    SizedBox(height: 20), // 添加间距
                    Row(children: [
                      Text(item['RECTIFICATIONTIME'] ?? '',style: TextStyle(fontSize: 12, color: Colors.grey),
                      )
                      , SizedBox(width: 20,)],),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }


  Future<void> _getDangerRecord(int type, int currentPage,
      String startDate,String endDate,String level,String riskStandard,String state,
      String departmentId,String correctiveDepartment,
      String isIndex,String keyWord,bool loadMore) async {
    try {
      if (_isLoading) return;
      _isLoading = true;


      final result = await ApiService.getHiddenTreatmentList( type,  currentPage,
           startDate, endDate, level, riskStandard, state,
           departmentId, correctiveDepartment, isIndex, keyWord);

      if (result['result'] == 'success') {

        _totalPage =result["page"]['totalPage'] ?? 1;
        final List<dynamic> newList = result['varList'] ?? [];
        // setState(() {
        //   _list.addAll(newList);
        // });

        setState(() {
          if (loadMore) {
            _list.addAll(newList);
          } else {
            _list = newList;
          }
          _hasMore = _page < _totalPage;
          // if (_hasMore) _page++;
        });

      }else{
        _showMessage('加载数据失败');
      }

    } catch (e) {
      // 出错时可以 Toast 或者在页面上显示错误状态
      print('加载数据失败：$e');
    } finally {
      // if (!loadMore) LoadingDialogHelper.hide();
      _isLoading = false;
    }
  }

  bool _onScroll(ScrollNotification n) {
    if (n.metrics.pixels > n.metrics.maxScrollExtent - 100 &&
        _hasMore && !_isLoading) {

      _page++;
      getListData(widget.appItem,true,"");
      // switch(widget.appItem){
      //   case 1://隐患记录
      //     _getDangerRecord(-1,_page,"","","","","","","","","",true);
      //     break;
      //   case 2://待整改隐患
      //     _getDangerRecord(2,_page,"","","","","","","","","",true);
      //     break;
      //   case 3://超期未整改
      //     _getDangerRecord(5,_page,"","","","","","-1","","","",true);
      //     break;
      //   case 4://隐患验收
      //     _getDangerRecord(3,_page,"","","","","","3","","","",true);
      //     break;
      //   case 5://已验收隐患
      //     _getDangerRecord(4,_page,"","","","","","4","","1","",true);
      //     break;

      // }

      // _getStudyList(loadMore: true);
    }
    return false;
  }


  Future<void> _getListTree() async {
    try {

      final result = await ApiService.getHiddenTreatmentListTree();
      if (result['result'] == 'success') {
        setState(() {
          treeJson= result['zTreeNodes'];
        });

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

  String _getSourceDangers(final item) {
    String type = item["SOURCE"];
    if("1"==type){
      return "隐患来源：隐患快报";
    }else if("2"==type){
      return "隐患来源：隐患排查清单检查";
    }else if("3"==type){
      return "隐患来源：标准排查清单检查";
    }else if("4"==type){
      return "隐患来源：专项检查";
    }else{
      return "隐患来源：安全检查";
    }

  }

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


}





