/*
 * @Author: wangyang 1147192855@qq.com
 * @Date: 2022-07-05 16:42:44
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-09-27 16:15:03
 * @FilePath: \marking_app\lib\pages\marking\index.dart
 * @Description: 阅卷主页
 */

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:marking_app/common/config/request_config.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/enum/marking_list_type.dart';
import 'package:marking_app/common/model/event_bus/marking_statistics_bus.dart';
import 'package:marking_app/common/model/marking/marking_statistics.dart';
import 'package:marking_app/pages/common/event_bus_mixin.dart';
import 'package:marking_app/provider/review_provider.dart';
import 'package:marking_app/utils/request/rest_client.dart';
import 'package:marking_app/common/model/common/base_page_data.dart';
import 'package:marking_app/common/model/marking/marking_item.dart';
import 'package:marking_app/common/model/marking/marking_list_params.dart';
import 'package:marking_app/components/TestPaperItem.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/easy_refresh/mixin/refresh_data_handle.dart';

// 阅卷主页
class TheMarking extends StatefulHookConsumerWidget {
  const TheMarking({Key? key}) : super(key: key);

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

class _TheMarkingState extends ConsumerState<TheMarking>
    with
        CommonMixin,
        EventBusMixin<MarkingStatisticsMainListBus>,
        SingleTickerProviderStateMixin,
        RefreshDataHandle<MarkingItem, MarkingListParams>,
        AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  /* Tab控制器 */
  late TabController _tabController;
  int _tabIndex = 0;
  bool completedToRefresh = true;

  Map<MarkingListType, int> tabNumsMap = new Map();

  /* 阅卷 */
  late final EasyRefreshController _refreshController1;
  final MarkingListParams params1 = MarkingListParams(
    isFinish: false,
    pageType: MarkingListType.NORMAL.index,
    page: RequestConfig.basePage.page,
    limit: RequestConfig.basePage.limit,
  );
  List<MarkingItem> markingDatas1 = [];

  /* 仲裁 */
  late final EasyRefreshController _refreshController2;
  RemoveListener? _currentTaskIdListener;
  final MarkingListParams params2 = MarkingListParams(
    isFinish: false,
    pageType: 1,
    page: RequestConfig.basePage.page,
    limit: RequestConfig.basePage.limit,
  );
  List<MarkingItem> markingDatas2 = [];

  /* 异常 */
  late final EasyRefreshController _exceptionalRefreshController;
  final MarkingListParams exceptionalParams = MarkingListParams(
    isFinish: false,
    pageType: 2,
    page: RequestConfig.basePage.page,
    limit: RequestConfig.basePage.limit,
  );
  List<MarkingItem> exceptionalMarkingDatas = [];

  Future<List<MarkingItem>> getData(EasyRefreshController controller, MarkingListParams theParams,
      {bool isReFresh = false}) async {
    if (!isReFresh) {
      theParams.page++;
    }

    RestClient client = await getClient();
    BasePageData<MarkingItem>? results = await toRefreshData(
      controller,
      api: client.getMarkingsByPage,
      params: theParams,
      isReFresh: isReFresh,
      context: context,
    );
    if (results != null) {
      if (_tabIndex == 0) {
        eventFire(model: MarkingStatisticsMainListBus());
      }
      return results.items;
    }
    return [];
  }

  void getTabNumsData() async {
    RestClient client = await getClient();
    Map<MarkingListType, int> map = {};
    BaseStructureResult<List<MarkingStatistics>> result = await client.getMarkingStatistics();
    if (result.success && result.data != null) {
      List<MarkingListType> _theTypes = MarkingListType.values;
      result.data!.forEach((e) => map[_theTypes[e.navld]] = e.total);
    }
    tabNumsMap = map;
  }

  @override
  void initState() {
    _tabController = TabController(length: 3, vsync: this);
    _refreshController1 = EasyRefreshController();
    _refreshController2 = EasyRefreshController();
    _exceptionalRefreshController = EasyRefreshController();

    Future.delayed(Duration.zero, () {
      getTabNumsData();
      //在这里处理页面
      _currentTaskIdListener = ref.watch(currentTaskIdProvider.notifier).addListener((state) {
        int? taskId = state.taskId;

        if (taskId != null && state.refresh) {
          getTabNumsData();
          _refreshController1.callRefresh();
          _refreshController2.callRefresh();
          _exceptionalRefreshController.callRefresh();
        }
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    if (_currentTaskIdListener != null) {
      _currentTaskIdListener!();
    }
    eventCancel();
    _tabController.dispose();
    _refreshController1.dispose();
    _refreshController2.dispose();
    _exceptionalRefreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //调用super.build(返回值始终返回null，应将其忽略)

    return AnnotatedRegion(
      value: const SystemUiOverlayStyle(
        systemNavigationBarColor: Color(0xFF000000),
        systemNavigationBarDividerColor: null,
        statusBarColor: Colors.transparent,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      child: Scaffold(
        body: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top + 4.h),
              child: TabBar(
                controller: _tabController,
                unselectedLabelStyle: TextStyle(fontSize: 14.sp),
                labelStyle: TextStyle(
                    fontSize: 16.sp, fontWeight: FontWeight.bold, color: const Color.fromRGBO(148, 163, 182, 1)),
                labelColor: const Color.fromRGBO(45, 56, 76, 1),
                indicatorSize: TabBarIndicatorSize.label,
                onTap: (index) {
                  setState(() {
                    _tabIndex = index;
                    if (index == 1 && markingDatas2.length == 0) {
                      _refreshController2.callRefresh();
                    } else if (index == 2 && exceptionalMarkingDatas.length == 0) {
                      _exceptionalRefreshController.callRefresh();
                    }
                  });
                },
                tabs: <Widget>[
                  Tab(
                      text: '阅卷' +
                          (tabNumsMap[MarkingListType.NORMAL] == null
                              ? ''
                              : '(${tabNumsMap[MarkingListType.NORMAL]})')),
                  Tab(
                      text: '仲裁' +
                          (tabNumsMap[MarkingListType.ARBITRATE] == null
                              ? ''
                              : '(${tabNumsMap[MarkingListType.ARBITRATE]})')),
                  Tab(
                      text: '异常' +
                          (tabNumsMap[MarkingListType.EXCEPTIONAL] == null
                              ? ''
                              : '(${tabNumsMap[MarkingListType.EXCEPTIONAL]})')),
                ],
              ),
            ),
            // $TypesOf(controller: controller, params: params),
            // MarkingStatisticsBox(controller: controller, isShow: _tabIndex != 0, params: params),
            Expanded(
              child: IndexedStack(
                index: _tabIndex,
                children: <Widget>[
                  EasyRefresh(
                    firstRefresh: true,
                    taskIndependence: true,
                    enableControlFinishLoad: true,
                    enableControlFinishRefresh: true,
                    emptyWidget: markingDatas1.isEmpty ? const MyEmptyWidget() : null,
                    controller: _refreshController1,
                    header: MaterialHeader(),
                    footer: TaurusFooter(),
                    child: ListView.builder(
                      padding: EdgeInsets.only(top: 4.h, bottom: 10.h),
                      itemBuilder: (context, index) => TestPaperItem(
                        markingItem: markingDatas1[index],
                        markingtype: MarkingListType.values[params1.pageType],
                        call: () => _refreshController1.callRefresh(),
                      ),
                      itemCount: markingDatas1.length,
                    ),
                    onRefresh: () async {
                      List<MarkingItem> lists = await getData(_refreshController1, params1, isReFresh: true);
                      if (lists.isNotEmpty) {
                        setState(() => markingDatas1 = lists);
                      }
                    },
                    onLoad: () async {
                      List<MarkingItem> lists = await getData(_refreshController1, params1);
                      if (lists.isNotEmpty) {
                        setState(() => markingDatas1.addAll(lists));
                      }
                    },
                  ),
                  EasyRefresh(
                    taskIndependence: true,
                    enableControlFinishLoad: true,
                    enableControlFinishRefresh: true,
                    emptyWidget: markingDatas2.isEmpty ? const MyEmptyWidget() : null,
                    controller: _refreshController2,
                    header: MaterialHeader(),
                    footer: TaurusFooter(),
                    child: ListView.builder(
                      padding: EdgeInsets.only(top: 4.h, bottom: 10.h),
                      itemBuilder: (context, index) => TestPaperItem(
                        markingItem: markingDatas2[index],
                        markingtype: MarkingListType.values[params2.pageType],
                      ),
                      itemCount: markingDatas2.length,
                    ),
                    onRefresh: () async {
                      List<MarkingItem> lists = await getData(_refreshController2, params2, isReFresh: true);
                      if (lists.isNotEmpty) {
                        setState(() => markingDatas2 = lists);
                      }
                    },
                    onLoad: () async {
                      List<MarkingItem> lists = await getData(_refreshController2, params2);
                      if (lists.isNotEmpty) {
                        setState(() => markingDatas2.addAll(lists));
                      }
                    },
                  ),
                  EasyRefresh(
                    firstRefresh: false,
                    taskIndependence: true,
                    enableControlFinishLoad: true,
                    enableControlFinishRefresh: true,
                    emptyWidget: exceptionalMarkingDatas.isEmpty ? const MyEmptyWidget() : null,
                    controller: _exceptionalRefreshController,
                    header: MaterialHeader(),
                    footer: TaurusFooter(),
                    child: ListView.builder(
                      padding: EdgeInsets.only(top: 4.h, bottom: 10.h),
                      itemBuilder: (context, index) => TestPaperItem(
                        markingItem: exceptionalMarkingDatas[index],
                        markingtype: MarkingListType.values[exceptionalParams.pageType],
                        call: () => _exceptionalRefreshController.callRefresh(),
                      ),
                      itemCount: exceptionalMarkingDatas.length,
                    ),
                    onRefresh: () async {
                      print('参数：' + exceptionalParams.toJson().toString());
                      List<MarkingItem> lists =
                          await getData(_exceptionalRefreshController, exceptionalParams, isReFresh: true);
                      if (lists.isNotEmpty) {
                        setState(() => exceptionalMarkingDatas = lists);
                      }
                    },
                    onLoad: () async {
                      List<MarkingItem> lists = await getData(_exceptionalRefreshController, exceptionalParams);
                      if (lists.isNotEmpty) {
                        setState(() => exceptionalMarkingDatas.addAll(lists));
                      }
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
