import 'dart:async';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:making_school_asignment_app/common/api/retrofit_client.dart';
import 'package:making_school_asignment_app/common/job/marking_models/favor_param.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/home_page/children/homework_review/configuration_files/index.dart';

/// 自定义收藏组件
/// isFavorite  默认是否收藏
/// favoriteNum 默认收藏次数
class FavoriteWidget extends StatefulWidget {
  const FavoriteWidget({super.key});

  @override
  State<FavoriteWidget> createState() => _FavoriteState();
}

class _FavoriteState extends State<FavoriteWidget> with RequestToolMixin {
  late StreamSubscription _listen;
  final _controller = Get.find<HomeworkReviewLogic>();
  final sateData = Get.find<HomeworkReviewLogic>().state;
  RxBool favorite = false.obs; // 初始化数据

  @override
  void initState() {
    _listen = _controller.state.data.listen((e) {
      if (e == null) return;
      if (favorite.value != e.isFav) favorite.value = !favorite.value;
    });
    super.initState();
  }

  @override
  void dispose() {
    _listen.cancel();
    super.dispose();
  }

  Future<void> toFavorite() async {
    try {
      var data = sateData.data.value!;
      var param = sateData.param.value;
      await getClient().toFavStudent(FavorParam(
        homeworkId: param.homeworkId,
        studentId: data.studentId,
        templateId: data.templateId,
        questionNo: data.studentQuestions[0].questionNo,
        isFav: !data.isFav,
      ));
      favorite.value = !data.isFav;
      data.isFav = favorite.value;
    } catch (e) {
      ToastUtils.showError('操作失败，请重试');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4.r),
      child: InkWell(
        onTap: () => easyThrottle('homework_review_collect_btn', () => toFavorite(), duration: const Duration(milliseconds: 500)),
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Obx(() {
              return Icon(
                const IconData(0xe63c, fontFamily: "AlibabaIcon"),
                size: 18.sp,
                color: favorite.value ? const Color.fromRGBO(255, 172, 48, 1) : const Color.fromRGBO(164, 164, 164, 1),
              );
            }),
            SizedBox(width: 6.w),
          ],
        ),
      ),
    );
  }
}

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

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