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/promise/promise_page.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/SafetyCommitment/other_promise_page.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 SafetyCommitmentOtherListPage extends StatefulWidget {
  const SafetyCommitmentOtherListPage({Key? key}) : super(key: key);

  @override
  State<SafetyCommitmentOtherListPage> createState() =>
      _SafetyCommitmentOtherListPageState();
}

class _SafetyCommitmentOtherListPageState
    extends State<SafetyCommitmentOtherListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController = TabController(
    length: 2,
    vsync: this,
    initialIndex: 1,
  );
  int _selectedTab = 1;

  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 Map<String, dynamic> result;
      if (_selectedTab == 0) {
        result = await ApiService.getMyOtherCommitmentsList();
      } else {
        result = await ApiService.getAcceptCommitmentList();
      }

      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(dynamic item) {
    return InkWell(
      onTap: () => _goToDetail(item),
      child: Container(
        padding: const EdgeInsets.all(20),
        margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '被承诺人：${item['coverpeople']}', //$itemTitle
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (item['ISREAD'] == '0')
                  Container(
                    width: 5,
                    height: 5,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                    ),
                  ),
              ],
            ),
            Text(
              '承诺人：${item['NAME']}', //$itemTitle
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [Text('${item['SIGNTIME']}')],
            ),
          ],
        ),
      ),
    );
  }

  bool _onScroll(ScrollNotification n) {
    if (n.metrics.pixels > n.metrics.maxScrollExtent - 100 &&
        _hasMore &&
        !_isLoading) {
      _page++;
      _getSafetyMeetingList(true);
    }
    return false;
  }

  void _goToDetail(dynamic item) {
    pushPage(
      OtherPromisePage(
        TabCur: _selectedTab,
        PROMISE_ID: item['PROMISE_ID'],
        PROMISEPEOPLE_ID: item['PROMISEPEOPLE_ID'],
      ),
      context,
    );
  }
}
