import 'package:flutter/Material.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import '../../data/api/response/user_info_response.dart';
import '../../data/api/response/zodiac_love_intimacy_love_info_response.dart';
import '../../data/consts/error_code.dart';
import '../../data/consts/event_report.dart';
import '../../data/repository/account_repository.dart';
import '../../data/repository/zodiac_love_intimacy_repository.dart';
import '../../dialog/login/login_dialog.dart';
import '../../handler/event_handler.dart';
import '../../resource/string.gen.dart';
import '../../router/app_page_arguments.dart';
import '../../utils/age_zodiac_sign_util.dart';
import '../../utils/atmob_log.dart';
import '../../utils/error_handler.dart';
import '../../utils/http_handler.dart';
import '../../utils/toast_util.dart';
import '../store/new_discount/new_discount_page.dart';
import '../user_profile/user_profile_page.dart';
import 'enums/zodiac_love_intimacy_tab.dart';

/// 星座恋爱分析Controller
@injectable
class ZodiacLoveIntimacyController extends BaseController
    with GetTickerProviderStateMixin {
  final String _tag = "ZodiacLoveIntimacyController";

  /// 账户信息Repository
  final AccountRepository accountRepository;

  /// 星座恋爱分析Repository
  final ZodiacLoveIntimacyRepository zodiacLoveIntimacyRepository;

  /// Tab列表
  RxList<ZodiacLoveIntimacyTab> tabBarList = ZodiacLoveIntimacyTab.values.obs;

  /// Tab控制器
  late final TabController tabController;

  /// PageView控制器
  late final PageController pageController;

  /// PageView是否允许滑动切换
  RxBool isPageViewSwipeEnabled = true.obs;

  /// 当前Tab的索引
  Rx<int> currentTabIndex = 0.obs;

  /// 当前用户信息
  Rxn<UserInfoResponse> get userInfo => accountRepository.userInfo;

  /// 星座恋爱分析-基础信息
  Rxn<ZodiacLoveIntimacyLoveInfoResponse> zodiacLoveIntimacyLoveInfoResponse =
      Rxn<ZodiacLoveIntimacyLoveInfoResponse>();

  /// 我的星座信息
  Zodiac? get myZodiacInfo {
    String? birthday =
        zodiacLoveIntimacyLoveInfoResponse.value?.birthday ??=
            userInfo.value?.birthday;
    int? gender =
        zodiacLoveIntimacyLoveInfoResponse.value?.gender ??=
            userInfo.value?.gender;
    return getUserZodiacInfo(birthday, gender);
  }

  /// Ta的星座信息
  Zodiac? get taZodiacInfo {
    final birthday = zodiacLoveIntimacyLoveInfoResponse.value?.targetBirthday;
    final gender = zodiacLoveIntimacyLoveInfoResponse.value?.targetGender;
    return getUserZodiacInfo(birthday, gender);
  }

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

  @override
  void onInit() {
    super.onInit();
    _initArgs();
    _getZodiacLoveIntimacyLoveInfo();
  }

  /// 初始化参数
  void _initArgs() {
    final arguments = Get.arguments as Map<String, dynamic>?;

    // 当前索引
    ZodiacLoveIntimacyTab? tab;
    if (arguments?[AppPageArguments.index] == null) {
      AtmobLog.i(_tag, '没有传递 index 参数');
    } else {
      final int? index = arguments?[AppPageArguments.index] as int?;
      if (index != null) {
        tab = ZodiacLoveIntimacyTab.fromIndex(index);
        if (tab != null) {
          AtmobLog.i(_tag, "index: ${tab.tabIndex}");
        }
      }
    }

    // 默认选中第一个Tab
    tab ??= ZodiacLoveIntimacyTab.today;

    // 创建PageController和TabController，并设置当前选中的index为初始索引
    pageController = PageController(initialPage: tab.tabIndex);
    tabController = TabController(
      initialIndex: tab.tabIndex,
      length: tabBarList.length,
      vsync: this,
    );
    currentTabIndex.value = tab.tabIndex;

    if (tab.tabIndex == ZodiacLoveIntimacyTab.today.tabIndex) {
      EventHandler.report(EventId.event_08001);
    } else if (tab.tabIndex == ZodiacLoveIntimacyTab.futureWeek.tabIndex) {
      EventHandler.report(EventId.event_08002);
    }
    currentTabIndex.listen((index) {
      if(index==ZodiacLoveIntimacyTab.today.tabIndex) {
        EventHandler.report(EventId.event_08001);
      }
      else if(index==ZodiacLoveIntimacyTab.futureWeek.tabIndex) {
        EventHandler.report(EventId.event_08002);
      }
    });
  }

  /// 返回
  void clickBack() {
    Get.back();
  }

  @override
  void onClose() {
    tabController.dispose();
    pageController.dispose();
    super.onClose();
  }

  /// 处理Tab切换，联动PageView
  void handleTabChange(int index) {
    pageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.fastOutSlowIn,
    );
  }

  /// 处理PageView切换，联动Tab
  void handlePageChange(int index) {
    tabController.animateTo(index, duration: const Duration(milliseconds: 300));
    currentTabIndex.value = index;
  }

  /// 获取星座恋爱分析-基本信息
  void _getZodiacLoveIntimacyLoveInfo() async {
    try {
      ZodiacLoveIntimacyLoveInfoResponse resp =
          await zodiacLoveIntimacyRepository.getZodiacLoveIntimacyLoveInfo();
      zodiacLoveIntimacyLoveInfoResponse.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 if (error.code == ErrorCode.noSetBirthday) {
          // 未设置生日
          ErrorHandler.toastError(error);
          await UserProfilePage.start();
        } else {
          ErrorHandler.toastError(error);
        }
      } else {
        ErrorHandler.toastError(error);
      }
    }
  }

  /// 获取用户的星座信息
  Zodiac? getUserZodiacInfo(String? birthday, int? gender) {
    if (birthday?.isEmpty != false || gender == null) {
      return null;
    }
    final zodiac = AgeZodiacSignUtil.getZodiacWithGenderLabel(
      birthday!,
      gender,
    );
    if (zodiac.name == '未知星座') {
      return null;
    }
    return zodiac;
  }
}
