import 'dart:io';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/api/response/user_info_response.dart';
import 'package:keyboard/data/repository/account_repository.dart';
import 'package:keyboard/data/repository/characters_repository.dart';
import 'package:keyboard/dialog/character_details_dialog.dart';
import 'package:keyboard/dialog/login/login_dialog.dart';
import 'package:keyboard/module/character/character_controller.dart';
import 'package:keyboard/module/store/store_page.dart';
import 'package:keyboard/module/store/ticket/discount_ticket_dialog.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard/utils/daily_limiter_util.dart';
import 'package:keyboard/utils/http_handler.dart';
import 'package:keyboard/utils/toast_util.dart';
import 'package:lottie/lottie.dart';

import '../../../data/bean/character_group_info.dart';
import '../../../data/bean/character_info.dart';
import '../../../data/bean/keyboard_info.dart';
import '../../../data/bean/member_info.dart';
import '../../../resource/assets.gen.dart';
import '../../../utils/error_handler.dart';
import '../../store/new_discount/new_discount_page.dart';
import '../../store/suprise/surprise_dialog.dart';

@injectable
class CharacterGroupContentController extends BaseController {
  final tag = "CharacterGroupContentController";

  Rx<KeyboardInfo> get currentKeyboardInfo =>
      Get.find<CharacterController>().currentKeyboardInfo;

  Rx<CharacterGroupInfo> get currentCharacterGroupInfo =>
      Get.find<CharacterController>().currentCharacterGroupInfo;
  final CharactersRepository charactersRepository;

  final AccountRepository accountRepository;

  bool get isVipUser => accountRepository.isVipUser;

  bool get isLogin => accountRepository.isLogin.value;

  bool get isVip =>
      memberStatusInfo != null && memberStatusInfo!.isMember && isLogin;

  MemberInfo? get memberStatusInfo => accountRepository.memberStatusInfo.value;

  UserInfoResponse? get userInfo => accountRepository.userInfo.value;

  CharacterGroupContentController(
    this.charactersRepository,
    this.accountRepository,
  );

  RxList<CharacterInfo> characterList = <CharacterInfo>[].obs;
  RxInt currentListCount = 0.obs;

  RxInt currentPage = 1.obs;
  late EasyRefreshController refreshController;

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

    refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
    // 等待页面渲染完成后再加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      refreshData();
    });
    everAll([currentCharacterGroupInfo, currentKeyboardInfo], (_) async {
      await refreshData();
    });
  }

  @override
  onReady() async {
    super.onReady();

  }

  // 下拉刷新
  Future<void> refreshData() async {
    AtmobLog.d(
      tag,
      'refreshData ${currentCharacterGroupInfo.value.id}, ${currentKeyboardInfo.value.id}',
    );
    currentPage.value = 1;
    await getCurrentCharacterListInfo(isRefresh: true);
    refreshController.finishRefresh();
    refreshController.resetFooter(); // 允许加载更多
  }

  // 上拉加载更多
  Future<void> loadMoreData() async {
    if (characterList.length >= currentListCount.value) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    currentPage.value++;
    await getCurrentCharacterListInfo(isRefresh: false);
    refreshController.finishLoad(IndicatorResult.success);
  }

  // 获取角色列表
  Future<void> getCurrentCharacterListInfo({bool isRefresh = false}) async {
    var response = await charactersRepository.getCharactersPage(
      groupId: currentCharacterGroupInfo.value.id.toString(),
      page: currentPage.value,
      keyboardId: currentKeyboardInfo.value.id.toString(),
    );
    if (isRefresh) {
      characterList.value = response.characterInfos;
    } else {
      characterList.addAll(response.characterInfos);
    }
    currentListCount.value = response.count;
  }

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

  void itemButtonClick(CharacterInfo characterInfo) {
    AtmobLog.d(tag, 'characterInfo ${characterInfo.toJson()} ');
    if (isLogin == false) {
      ToastUtil.show('请先登录~');
      LoginDialog.show();
      return;
    }
    CharacterDetailsDialog.show(
      characterInfo: characterInfo,
      clickCallback: () {
        if (characterInfo.isAdd == false) {

          addCharacter(characterInfo);
        }
      },
      onDismiss: () {
        if (Platform.isAndroid) {
          DailyLimiterUtil.run(
            actionKey: 'DiscountTicketDialog', // 唯一标识该弹窗逻辑
            condition:
            characterInfo.isVip == true &&
                characterInfo.isLock == true &&
                !isVipUser,
            onExecute: () {
              DiscountTicketDialog.show(
                clickConfirm: () {
                  NewDiscountPage.start();
                },
              );
            },
          );
        }else if (Platform.isIOS) {
          DailyLimiterUtil.run(
            actionKey: 'SurpriseDialog', // 唯一标识该弹窗逻辑
            condition:
            characterInfo.isVip == true &&
                characterInfo.isLock == true &&
                !isVipUser,
            onExecute: () {
              SurpriseDialog.show(
                clickConfirm: () {
                  NewDiscountPage.start();
                },
              );
            },
          );

        }
      },
    );
  }

  Future<void> addCharacter(CharacterInfo characterInfo) async {
    try {
      final characterAddResponse = await charactersRepository.characterAdd(
        characterId: characterInfo.id.toString(),
        keyboardId: currentKeyboardInfo.value.id.toString(),
      );

      int index = characterList.indexWhere(
        (element) => element.id == characterAddResponse.characterInfo.id,
      );
      if (index != -1) {
        characterList[index] = characterAddResponse.characterInfo;
      }

      ToastUtil.show('添加成功~');
    } catch (error) {
      if (error is ServerErrorException) {
        if (error.code == 1005) {
          StorePage.start();
          ToastUtil.show(error.message);
        } else {
          ToastUtil.show(error.message);
        }
      } else {
        ErrorHandler.toastError(error);
      }
    }
  }

  void unlockCharacter(CharacterInfo characterInfo) {
    charactersRepository
        .characterUnlock(
          characterId: characterInfo.id.toString(),
          keyboardId: currentKeyboardInfo.value.id.toString(),
        )
        .then((characterUnlockResponse) {
          int index = characterList.indexWhere(
            (element) => element.id == characterUnlockResponse.characterInfo.id,
          );
          if (index != -1) {
            characterList[index] = characterUnlockResponse.characterInfo;
          }
          ToastUtil.show('解锁成功~');
        })
        .catchError((error) {
          if (error is ServerErrorException) {
            if (error.code == 1005) {
              ToastUtil.show('请开通会员解锁权益~');
              StorePage.start();
            }
            ToastUtil.show(error.message);
          } else {
            ErrorHandler.toastError(error);
          }
        });
  }
}
