import 'package:fis_jsonrpc/services/appletAPI.m.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/event_bus.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_env/index.dart';
import 'package:get/get.dart';

import 'index.dart';

class WxHomeController extends GetxController {
  WxHomeController();

  final state = MiniProgramHomeState();

  bool get isBinded => Store.user.token.isNotEmpty;

  void routerTo(String routeName) {
    if (routeName == MobileRouteNames.Wechat.MiniProgramConsultation ||
        routeName == MobileRouteNames.Wechat.MiniProgramDiagnosis) {
      if (!isBinded) {
        Get.snackbar("通知", "请先绑定账号",
            duration: Duration(seconds: 2),
            margin: EdgeInsets.only(top: 10),
            colorText: Color.fromARGB(255, 77, 77, 77));
        return;
      }
    }
    Get.toNamed(routeName);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    updateServer();
    initUserInfo();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
    delayUpdateServer();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void updateServer() {
    print("更新服务器");
    bus.emit(
        bus.Keys.SERVER_ADDRESS_CHANGED,
        Uri(
          scheme: "http",
          host: "192.168.6.74",
          port: 7307,
        ).toString());
  }

  void delayUpdateServer() {
    Future.delayed(Duration(seconds: 3), () {
      updateServer();
    });
  }

  /// 初始化账号信息【openid 有则存，身份如果绑定成功或者获取成功则存 token】
  void initUserInfo() async {
    if (kOpenId.isNotEmpty) {
      /// 如果存在openid，则直接先写入openid
      Store.user.setOpenid(kOpenId);
      print("设置当前的 openid 为: $kOpenId");
      final bool isAccountExist = await checkUserInfoByOpenId(kOpenId);
      if (isAccountExist) {
        Store.user.setToken(kOpenId);
      } else {
        print("用户信息不存在");
        Store.user.setToken("");
      }
    }

    /// 如果没有 openId 也没有身份，则提示微信用户信息未授权，请重试
    if (Store.user.token.isEmpty && kOpenId.isEmpty) {
      print("微信用户信息未授权，请重试");
    }
  }

  Future<bool> checkUserInfoByOpenId(String openId) async {
    print("根据openid获取用户信息 当前的 openid 为: $openId");
    GetUserInfoByOpenIdResult result = await rpc.appletAPI
        .getUserInfoByOpenIdAsync(GetUserInfoByOpenIdRequest(openId: openId));
    if (result.nickName == null) {
      Get.snackbar("无账号信息", "请先绑定账号",
          duration: Duration(seconds: 2),
          margin: EdgeInsets.only(top: 10),
          colorText: Color.fromARGB(255, 77, 77, 77));
      return false;
    }
    print(
        "根据openid获取用户信息 获取到的信息为: 用户名${result.nickName} 医院${result.hospital} 用户id ${result.userId}");
    Store.user.handleWechatLogin(
      result.nickName ?? '',
      result.hospital ?? '',
      result.userId ?? '',
    );
    return true;
  }
}
