import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_rx/src/rx_workers/rx_workers.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';

import '../../../data/api/response/zodiac_love_intimacy_response.dart';
import '../../../data/bean/member_info.dart';
import '../../../data/consts/error_code.dart';
import '../../../data/repository/account_repository.dart';
import '../../../data/repository/zodiac_love_intimacy_repository.dart';
import '../../../dialog/login/login_dialog.dart';
import '../../../resource/string.gen.dart';
import '../../../utils/error_handler.dart';
import '../../../utils/http_handler.dart';
import '../../../utils/toast_util.dart';
import '../../store/new_discount/new_discount_page.dart';

/// 星座恋爱分析-未来一周Tab-Controller
@injectable
class ZodiacLoveFutureWeekController extends BaseController {
  /// 星座恋爱分析的Repository
  final ZodiacLoveIntimacyRepository zodiacLoveIntimacyRepository;

  /// 用户信息
  final AccountRepository accountRepository;

  /// 分析列表
  final Rxn<ZodiacLoveIntimacyResponse> zodiacLoveIntimacyResp =
      Rxn<ZodiacLoveIntimacyResponse>();

  /// 当前用户的会员信息
  Rxn<MemberInfo> get memberInfo => accountRepository.memberStatusInfo;

  /// 报告是否生成中
  RxBool isReportCreating = false.obs;

  ZodiacLoveFutureWeekController(
    this.zodiacLoveIntimacyRepository,
    this.accountRepository,
  );

  @override
  void onInit() {
    super.onInit();
    ever(memberInfo, (info) {
      // 如果是会员了，重新拉取数据
      if (info != null) {
        if (info.isMember) {
          _getZodiacLoveIntimacyFutureWeek();
        }
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    if (memberInfo.value?.isMember == true) {
      _getZodiacLoveIntimacyFutureWeek();
    }
  }

  /// 星座恋爱分析-获取未来一周分析
  void _getZodiacLoveIntimacyFutureWeek() async {
    // 生成中
    isReportCreating.value = true;

    try {
      ZodiacLoveIntimacyResponse resp =
          await zodiacLoveIntimacyRepository.getZodiacLoveIntimacyFutureWeek();
      zodiacLoveIntimacyResp.value = resp;
    } catch (error) {
      if (error is ServerErrorException) {
        // 未登录
        if (error.code == ErrorCode.noLoginError) {
          ToastUtil.show(StringName.accountNoLogin);
          LoginDialog.show();
        } else if (error.code == ErrorCode.noMember) {
          // 需要VIP
          ToastUtil.show(StringName.needVipTip);
          NewDiscountPage.start();
        } else {
          ErrorHandler.toastError(error);
        }
      } else {
        ErrorHandler.toastError(error);
      }
    } finally {
      // 生成结束
      isReportCreating.value = false;
    }
  }

  /// 点击解锁按钮
  void clickUnlockBtn() {
    // 跳转去会员活动页
    NewDiscountPage.start();
  }
}
