
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/danner_repain_item.dart';
import 'package:qhd_prevention/customWidget/department_picker.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';

import 'package:qhd_prevention/pages/app/Danger_paicha/check_record_detail_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 CheckRecordListPage extends StatefulWidget {
  const CheckRecordListPage(this.id, this.type, {super.key});

  final String id;
  final int type;
  @override
  _CheckRecordListPageState createState() => _CheckRecordListPageState();
}

class _CheckRecordListPageState extends State<CheckRecordListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _selectedTab = 0;
  String keyWord="";


  final TextEditingController _searchController = TextEditingController();
  List<dynamic> alreadyList = [];
  List<dynamic> overTimeList = [];
  dynamic ls;

  List<dynamic> listDates = [];


  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      // if (!_tabController.indexIsChanging) {
      //   setState(() => _selectedTab = _tabController.index);
      // }

      if (_tabController.indexIsChanging) {
        setState(() => _selectedTab = _tabController.index);
        print('切换到标签：${_tabController.index}');
        listDates.clear();
        if(_selectedTab==0){
          listDates.addAll(alreadyList);
        }else{
          listDates.addAll(overTimeList);
        }

      }

    });



    getListData();

  }

  void getListData(){
    listDates.clear();
    alreadyList.clear();
    overTimeList.clear();
    switch(widget.type  ){
      case 1://检查记录
        _getCheckRecordListOne();
        break;
      case 2://标准排查清单
        _getCheckRecordList();
        break;
    }
  }



  Future<void> _getCheckRecordListOne() async {
    try {

      final result = await ApiService.getCheckRecordListOne(widget.id,keyWord);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {
          ls= result['ls'];
          for(int i=0;i<newList.length;i++){
            if(newList[i]["TYPE"]=="1"){
              alreadyList.add(newList[i]);
            }else{
              overTimeList.add(newList[i]);
            }
          }
          listDates.addAll(alreadyList);
        });

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

  Future<void> _getCheckRecordList() async {
    try {

      final result = await ApiService.getCheckRecordList(widget.id,keyWord);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {
          ls= result['ls'];
          for(int i=0;i<newList.length;i++){
            if(newList[i]["TYPE"]=="1"){
              alreadyList.add(newList[i]);
            }else{
              overTimeList.add(newList[i]);
            }
          }
          listDates.addAll(alreadyList);
        });

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


  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  void _handleItemTap( item, int index) {
    if(_selectedTab==0){
      print("点击了是: ${index}");
      pushPage(CheckRecordDetailPage(item['CHECKRECORD_ID'],widget.type), context);
    }
  }
  // 显示分类选择器
  void showCategoryPicker() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (ctx) => DepartmentPicker(onSelected: (id, name) {

          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(
        title: "清单检查记录",

      ),
      body: SafeArea(
        child: Column(
          children: [
            // Tab bar
            TabBar(
              controller: _tabController,
              labelStyle: TextStyle(fontSize: 16),
              indicator: UnderlineTabIndicator(
                borderSide: BorderSide(width: 3.0, color: Colors.blue),
                insets: EdgeInsets.symmetric(horizontal: 100.0),
              ),
              labelColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              tabs: const [Tab(text: '已检查记录'), Tab(text: '超期未检查记录')],
            ),

            // Search bar
        Container(
          color: Colors.white,
          child: Padding(
              padding: const EdgeInsets.all(10),
              child: SearchBarWidget(
                showResetButton: false,
                onInputTap: () {
                  showCategoryPicker();
                },
                hintText: "",
                isClickableOnly: true,
                onSearch: (text) {
                  print('----------');
                  keyWord=text;
                  getListData();

                },
                controller: _searchController,
              ),
            ),
        ),

            // List
            Expanded(
              child: listDates.isEmpty
                  ? NoDataWidget.show()
                  : ListView.separated(
                padding: EdgeInsets.only(top: 15),
                itemCount: listDates.length,
                separatorBuilder: (_, __) => const SizedBox(),
                itemBuilder: (context, index) {
                  final item = listDates[index];
                  return GestureDetector(
                    onTap: () => _handleItemTap(item, index),
                    child: DannerRepainItem(
                      title: widget.type==1?'清单名称：${item['LIST_NAME']??""}':'清单名称：${item['CUSTOM_NAME']??""}',
                      showTitleIcon: false,
                      details: [
                        widget.type==1? '人员：${item['PRINCIPALNAME']??ls['USER_NAME']}':'人员：${item['USER_NAME']??ls['USER_NAME']}',
                        '',
                        '检查周期：${returnTime(item['DATESTART'])}-${returnTime(item['DATEEND']).toString()}',
                        '',
                        _selectedTab==0?'检查人：${item['CHECK_USERS']}':'清单类型：${ls['TYPENAME']}',
                        _selectedTab==0?'检查时间：${returnTime(item['CHECK_TIME'])}':'清单周期：${ls['PERIODNAME']}',
                      ],
                      showBottomTags: false,

                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }


  String returnTime(String time) {
   return time.substring(0, 16);
  }

}


