import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/check_record_list_page.dart';
import 'package:qhd_prevention/pages/app/Danger_paicha/custom_record_drawer.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 '../../../Model/list_model.dart';
import '../../../customWidget/danner_repain_item.dart';
import '../../home/scan_page.dart';

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

  final int type;
  @override
  State<CheckRecordPage> createState() => _CheckRecordPageState();
}

class _CheckRecordPageState extends State<CheckRecordPage> {
  final TextEditingController _searchController = TextEditingController();

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

  List<dynamic> listType = [];
  List<dynamic> listInspectionCycle = [];



  void _handleItemTap(item) {
  //item点击事件
  String id="";

  switch(widget.type  ){
    case 1://检查记录
      id=item["LISTMANAGER_ID"];
      break;
    case 2://标准排查清单
      id=item["CUSTOM_ID"];
      break;
  }

    pushPage(CheckRecordListPage(id,widget.type), context);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    id=SessionService.instance.loginUser?["DEPARTMENT_ID"]??"";
    print("======>$id");
    getListData(false,"");
    _getListType();
    _getListInspectionCycle();
    SessionService.instance.setCustomRecordDangerJson("");

  }


  void getListData(bool addList,String keyWord){
    switch(widget.type  ){
      case 1://检查记录
        appBarTitle="检查记录";
        _getHazardInspectionRecordList(_page,keyWord,"","","","","","",addList);

        break;
      case 2://标准排查清单
        appBarTitle="标准排查清单";
        _getStandardInvestigationRecordList(_page,keyWord,"","","","","","",addList);
        break;
    }
  }


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

    return Scaffold(
      appBar: MyAppbar(
        title: appBarTitle,
        actions: [
          // 用 Builder 拿到 Scaffold 之下的 context
          Builder(
            builder: (innerContext) {
              return TextButton(
                onPressed: () {
                  // 通过 innerContext 调用 openEndDrawer
                  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:  CustomRecordDrawer(
              listType,listInspectionCycle,
            onClose: (String departmentId,String responsibleName,String selectedQDTypeId,String selectedZQTimeId
                ,String startDate,String endDate) {

              _page=1;
              switch(widget.type  ){
                case 1://检查记录
                  _getHazardInspectionRecordList(_page,searchKey,departmentId,startDate,endDate,selectedZQTimeId,responsibleName,selectedQDTypeId,false);

                  break;
                case 2://标准排查清单
                  _getStandardInvestigationRecordList(_page,searchKey,departmentId,startDate,endDate,selectedZQTimeId,responsibleName,selectedQDTypeId,false);
                  break;
              }


            },

          ),
        ),
      ),


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

    );
  }

  Widget _vcDetailWidget() {
    return Column(
      children: [
        Container(
          color: Colors.white,
          child: Padding(
            padding: EdgeInsets.all(10),
            child: SearchBarWidget(
              controller: _searchController,

              onSearch: (keyboard) {

                // 输入请求接口
                _page=1;
                searchKey=keyboard;
                getListData(false,keyboard);
              },
            ),
          ),
        ),

        Container(
          height: 5,
          color: h_backGroundColor(),
        ),

        Expanded(

          child:_list.isEmpty
              ? NoDataWidget.show()
              : ListView.separated(
            padding: EdgeInsets.only(top: 15),
            itemCount: _list.length,
            separatorBuilder: (_, __) => const SizedBox(),
            itemBuilder: (context, index) {
              final  item = _list[index];
              return GestureDetector(
                onTap: (){
                  _handleItemTap(item);
                } ,
                // => _handleItemTap(item),
                child: DannerRepainItem(
                  showTitleIcon: true,
                  title: '清单名称：${item['NAME']}',
                  details: [
                    '清单类型：${item['TYPENAME']}',
                    '排查周期：${item['PERIODNAME']}',
                    '部门：${item['DEPARTMENT_NAME']}',
                    '',
                    '岗位：${item['POST_NAME']}',
                    '人员：${item['USER_NAME']}',
                    "检查次数：${item['count']}",
                    '超期未检查次数：${item['overTimeCount']}'
                  ],
                  showBottomTags: false,

                ),
              );
            },
          ),
        )


      ],
    );
  }

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

      _page++;
      getListData(true,"");

    }
    return false;
  }

  Future<void> _getHazardInspectionRecordList( int currentPage,String keyWord,String dept,
      String starDate,String endDate,String periodId,String userName,String typeId,bool loadMore) async {
    try {
      if (_isLoading) return;
      _isLoading = true;


      final result = await ApiService.getHazardInspectionRecordList(
         currentPage, keyWord, id, dept,
         starDate, endDate, periodId, userName, typeId);

      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{
        ToastUtil.showNormal(context, '加载数据失败');
        // _showMessage('加载数据失败');
      }

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



  Future<void> _getStandardInvestigationRecordList( int currentPage,String keyWord,String dept,
      String starDate,String endDate,String periodId,String userName,String typeId,bool loadMore) async {
    try {
      if (_isLoading) return;
      _isLoading = true;


      final result = await ApiService.getStandardInvestigationRecordList(
          currentPage, keyWord, id, dept,
          starDate, endDate, periodId, userName, typeId);

      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{
        ToastUtil.showNormal(context, '加载数据失败');
        // _showMessage('加载数据失败');
      }

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

  Future<void> _getListType() async {
    try {

      final result = await ApiService.getListType();
      if (result['result'] == 'success') {
        setState(() {
          listType= result['list'];
        });

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


  Future<void> _getListInspectionCycle() async {
    try {

      final result = await ApiService.getListInspectionCycle();
      if (result['result'] == 'success') {
        setState(() {
          listInspectionCycle= result['list'];
        });

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

}
