/*
 * @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:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:marking_app/common/mixin/common.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/model/job/job_task_item.dart';
import 'package:marking_app/pages/homework_correction/components/new_version_of_homework/homework_tasks_view_item.dart';
import 'package:marking_app/provider/review_provider.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.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_list_params.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/easy_refresh/mixin/refresh_data_handle.dart';

part 'index.g.dart';

// 作业主页
class HomeworkCorrection extends StatefulHookConsumerWidget {
  const HomeworkCorrection({Key? key}) : super(key: key);

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

class _HomeworkCorrectionState extends ConsumerState<HomeworkCorrection>
    with
        CommonMixin,
        SingleTickerProviderStateMixin,
        RefreshDataHandle<JobTaskItem, MarkingListParams>,
        AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

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

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

  /* 已阅完 */
  late final EasyRefreshController _refreshController2;
  RemoveListener? _currentTaskIdListener;
  final MarkingListParams params2 = MarkingListParams(
    isFinish: true,
    page: RequestConfig.basePage.page,
    limit: RequestConfig.basePage.limit,
    pageType: 0,
  );
  List<JobTaskItem> markingDatas2 = [];

  /* 发起请求 */
  Future<List<JobTaskItem>> getData(
    EasyRefreshController controller,
    MarkingListParams params, {
    bool isReFresh = false,
  }) async {
    RestClient client = await getClient();
    BasePageData<JobTaskItem>? results = await toRefreshData(
      controller,
      api: client.getJobsByPage,
      params: params,
      isReFresh: isReFresh,
      context: context,
    );
    if (results != null) return results.items;
    return [];
  }

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

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

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

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

  /// 刷新方法
  Future<void> onMyRefresh(EasyRefreshController controller, MarkingListParams params, int tab) async {
    params.page = RequestConfig.basePage.page;
    List<JobTaskItem> lists = await getData(controller, params, isReFresh: true);
    try {
      tab == 1 ? (markingDatas1 = lists) : (markingDatas2 = lists);
    } catch (e) {}
    toUpState(setState, () {}, mounted);
  }

  /// 加载方法
  Future<void> onMyLoad(EasyRefreshController controller, MarkingListParams params, int tab) async {
    params.page++;
    List<JobTaskItem> lists = await getData(controller, params);
    if (lists.isNotEmpty) {
      tab == 1 ? markingDatas1.addAll(lists) : markingDatas2.addAll(lists);
      toUpState(setState, () {}, mounted);
    }
  }

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

    return AnnotatedRegion(
      value: const SystemUiOverlayStyle(
        systemNavigationBarColor: Color(0xFF000000),
        systemNavigationBarDividerColor: null,
        statusBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      child: Scaffold(
        backgroundColor: Color.fromRGBO(244, 244, 244, 1),
        body: OrientationBuilder(
          builder: (BuildContext context, Orientation orientation) {
            return Column(
              children: <Widget>[
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
                  padding: EdgeInsets.only(bottom: 9.h, top: 4.h),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: SizedBox(),
                      ),
                      Expanded(
                        flex: 4,
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 2.h),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: const Color.fromRGBO(243, 243, 243, 1),
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: TabBar(
                            padding: EdgeInsets.zero,
                            indicatorPadding: EdgeInsets.zero,
                            indicatorWeight: 0,
                            labelPadding: EdgeInsets.symmetric(horizontal: 2.w),
                            controller: _tabController,
                            unselectedLabelStyle: TextStyle(
                              fontSize: 14.sp,
                              color: const Color.fromRGBO(69, 83, 100, 1),
                            ),
                            labelStyle: TextStyle(
                              fontSize: 14.sp,
                              color: const Color.fromRGBO(104, 136, 253, 1),
                            ),
                            // labelColor: const Color.fromRGBO(45, 56, 76, 1),
                            indicator: const BoxDecoration(),
                            onTap: (index) {
                              setState(() {
                                _tabIndex = index;
                                if (index == 1 && completedToRefresh) {
                                  // 已阅卷
                                  _refreshController2.callRefresh();
                                  completedToRefresh = false;
                                }
                              });
                            },
                            tabs: <Widget>[
                              Tab(
                                iconMargin: EdgeInsets.zero,
                                height: 34.h,
                                child: Container(
                                  width: 140.w,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    color: _tabIndex == 0 ? const Color.fromRGBO(255, 255, 255, 1) : null,
                                    borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                  ),
                                  child: quickText(
                                    '待批阅',
                                    size: 14.sp,
                                    color: _tabIndex == 0
                                        ? Theme.of(context).primaryColor
                                        : const Color.fromRGBO(80, 94, 110, 1),
                                    fontWeight: _tabIndex == 0 ? FontWeight.bold : null,
                                  ),
                                ),
                              ),
                              Tab(
                                iconMargin: EdgeInsets.zero,
                                height: 34.h,
                                child: Container(
                                  width: 140.w,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    color: _tabIndex == 1 ? const Color.fromRGBO(255, 255, 255, 1) : null,
                                    borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                  ),
                                  child: quickText(
                                    '已批阅',
                                    size: 14.sp,
                                    color: _tabIndex == 1
                                        ? Theme.of(context).primaryColor
                                        : const Color.fromRGBO(80, 94, 110, 1),
                                    fontWeight: _tabIndex == 1 ? FontWeight.bold : null,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {},
                          child: Icon(Icons.settings_outlined, color: Color.fromRGBO(44, 48, 63, 1), size: 24.sp),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: IndexedStack(
                    index: _tabIndex,
                    children: <Widget>[
                      $EasyRefresh(
                        controller: _refreshController1,
                        params: params1,
                        tab: 1,
                        data: markingDatas1,
                        onLoad: onMyLoad,
                        onRefresh: onMyRefresh,
                      ),
                      $EasyRefresh(
                        controller: _refreshController2,
                        params: params2,
                        tab: 2,
                        data: markingDatas2,
                        onLoad: onMyLoad,
                        onRefresh: onMyRefresh,
                      ),
                    ],
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

/// 已阅卷
/// OnRefreshCallback? onRefresh
///
@swidget
Widget $easyRefresh({
  required EasyRefreshController controller,
  required Future<void> Function(EasyRefreshController controller, MarkingListParams params, int tab) onRefresh,
  required Future<void> Function(EasyRefreshController controller, MarkingListParams params, int tab) onLoad,
  required MarkingListParams params,
  required List<JobTaskItem> data,
  required int tab,
}) {
  bool completed = tab == 2; // 是否是待批阅
  bool isPadFlag = isPad();
  return EasyRefresh(
    firstRefresh: true,
    taskIndependence: true,
    enableControlFinishLoad: true,
    enableControlFinishRefresh: true,
    emptyWidget: data.isEmpty ? const MyEmptyWidget() : null,
    controller: controller,
    header: MaterialHeader(),
    footer: TaurusFooter(),
    child: completed && isPadFlag
        ? GridView(
            padding: EdgeInsets.only(top: 11.h, bottom: 10.h, left: 12.w, right: 12.w),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, //横轴三个子widget
                mainAxisSpacing: 10.h,
                crossAxisSpacing: 6.w,
                childAspectRatio: 2.2 //宽高比为1时，子widget
                ),
            children: data.map((e) {
              return $ReviewedItem(jobTaskItem: e);
            }).toList(),
          )
        : ListView.builder(
            padding: EdgeInsets.only(top: 11.h, bottom: 10.h, left: 12.w, right: 12.w),
            itemBuilder: (context, index) {
              return HomeworkTasksViewItem(
                completed: completed,
                jobTaskItem: data[index],
                call: () => controller.callRefresh(),
              );
            },
            itemCount: data.length,
          ),
    onRefresh: () => onRefresh(controller, params, tab),
    onLoad: () => onLoad(controller, params, tab),
  );
}

@swidget
Widget $reviewedItem(BuildContext context, {required JobTaskItem jobTaskItem}) {
  EdgeInsets padEdg = EdgeInsets.symmetric(horizontal: 10.w);
  return Container(
    padding: EdgeInsets.only(top: 10.h),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(6.r),
      color: Colors.white,
      boxShadow: [
        BoxShadow(
          color: const Color.fromRGBO(210, 216, 241, 1),
          offset: Offset.zero, //阴影y轴偏移量
          blurRadius: 5.8, //阴影模糊程度
          spreadRadius: 0, //阴影扩散程度
        )
      ],
    ),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        // 顶部任务名称
        Padding(
          padding: padEdg,
          child: Row(
            children: [
              Container(
                width: 32.w,
                height: 18.h,
                alignment: Alignment.center,
                padding: EdgeInsets.only(left: 2.w),
                decoration: BoxDecoration(
                  color: jobTaskItem.markingTypeEnum.name == '作业'
                      ? const Color.fromRGBO(104, 136, 253, 1)
                      : const Color.fromRGBO(255, 175, 56, 1),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(18.r),
                    topRight: Radius.circular(3.r),
                    bottomLeft: Radius.circular(4.r),
                    bottomRight: Radius.circular(4.r),
                  ),
                ),
                margin: EdgeInsets.only(right: 4.w),
                child: quickText(jobTaskItem.markingTypeEnum.name, color: Colors.white, size: 10.sp),
              ),
              quickText(
                jobTaskItem.title,
                size: 16.sp,
                color: Color.fromRGBO(70, 70, 70, 1),
                fontWeight: FontWeight.bold,
              )
            ],
          ),
        ),

        Padding(
          padding: padEdg,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              quickText(
                jobTaskItem.createTime.substring(0, 10),
                color: Color.fromRGBO(97, 97, 97, 1),
                size: 10.sp,
                fontWeight: FontWeight.w500,
              ),
              quickText(' / ', color: Color.fromRGBO(76, 199, 147, 1), size: 10.sp, fontWeight: FontWeight.w500),
              quickText(
                '参与班级：2',
                color: Color.fromRGBO(76, 199, 147, 1),
                size: 10.sp,
                fontWeight: FontWeight.w600,
              ),
              quickText(' / ', color: Color.fromRGBO(116, 145, 253, 1), size: 10.sp, fontWeight: FontWeight.w500),
              quickText(
                '科目：' + jobTaskItem.subjectName,
                color: Color.fromRGBO(116, 145, 253, 1),
                size: 10.sp,
                fontWeight: FontWeight.w600,
              ),
            ],
          ),
        ),

        Container(
          padding: EdgeInsets.symmetric(vertical: 6.h),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(6.r), bottomRight: Radius.circular(6.r)),
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: const Color.fromRGBO(0, 0, 0, 0.15),
                offset: Offset(0, -0.0001), //阴影y轴偏移量
                blurRadius: 4, //阴影模糊程度
                spreadRadius: 0, //阴影扩散程度
              )
            ],
          ),
          child: Row(children: [
            Expanded(
                child: InkWell(
              onTap: () => easyThrottle('go_to_homework_report', () => {}),
              child: Container(
                alignment: Alignment.center,
                child: quickText('查看报告', color: Color.fromRGBO(118, 118, 118, 1), size: 11.sp),
              ),
            )),
          ]),
        ),
      ],
    ),
  );
}
