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/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 SafetyMeetingListPage extends StatefulWidget {
  const SafetyMeetingListPage({Key? key}) : super(key: key);

  @override
  State<SafetyMeetingListPage> createState() => _SafetyMeetingListPageState();
}

class _SafetyMeetingListPageState extends State<SafetyMeetingListPage>
    with SingleTickerProviderStateMixin{



  late TabController _tabController= TabController(length: 2, vsync: this);
  int _selectedTab = 0;

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



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

    });

    _getSafetyMeetingList(false);
  }

  void reRefreshData(){
    _page=1;
    _list.clear();


    _getSafetyMeetingList(false);

  }

  Future<void> _getSafetyMeetingList(bool loadMore) async {
    // LoadingDialogHelper.show();
    try {
      if (_isLoading) return;
      _isLoading = true;


      final result = await ApiService.getSafetyMeetingList(_page,_selectedTab );

      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;
    }
  }







  @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
                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
                NotificationListener<ScrollNotification>(
                    onNotification: _onScroll,
                    child: Expanded(
                      child:
                      _list.isEmpty
                          ? NoDataWidget.show()
                          : ListView.builder(
                        itemCount: _list.length,
                        itemBuilder: (context, index) {
                          return _itemCell(_list[index]);
                        },
                      ),
                    ),
                ),

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

  Widget _itemCell(final item) {
    return Container(
      padding: EdgeInsets.all(20),
      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  item["SAFETY_MEETING_TITLE"],
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 8),
          Text(
            '例会正文：${item["SAFETY_MEETING_CONTENT"]}',
            style: TextStyle(color: Colors.grey[600]),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
          SizedBox(height: 8),
          Text('发布人：${item["NAME"]}'),
          SizedBox(height: 8),
          Text('发布时间：${item["CREATTIME"]}'),
          SizedBox(height: 8),
          Align(
            alignment: Alignment.centerRight,
            child:
            SizedBox(
            width: 90,
            height: 40,
            child:  CustomButton(
              text: _selectedTab == 0 ? '立即反馈' : '查看',
              backgroundColor: Colors.blue,
              textStyle: TextStyle(color: Colors.white,fontSize: 12),
              onPressed: () {
                _goToDetail(item["SAFETY_MEETING_ID"]);
              },
            ),
            ),
          ),
        ],
      ),
    );
  }


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

      _page++;
      _getSafetyMeetingList(true);
    }
    return false;
  }


  void _goToDetail(String id){
    pushPage(SafetyMeetingDetailPage(
        id,_selectedTab,
      onClose: (String result) {
        setState(() {
          reRefreshData();
        });

      },
    ), context);
  }






}



