// 右侧抽屉（评阅记录）
import 'package:collection/collection.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.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_page_data.dart';
import 'package:marking_app/common/model/enum/KeyboardType.dart';
import 'package:marking_app/common/model/marking/marking_text_question_tab.dart';
import 'package:marking_app/common/model/marking/review_records_item.dart';
import 'package:marking_app/common/model/marking/review_records_params.dart';
import 'package:marking_app/components/marking/rating_progress_view.dart';
import 'package:marking_app/pages/marking/provider/rating_progress_provider.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/easy_refresh/mixin/refresh_data_handle.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:marking_app/utils/request/rest_client.dart';

part 'review_records_view.g.dart';

class ReviewRecords extends StatefulHookConsumerWidget {
  final int markingUserId;
  final String? questionNum;
  final List<MarkingTextQuestionTab> tabs;
  final ScreenDirection direction;
  final String tabName;
  final Function(int detailId, String questionNum) call;
  const ReviewRecords(
      {required this.markingUserId,
      required this.tabName,
      required this.tabs,
      this.questionNum,
      required this.direction,
      required this.call,
      super.key});

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

class _ReviewRecordsState extends ConsumerState<ReviewRecords>
    with CommonMixin, RefreshDataHandle<ReviewRecordsItem, ReviewRecordsParams> {
  late final EasyRefreshController _refreshController;
  late final List<String> _currentTabs;
  late final ReviewRecordsParams _params;
  List<ReviewRecordsItem> _records = [];

  @override
  void initState() {
    super.initState();
    _refreshController = EasyRefreshController();
    _currentTabs = widget.tabs.map((e) => e.questionNum + '题').toList();
    _params = new ReviewRecordsParams(
      page: RequestConfig.basePage.page,
      limit: RequestConfig.basePage.limit,
      questionNum: widget.questionNum ?? '',
      markingUserId: widget.markingUserId,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController?.dispose();
  }

  /* 发起请求 */
  Future<List<ReviewRecordsItem>> getData(EasyRefreshController controller, ReviewRecordsParams params,
      {bool isReFresh = false}) async {
    print('进来....................');
    if (!isReFresh) {
      params.page++;
    } else {
      params.page = 1;
    }
    RestClient client = await getClient();
    BasePageData<ReviewRecordsItem>? results = await toRefreshDataWithPath(
      controller,
      api: client.getMarkingRecords,
      params: params,
      isReFresh: isReFresh,
      context: context,
      pahtVal: widget.markingUserId.toString(),
    );
    List<ReviewRecordsItem> theRecordsData = results?.items ?? [];
    isReFresh ? setState(() => _records = theRecordsData) : setState(() => _records.addAll(theRecordsData));
    return _records;
  }

  @override
  Widget build(BuildContext context) {
    EndDrawerViewEnum theVal = ref.watch(ratingProgressProvider);
    if (theVal == EndDrawerViewEnum.RATING_PROGRESS)
      return RatingProgressView(
        direction: widget.direction,
        markingUserId: widget.markingUserId,
      );

    if (widget.questionNum == null) return Container();

    return SafeArea(
      top: false,
      bottom: false,
      child: Drawer(
        width: MediaQuery.of(context).size.width * (ScreenDirection.HORIZONTAL_SCREEN != widget.direction ? 0.7 : 0.35),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(left: 4.w, right: 4.w, top: 10.h),
              child: Row(
                children: [
                  quickText('题型：', size: 20.sp),
                  Expanded(
                    child: DropdownButtonFormField2<String>(
                      value: _params.questionNum + '题',
                      isExpanded: true,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.symmetric(vertical: 12.h),
                        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12.sp)),
                      ),
                      hint: const Text(
                        '选择试题题型',
                        style: TextStyle(fontSize: 14),
                      ),
                      items: _currentTabs
                          .map((item) => DropdownMenuItem<String>(
                              value: item, child: Text(item, style: TextStyle(fontSize: 16.sp))))
                          .toList(),
                      onChanged: (value) {
                        if (value != null) {
                          var _tab = widget.tabs.firstWhereOrNull((element) => value.contains(element.questionNum));
                          if (_tab != null) {
                            _params.questionNum = _tab.questionNum;
                            _refreshController.callRefresh();
                          }
                        }
                      },
                      buttonStyleData: const ButtonStyleData(
                        padding: EdgeInsets.only(right: 8),
                      ),
                      iconStyleData: const IconStyleData(
                        icon: Icon(
                          Icons.arrow_drop_down,
                          color: Colors.black45,
                        ),
                        iconSize: 24,
                      ),
                      dropdownStyleData: DropdownStyleData(
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(15)),
                      ),
                      menuItemStyleData: MenuItemStyleData(padding: EdgeInsets.symmetric(horizontal: 14.h)),
                    ),
                  )
                ],
              ),
              //  quickText('题型：' + widget.tabName),
            ),
            Expanded(
              child: EasyRefresh(
                firstRefresh: true,
                taskIndependence: true,
                enableControlFinishLoad: true,
                enableControlFinishRefresh: true,
                emptyWidget: _records.isEmpty ? MyEmptyWidget(imgHeight: 50.w, imgWidth: 50.w) : null,
                controller: _refreshController,
                header: MaterialHeader(),
                footer: TaurusFooter(),
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: DataTable(
                    horizontalMargin: 10.w,
                    columnSpacing: 0.w,
                    columns: [
                      DataColumn(label: Container(child: Text('编号'), width: 30.w)),
                      DataColumn(label: Container(child: Text('得分'), width: 30.w)),
                      DataColumn(label: Container(child: Text('批阅时间'), width: 80.w)),
                    ],
                    rows: _records
                        .map((e) => DataRow(
                              cells: [
                                DataCell(quickText(e.sort),
                                    onTap: () => widget.call(e.markingUserDetailId, _params.questionNum)),
                                DataCell(quickText(e.score),
                                    onTap: () => widget.call(e.markingUserDetailId, _params.questionNum)),
                                DataCell(
                                    quickText(e.finishTime.length > 13 ? e.finishTime.substring(0, 16) : e.finishTime),
                                    onTap: () => widget.call(e.markingUserDetailId, _params.questionNum))
                              ],
                            ))
                        .toList(),
                  ),
                ),
                onRefresh: () async => getData(_refreshController, _params, isReFresh: true),
                onLoad: () async => getData(_refreshController, _params),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

@swidget
Widget $reviewRecordsItem({required ReviewRecordsItem item, required Function(ReviewRecordsItem) call}) {
  return Container(
    child: Row(
      children: [
        quickText(item.sort),
        quickText(item.score),
        quickText(item.finishTime),
      ],
    ),
  );
}
