import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.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/module/login/login_page.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard/utils/toast_util.dart';

import '../../data/consts/error_code.dart';
import '../../handler/wechat_login_service.dart';
import '../../resource/string.gen.dart';
import '../../utils/error_handler.dart';
import '../../utils/http_handler.dart';
import '../member_agreement_dialog.dart';
import '../privacy_agreement_dialog.dart';
import 'login_dialog.dart';

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

  final WechatLoginService wechatLoginService;
  final AccountRepository accountRepository;

  LoginDialogController(this.wechatLoginService, this.accountRepository);

  final RxBool _isAgree = false.obs;

  bool get isAgree => _isAgree.value;

  clickAgree() {
    _isAgree.value = !_isAgree.value;
  }

  void clickWxLogin() async {
    if (!_isAgree.value) {
      PrivacyAgreementDialog.show(
        btnConfirm: () async {
          _isAgree.value = true;
          clickWxLogin();
        },
      );

      return;
    }
    wechatLoginService.login(
      onSuccess: (code) {

        accountRepository
            .wechatLogin(code)
            .then((data) {
              ToastUtil.show(StringName.loginSuccess);
              SmartDialog.dismiss(tag: LoginDialog.TAG);
            })
            .catchError((error) {
              if (error is ServerErrorException) {
                if (error.code == ErrorCode.verificationCodeError) {
                  ToastUtil.show(StringName.loginVerificationCodeErrorToast);
                } else {
                  ToastUtil.show(error.message);
                }
              } else {
                ErrorHandler.toastError(error);

              }
            });
      },
      onError: (code, msg) {
        ToastUtil.show("微信登录失败：$msg");
      },
      onCancel: () {
        ToastUtil.show("用户取消登录");
      },
    );
  }

  void clickClose() {
    AtmobLog.d(tag, "clickClose");
    SmartDialog.dismiss(tag: LoginDialog.TAG);
  }

  void clickPhoneLogin() {
    AtmobLog.d(tag, "clickPhoneLogin");

    LoginPage.start();

    SmartDialog.dismiss(tag: LoginDialog.TAG);
  }

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

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