import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.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/job/job_collect_params.dart';
import 'package:marking_app/pages/common/event_bus_mixin.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/request/rest_client.dart';

/// 自定义收藏组件
/// isFavorite  默认是否收藏
/// favoriteNum 默认收藏次数
class FavoriteWidget extends StatefulWidget {
  final Function call;
  FavoriteWidget(this.call, {Key? key}) : super(key: key);

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

class _FavoriteState extends State<FavoriteWidget> with EventBusMixin<JobQuestionsSwitch>, CommonMixin {
  Future<JobCollectParams?>? _future; // 考试试卷
  JobQuestionsSwitch? _eventModel;
  @override
  void initState() {
    super.initState();
    eventOn(callback: (JobQuestionsSwitch eventModel) {
      _eventModel = eventModel;
      _future = getData(eventModel.taskId, eventModel.studentId, eventModel.paperId);
      toUpState(setState, () {}, mounted);
    });
  }

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

  Future<JobCollectParams?> getData(int taskId, int studentId, int paperId) async {
    try {
      RestClient _client = await getClient();
      BaseStructureResult<bool> res = await _client.getJobCollect(taskId, studentId, paperId);
      if (res.success) return JobCollectParams(paperId, taskId, studentId, res.data ?? false);
    } catch (e) {}

    return null;
  }

  Future<void> toFavorite(JobCollectParams favoriteVal) async {
    try {
      if (_eventModel?.paperId == null) return;
      ToastUtils.showLoading();
      RestClient _client = await getClient();
      favoriteVal.isCollect = !favoriteVal.isCollect;
      favoriteVal.paperId = _eventModel!.paperId;
      BaseStructureResult<bool> res = await _client.toJobFavoriteCancel(favoriteVal);
      if (res.success) {
        _future = getData(favoriteVal.taskId, favoriteVal.studentId, _eventModel!.paperId);
        widget.call();
        toUpState(setState, () {}, mounted);
      } else {
        ToastUtils.showError(res.message ?? '操作失败，请重试');
      }
    } catch (e) {
    } finally {
      ToastUtils.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_future == null) return Container();

    return MyFutureBuilder.buildFutureBuilderOfSingleInstance<JobCollectParams>(context, _future!, (favoriteVal) {
      if (favoriteVal == null) return Container();
      var _isFavorite = favoriteVal.isCollect;
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 4.r),
        child: InkWell(
          onTap: () => easyThrottle('homework_review_collect_btn', () => toFavorite(favoriteVal),
              duration: Duration(milliseconds: 500)),
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Icon(
                const IconData(0xe63c, fontFamily: "AlibabaIcon"),
                size: 18.sp,
                color: _isFavorite ? Color.fromRGBO(255, 172, 48, 1) : Color.fromRGBO(164, 164, 164, 1),
              ),
              SizedBox(width: 6.w),
            ],
          ),
        ),
      );
    }, widget: Container());
  }
}

class JobQuestionsSwitch extends Object {
  final int taskId;
  final int studentId;
  final int paperId;

  JobQuestionsSwitch(this.taskId, this.studentId, this.paperId);
}
