import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get_storage/get_storage.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:vbvs_app/common/color/ServiceConstant.dart';
import 'package:vbvs_app/common/color/app_uri_status.dart';
import 'package:vbvs_app/common/util/CommonVariables.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/common/util/requestWithLog.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/time/countdown_controller.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:vbvs_app/model/api_response.dart';
import 'package:vbvs_app/model/user_data.dart';

part 'login_controller.g.dart';

@JsonSerializable()
class LoginModel {
  //版本id
  int? loginStyle = 1; //1.密码登录 2.短信登录
  String? account = '17649984946'; //账户
  String? password = '123wyf..'; //密码

  String? phone; //手机号/邮箱
  String? code; //验证码

  String? register_code;

  bool? showPd = true;

  int? forceLogin = 0;

  bool? isIos; //是否为ios设备

  bool? isWeChatNotInstalled; //是否安装微信

  bool? register_agree = false; //是否同意协议

  LoginModel();

  static LoginModel fromJson(Map<String, dynamic> json) =>
      _$LoginModelFromJson(json);
  Map<String, dynamic> toJson() => _$LoginModelToJson(this);
}

class LoginController extends GetControllerEx<LoginModel> {
  // 初始化实例
  final Fluwx fluwx = Fluwx();
  // 微信监听返回值
  FluwxCancelable? fluwxCancelable;

  // final UserRepository repository = UserRepository();
  LoginController() {
    attr = GetModel(LoginModel()).obs;
  }

  //登录
  Future<ApiResponse> login(BuildContext context) async {
    ApiResponse apiResponse = ApiResponse(code: -1, msg: "其他手机登录页.登录失败".tr);
    if (model.phone == null || model.phone!.isEmpty) {
      apiResponse.msg = "其他手机登录页.请输入手机号".tr;
      return apiResponse;
    }
    if (model.code == null || model.code!.isEmpty) {
      apiResponse.msg = "其他手机登录页.请输入验证码".tr;
      return apiResponse;
    }
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.login;
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
    String? language = "";
    if (languageController.selectLanguage != null) {
      language = languageController.selectLanguage.value!.language_code;
    }
    if (language != null && language.isNotEmpty) {
      if (queryUrl.contains("?")) {
        queryUrl += "&lang=$language";
      } else {
        queryUrl += "?lang=$language";
      }
    }
    var data = {
      "type": 1,
      "userName": model.phone,
      "password": model.code,
    };
    var response =
        await EasyDartModule.dio.post(queryUrl, data: jsonEncode(data));
    if (response != null) {
      var responseData =
          response.data is String ? jsonDecode(response.data) : response.data;
      ApiResponse res = ApiResponse.fromJson(responseData, (object) => object);
      MyUtils.formatResponse(apiResponse, "其他手机登录页.登陆成功".tr, "其他手机登录页.登陆失败".tr);
      if (res.code == HttpStatusCodes.ok) {
        CountdownController countdownController = Get.find();
        countdownController.countdown.value = 0;
        UserInfoController userInfoController = Get.find();
        userInfoController.model.login = 1;
        userInfoController.model.user = UserModel.fromJson(res.data);
        String token = response.headers['token']!.first;
        EasyDartModule.dio.token = token;
        final box = GetStorage();
        box.write('token', token); // 存储 token
        box.write('user', userInfoController.model.user!.toJson()); // 存储用户信息
      }
      return res;
    } else {
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  Future<ApiResponse> getCode(BuildContext context) async {
    ApiResponse apiResponse = ApiResponse(code: -1, msg: "其他手机登录页.发送失败".tr);
    try {
      // if (model.register_agree == null || model.register_agree != true) {
      //   apiResponse.msg = "登录页.未同意协议".tr;
      //   return apiResponse;
      // }
      if (model.phone == null || model.phone!.isEmpty) {
        apiResponse.msg = "其他手机登录页.请输入手机号".tr;
        return apiResponse;
      }
      model.phone = model.phone!.trim();
      if (!MyUtils.isValidPhoneNumber(model.phone!) &&
          !MyUtils.isValidEmail(model.phone!)) {
        apiResponse.msg = '其他手机登录页.不正确手机号'.tr;
        return apiResponse;
      }
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.send_code;
      String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        if (queryUrl.contains("?")) {
          queryUrl += "&lang=$language";
        } else {
          queryUrl += "?lang=$language";
        }
      }
      var data = {
        "userName": model.phone,
      };
      var response =
          await EasyDartModule.dio.post(queryUrl, data: jsonEncode(data));
      if (response != null) {
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        if (res.code != HttpStatusCodes.ok) {
          if (res.msg == null || res.msg!.isEmpty) {
            res.msg = apiResponse.msg;
          }
        } else {
          if (res.msg == null || res.msg!.isEmpty) {
            res.msg = "其他手机登录页.发送成功".tr;
          }
        }
        return res;
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
    } catch (e) {
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  //微信登录
  Future<void> wxLoginSendAuth(BuildContext context) async {
    /*
    1、目前移动应用上微信登录只提供原生的登录方式，需要用户安装微信客户端才能配合使用。
    2、对于Android应用，建议总是显示微信登录按钮，当用户手机没有安装微信客户端时，请引导用户下载安装微信客户端。
    3、对于iOS应用，考虑到iOS应用商店审核指南中的相关规定，建议开发者接入微信登录时，先检测用户手机是否已安装微信客户端
    （使用sdk中isWXAppInstalled函数 ），对未安装的用户隐藏微信登录按钮，只提供其他登录方式（比如手机号注册登录、游客登录等）
    */
    try {
      if (isAndroid) {
        bool isWeChatInstalled = await fluwx.isWeChatInstalled;
        if (!isWeChatInstalled) {
          TopSlideNotification.show(context,
              text: "微信安装提示".tr, textColor: themeController.currentColor.sc9);
          return;
        }
      }
      fluwx
          .authBy(
              which: NormalAuth(
        scope: 'snsapi_userinfo',
        state: 'wechat_sdk_theh_wxlogin',
      ))
          .then((data) async {
        //返回true表示成功或者false表示失败，这边没有意义从login_controller页面构造函数监听中去处理
        debugPrint('msg:$data');
        EasyDartModule.logger.error('msg:$data');
        if (data) {
          //登陆成功
          // await dealBindProcess();
        }
      });
    } catch (e) {
      debugPrint('msg:$e');
      EasyDartModule.logger.error('msg:$e');
    }
  }

  Future<ApiResponse> loginByWechatCode(String code) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.login;
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
    String? language = "";
    var data = {
      "type": 2,
      "password": code,
    };
    ApiResponse apiResponse = await requestWithLog(
        logTitle: "微信登录",
        method: MyHttpMethod.post,
        queryUrl: queryUrl,
        data: data);
    if (apiResponse.code == HttpStatusCodes.ok) {
      UserInfoController userInfoController = Get.find();
      userInfoController.model.login = 1;
      userInfoController.model.user = UserModel.fromJson(apiResponse.data);
      String token = apiResponse.rawResponse.headers['token']!.first;
      EasyDartModule.dio.token = token;
      final box = GetStorage();
      box.write('token', token); // 存储 token
      box.write('user', userInfoController.model.user!.toJson()); // 存储用户信息
    }
    return apiResponse;
  }

  Future<void> openWeChatCustomerService(BuildContext context) async {
    bool isWeChatInstalled = await fluwx.isWeChatInstalled;
    if (!isWeChatInstalled) {
      TopSlideNotification.show(context,
          text: "微信客服提示".tr, textColor: themeController.currentColor.sc9);
      return;
    }
    TopSlideNotification.show(context,
        text: "打开微信客服提示".tr, textColor: themeController.currentColor.sc1);
    await fluwx.open(
        target: CustomerServiceChat(
            corpId: CommonVariables.wxCorpId, url: CommonVariables.wxKfUrl));
  }

  //退出登录
  // Future<void> logout() async {
  //   await repository.logout();
  // }

  // loginByWechatCode(String code) async {
  //   return await repository.loginByWechatCode(code);
  // }

  //注销账号
  // deletedAccount() async {
  //   return await repository.deletedAccount();
  // }
}
