import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'dart:convert';
import 'dart:math' as math;

import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/EquipmentInspection/equiment_detail_listinfo.dart';
import 'package:qhd_prevention/pages/home/Safetymeeting/safety_meeting_detail_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/pages/notif/notif_detail_page.dart';
import 'package:qhd_prevention/tools/tools.dart';


class EquimentDetailListPage extends StatefulWidget {
  const EquimentDetailListPage(this.id, {Key? key}) : super(key: key);

  final String id;
  @override
  State<EquimentDetailListPage> createState() => _EquimentDetailListPageState();
}

class _EquimentDetailListPageState extends State<EquimentDetailListPage>
    with SingleTickerProviderStateMixin{

  late TabController _tabController= TabController(length: 2, vsync: this);
  int _selectedTab = 0;
  late List<dynamic> _list = [];


  @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}');
        reRefreshData();
      }

    });

    _getEquipmentDetailList(false);
  }

  void reRefreshData(){
    _list.clear();
    _getEquipmentDetailList(false);

  }

  Future<void> _getEquipmentDetailList(bool loadMore) async {
    try {

      final result = await ApiService.getEquipmentDetailList(widget.id,_selectedTab );
      if (result['result'] == 'success') {

        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {
          _list.addAll(newList);
        });

      }else{
        ToastUtil.showNormal(context, "加载数据失败");
        // _showMessage('加载数据失败');
      }

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



  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "设备巡检记录"),
      body:
      GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus(); // 收起键盘
        },
        behavior: HitTestBehavior.opaque,
        child: Scaffold(
          body: SafeArea(
            child: Column(
              children: [
                // Tab bar
                Container(
                  color: Colors.white,
                  child: 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
                // List
                Expanded(
                      child:
                      _list.isEmpty
                          ? NoDataWidget.show()
                          : ListView.builder(
                        itemCount: _list.length,
                        itemBuilder: (context, index) {
                          return _itemCell(_list[index]);
                        },
                      ),
                    ),


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

  Widget _itemCell(final record) {
    return Card(
      color: Colors.white,
      margin: const EdgeInsets.only(top: 15,left: 15,right: 15),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: InkWell(
        onTap:() {
          _goToDetail(record);
        } ,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildInfoRow('人员：${record['INSPECTOR']}'),
              const SizedBox(height: 8),
              _buildInfoRow(
                  '检查周期：${ DateFormat('yyyy-MM-dd').format(DateTime.parse(record['PERIOD_START_DATE']))} '
                      '- ${DateFormat('yyyy-MM-dd').format(DateTime.parse(record['PERIOD_END_DATE']))}'
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildInfoRow('检查时间：${record['INSPECTIONTIME']}'),
                  _buildInfoRow('是否故障：${record['ISFAULT']}'),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfoRow(String text) {
    return Text(
      text,
      style: const TextStyle(color: Colors.grey, fontSize: 14),
    );
  }


  void _goToDetail(item){
    // pushPage(SafetyMeetingDetailPage(
    //     id,_selectedTab,
    //   onClose: (String result) {
    //     setState(() {
    //       reRefreshData();
    //     });
    //
    //   },
    // ), context);
    pushPage(EquimentDetailListinfo(item["SPECIALEQUIPMENTAQXJ_ID"]), context);
  }






}



