import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:qhd_prevention/customWidget/search_bar_widget.dart';

import 'package:qhd_prevention/pages/http/ApiService.dart';
import 'package:qhd_prevention/pages/notif/notif_detail_page.dart';
import 'package:qhd_prevention/tools/tools.dart';



class NotifPage extends StatefulWidget {
  const NotifPage({Key? key}) : super(key: key);

  @override
  _NotifPageState createState() => _NotifPageState();
}

class _NotifPageState extends State<NotifPage>
    with SingleTickerProviderStateMixin {

  final TextEditingController searchController = TextEditingController();
  late List<dynamic> _list = [];
  late TabController _tabController;
  int _selectedTab = 0;
  int pageNum = 1;

  // 模拟数据
  final List<Map<String, dynamic>> _notifications = List.generate(10, (i) {
    bool read = i % 3 == 0;
    return {
      'title': '测试数据标题标题 ${i + 1}',
      'time': '2025-06-${10 + i} 12:3${i}',
      'read': read,
    };
  });

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

    });

    _getNotifList("");
  }

  void reRefreshData(){
    pageNum=1;
    _list.clear();
    searchController.text="";
    if(0==_selectedTab){
      _getNotifList("");
    }else{
      _getNotifEnterprise("");
    }
  }

  Future<void> _getNotifList(String keyWord) async {
    LoadingDialogHelper.show();
    try {
      final result = await ApiService.getNotifList("-1", pageNum.toString(),keyWord);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {
          _list.addAll(newList);
        });
      }
      LoadingDialogHelper.hide();
    } catch (e) {
      LoadingDialogHelper.hide();

      print('加载出错: $e');
    } finally {
      LoadingDialogHelper.hide();
    }
  }

  Future<void> _getNotifEnterprise(String keyWord) async {
    // LoadingDialogHelper.show();
    try {
      final result = await ApiService.getNotifEnterprise("-1", pageNum.toString(),keyWord);
      if (result['result'] == 'success') {
        final List<dynamic> newList = result['varList'] ?? [];
        setState(() {
          _list.addAll(newList);
        });
      }
    } catch (e) {
      print('加载出错: $e');
    } finally {
      LoadingDialogHelper.hide();
    }
  }

  Future<void> _deleteNotif(String id) async {
    // LoadingDialogHelper.show();
    try {
      final result = await ApiService.deleteNotif(id);
      if (result['result'] == 'success') {
        setState(() {
          reRefreshData();

        });
      }
    } catch (e) {
      print('加载出错: $e');
    } finally {
      LoadingDialogHelper.hide();
    }
  }



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

  @override
  Widget build(BuildContext context) {


    return 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
              Padding(
                padding: const EdgeInsets.all(10),
                child: SearchBarWidget(
                  key: Key("searchBody"),
                  controller: searchController,
                  onSearch: (keyword) {
                    print("用户输入的是: $keyword");
                    // TODO: 执行搜索
                    // String word="整改";
                      pageNum=1;
                      _list.clear();
                      if(0==_selectedTab){
                        _getNotifList(keyword);
                      }else{
                        _getNotifEnterprise(keyword);
                      }

                  },
                ),
              ),

              // List
              Expanded(
                child:
                    _list.isEmpty
                        ? NoDataWidget.show()
                        : ListView.builder(
                          itemCount: _list.length,
                          itemBuilder: (context, index) {
                            return _itemCell(_list[index]);
                          },
                        ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _itemCell(final item) {
    return Column(
      children: [
        ListTile(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => NotifDetailPage(
                  item,_selectedTab,
                  onClose: (result) {
                    print('详情页面已关闭，返回结果: $result');
                    reRefreshData();
                  },
                ),
              ),
            );

            // pushPage(NotifDetailPage(item,_selectedTab), context);
          },
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 10,
          ),
          title: Padding(
            padding: const EdgeInsets.only(bottom: 20), // 减小底部间距
            child: Text(item['SYNOPSIS'], style: const TextStyle(fontSize: 14)),
          ),

          subtitle: Text(item['CREATTIME'], style: TextStyle(fontSize: 13)),

          trailing: Container(
            constraints: const BoxConstraints(minHeight: 100), // 确保最小高度
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min, // 关键修改：使用最小尺寸
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                if (0 != _selectedTab)
                  Text(
                    item['TYPE'] == 1 ? '已读' : '未读',
                    style: TextStyle(
                      fontSize: 12, // 稍微减小字体大小
                      color: item['TYPE'] == 1 ? Colors.grey : Colors.red,
                    ),
                  ),
                SizedBox(height: 15),

                if (0 != _selectedTab && item['TYPE'] == 1)
                  SizedBox(
                    height: 24, // 固定按钮高度
                    child: TextButton(
                      onPressed: () async{
                        // 显示确认对话框
                        bool? confirm = await showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: Text("确认删除"),
                          content: Text("确定要删除这条通知吗？"),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.pop(context, false),
                              // onPressed: () => Navigator.pop(context, false),
                              child: Text("取消"),
                            ),
                            TextButton(
                              onPressed: () => Navigator.pop(context, true),
                              // onPressed: () => Navigator.pop(context, true),
                              child: Text("确定", style: TextStyle(color: Colors.red)),
                            ),
                          ],
                        ),
                        );
                        if (confirm == true) {
                          _deleteNotif(item['NOTICECORPUSERID_ID']);
                        }

                      },
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(horizontal: 12),
                        backgroundColor: Colors.red,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text( '删除', style: TextStyle(fontSize: 13, color: Colors.white),),

                    ),
                  ),
              ],
            ),
          ),
        ),
        Divider(height: 1, color: Colors.black12),
      ],
    );
  }
}




