import 'dart:io';

import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/api/response/member_trial_info_response.dart';
import 'package:location/data/bean/member_status_info.dart';
import 'package:location/data/bean/user_info.dart';
import 'package:location/data/consts/error_code.dart';
import 'package:location/data/repositories/config_repository.dart';
import 'package:location/handler/error_handler.dart';
import 'package:location/module/avatar/user_avatar_view.dart';
import 'package:location/module/feedback/feed_back_page.dart';
import 'package:location/module/login/login_page.dart';
import 'package:location/module/member/member_page.dart';
import 'package:location/module/urgent_contact/urgent_contact_page.dart';
import 'package:location/resource/string.gen.dart';
import 'package:location/utils/http_handler.dart';

import '../../data/repositories/account_repository.dart';
import '../../data/repositories/member_repository.dart';
import '../../dialog/common_alert_dialog_impl.dart';
import '../../dialog/user_avatar_dialog.dart';
import '../../sdk/wechat/wechat_share_util.dart';
import '../../utils/app_info_util.dart';
import '../../utils/toast_util.dart';
import '../about/about_page.dart';
import '../browser/browser_view.dart';
import '../permission/permission_setting_page.dart';
import 'mine_expiration_reminder_dialog.dart';

@injectable
class MineController extends BaseController {
  final AccountRepository accountRepository;
  final ConfigRepository configRepository;
  final MemberRepository memberRepository;

  MineController(
      this.accountRepository, this.configRepository, this.memberRepository);

  bool get isLogin => accountRepository.isLogin.value;

  bool? get isOpenFreeMember => configRepository.isOpenFreeMember.value;

  UserInfo get mineInfo => accountRepository.mineUserInfo.value;

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

  String? get phone => accountRepository.loginPhoneNum.value;

  void onBack() {
    Get.back();
  }

  String getUserName(String phone) {
    if (phone.length > 4) {
      phone = phone.substring(phone.length - 4);
    }
    return '${StringName.mineAccountLoggedDesc}$phone';
  }

  void onShareClick() {
    WechatShareUtil.shareWebPage().catchError((error) {
      ToastUtil.show(error);
    });
  }

  void onCustomerServiceClick() {
    String phone = AccountRepository.getInstance().loginPhoneNum.value ?? '';
    String url = "https://qiyu-kefu.atmob.com?"
        "ssid=$phone"
        "&device_id=$phone"
        "&app_platform=${Platform.isAndroid ? 1 : 2}"
        "&app_version=${appInfoUtil.appVersionName}"
        "&package_name=${appInfoUtil.packageName}"
        "&app_name=${Platform.isIOS? StringName.appNameIos : StringName.appName}"
        "&phone=$phone";
    BrowserPage.start(url);
  }

  void onPermissionSettingClick() {
    PermissionSettingPage.start();
  }

  void onAccountFeedbackClick() {
    FeedBackPage.start();
  }

  void onAboutClick() {
    AboutPage.start();
  }

  void onLogoutAccountClick() {
    logoutAccountDialog(
        logoutCallback: () {
          accountRepository.userClear().then((_) {
            ToastUtil.show(StringName.accountLogoutSuccess);
            accountRepository.logout();
          }).catchError((error) {
            ErrorHandler.toastError(error);
          });
        },
        cancelCallback: () {});
  }

  void onFunExitAccountClick() {
    exitAccountDialog(confirmOnTap: () {
      accountRepository.logout();
    });
  }

  void onEditUserAvatarClick() {
    if (isLogin) {
      editUserAvatar();
    } else {
      LoginPage.start();
    }
  }

  void onMineDescClick() {
    if (isLogin) {
      if (accountRepository.memberIsExpired()) {
        MemberPage.start();
      }
      return;
    }
    LoginPage.start();
  }

  void editUserAvatar() {
    UserAvatarView.show();
  }

  onUrgentContactClick() {
    UrgentContactPage.start();
  }

  Future<void> onMemberTryOutClick() {
    return memberRepository.memberTrial().then((_) {
      ToastUtil.show('已获得会员试用');

      ///刷新会员状态。
      accountRepository.refreshMemberStatus();
    }).catchError((error) {
      if (error is ServerErrorException) {
        if (error.code == ErrorCode.getMemberFree) {
          ToastUtil.show(StringName.memberFreeCodeErrorToast);
        } else if (error.code == ErrorCode.isMember) {
          ToastUtil.show(StringName.memberFreeCodeIsmember);
        } else if (error.code == ErrorCode.noLoginError) {
          ToastUtil.show(StringName.accountNoLogin);
          LoginPage.start();
          throw error;
        } else {
          ToastUtil.show(error.message);
          throw error;
        }
      } else {
        ErrorHandler.toastError(error);
        throw error;
      }
    });
  }

  void onMemberCardClick() {
    MemberPage.start();
  }

  ///会员倒计时到期弹出提示窗
  void promptWindowPopsCountdownExpires() {}
}
