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/repository/account_repository.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/utils/toast_util.dart';

import '../../data/repository/store_repository.dart';
import '../../dialog/tips_dialog.dart';
import '../../utils/atmob_log.dart';
import '../../utils/http_handler.dart';

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

  final AccountRepository accountRepository;
  final StoreRepository storeRepository;

  RxBool get hasAutoRenewal => storeRepository.hasAutoRenewal;

  AutoRenewalController(this.accountRepository, this.storeRepository) {
    AtmobLog.d(tag, '$tag....init');
    checkMemberAgreement();
  }

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

    AtmobLog.d(tag, '$tag....onInit');
  }

  @override
  void onReady() {
    super.onReady();
    AtmobLog.d(tag, '$tag....onReady');
  }

  @override
  void onClose() {
    super.onClose();
    AtmobLog.d(tag, '$tag....onClose');
  }

  void clickBack() {
    Get.back();

  }

  void clickUnSignAutoRenewal(){
    TipsDialog.show(
      title: StringName.tipsDialogTitle,
      desc: StringName.autoRenewalTipDialogDesc,
      btnConfirmText: StringName.dialogCancel,
      btnCancelText: StringName.dialogClose,
      btnCancel: () {
        unSignAutoRenewal();
      },
    );
  }

  Future<void> unSignAutoRenewal() async {
    AtmobLog.d(tag, '$tag....unSignAutoRenewal');
    try {
      await storeRepository.unSignMemberAgreement();
      ToastUtil.show("已关闭自动续费服务");
      checkMemberAgreement();
    } catch (error) {
      if (error is ServerErrorException) {
        ToastUtil.show(error.message);
      } else {
        ToastUtil.show("请重试");
      }
    }
  }

  Future<void> checkMemberAgreement() async {
    AtmobLog.d(tag, '$tag....checkMemberAgreement');
    try {
      await storeRepository.checkMemberAgreement();
    } catch (error) {
      if (error is ServerErrorException) {
        ToastUtil.show(error.message);
      } else {
        debugPrint("checkMemberAgreement failed: $error");
      }
    }
  }
}
