import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/resource/string.gen.dart';

import '../../router/app_page_arguments.dart';
import '../../utils/atmob_log.dart';
import 'enums/intimacy_analyse_tab.dart';

/// 亲密度分析Controller
@injectable
class IntimacyAnalyseController extends BaseController
    with GetTickerProviderStateMixin {
  final String _tag = "IntimacyAnalyseController";

  /// Tab列表
  RxList<String> tabBarList =
      IntimacyAnalyseTab.values.map((item) => item.getTabName()).toList().obs;

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

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

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

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

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

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

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

  /// 返回上一页
  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.easeInToLinear,
    );
  }

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