import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/consts/constants.dart';
import 'package:electronic_assistant/data/consts/error_code.dart';
import 'package:electronic_assistant/data/consts/event_report_id.dart';
import 'package:electronic_assistant/data/repositories/account_repository.dart';
import 'package:electronic_assistant/dialog/alert_dialog.dart';
import 'package:electronic_assistant/handler/event_handler.dart';
import 'package:electronic_assistant/module/browser/view.dart';
import 'package:electronic_assistant/module/login/view.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:electronic_assistant/utils/expand.dart';
import 'package:electronic_assistant/utils/http_handler.dart';
import 'package:electronic_assistant/utils/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LoginController extends BaseController {
  final phone = "".obs;
  final code = "".obs;
  final isAgree = false.obs;

  final FocusNode phoneFocusNode = FocusNode();

  LoginFromType? fromType;

  @override
  void onReady() {
    super.onReady();
    phoneFocusNode.requestFocus();
    _initArguments();
  }

  void _initArguments() {
    fromType = parameters?['fromType'];
    if (fromType != null) {
      if (fromType == LoginFromType.talkDetail) {
        EventHandler.report(EventId.event_103001,
            params: {EventId.id: EventId.id_001});
      } else if (fromType == LoginFromType.mainLogin) {
        EventHandler.report(EventId.event_103001,
            params: {EventId.id: EventId.id_002});
      } else if (fromType == LoginFromType.store) {
        EventHandler.report(EventId.event_103001,
            params: {EventId.id: EventId.id_003});
      } else if (fromType == LoginFromType.aiChat) {
        EventHandler.report(EventId.event_103001,
            params: {EventId.id: EventId.id_004});
      }
    }
  }

  void getUserCode() {
    if (phone.value.isEmpty) {
      ToastUtil.showToast("请输入手机号");
      return;
    }
    accountRepository.getVerificationCode(phone.value).then((data) {
      ToastUtil.showToast("验证码已发送");
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void login() {
    FocusScope.of(Get.context!).requestFocus(FocusNode());

    if (phone.value.isEmpty) {
      ToastUtil.showToast("请输入手机号");
      return;
    }

    if (code.value.isEmpty) {
      ToastUtil.showToast("请输入验证码");
      return;
    }

    if (!isAgree.value) {
      EAAlertDialog.show(
        title: "隐私政策及权限说明",
        contentWidget: Wrap(
          children: [
            Text(
              "进入下一步前，请先阅读并同意小听的",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: "#5F5F61".toColor(),
                fontSize: 14,
                decoration: TextDecoration.none,
              ),
            ),
            GestureDetector(
              onTap: () {
                if (GetPlatform.isIOS) {
                  BrowserPage.start(Constants.privacyPolicyIos);
                } else {
                  BrowserPage.start(Constants.privacyPolicy);
                }
              },
              child: Text(
                "《隐私政策》",
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: "#5E8BFF".toColor(),
                  fontSize: 14,
                  decoration: TextDecoration.none,
                ),
              ),
            ),
            Text(
              "和",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: "#5F5F61".toColor(),
                fontSize: 14,
                decoration: TextDecoration.none,
              ),
            ),
            GestureDetector(
              onTap: () {
                BrowserPage.start(Constants.userAgreement);
              },
              child: Text(
                "《用户使用协议》",
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: "#5E8BFF".toColor(),
                  fontSize: 14,
                  decoration: TextDecoration.none,
                ),
              ),
            ),
            Text(
              "。",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: "#5F5F61".toColor(),
                fontSize: 14,
                decoration: TextDecoration.none,
              ),
            ),
          ],
        ),
        cancelText: "不同意",
        confirmText: "同意并继续",
        cancelOnTap: () {
          EAAlertDialog.dismiss();
        },
        confirmOnTap: () {
          EAAlertDialog.dismiss();
          isAgree.value = true;
          login();
        },
      );
      return;
    }

    if (phone.value.isEmpty || code.value.isEmpty) {
      return;
    }
    accountRepository.login(phone.value, code.value).then((data) {
      ToastUtil.showToast("登录成功");
      EventHandler.report(EventId.event_103002);
      Get.back(result: true);
    }).catchError((error) {
      if (error is ServerErrorException) {
        if (error.code == ErrorCode.errorVerificationCode) {
          EventHandler.report(EventId.event_103004);
          ToastUtil.showToast("验证码错误");
        } else {
          EventHandler.report(EventId.event_103003);
          ErrorHandler.toastError(error);
        }
      } else {
        EventHandler.report(EventId.event_103003);
        ErrorHandler.toastError(error);
      }
    });
  }

  void setPhone(String text) {
    phone.value = text;
  }

  void setCode(String text) {
    code.value = text;
  }
}
