import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:flutter_clx_base/widget/my_refresh_list_public.dart';

import 'account_center_state.dart';

class AccountCenterLogic extends GetxController {
  final AccountCenterState state = AccountCenterState();

  //list 控制器
  final MyListController listController = MyListController();

  @override
  void onInit() {
    SpUtil.putString(SPKey.token, Get.arguments['token'] ?? '');
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    getLoginUserInfo();
    getLoginUserDefaultCompany();
  }

  //获取登录人的信息

  void getLoginUserInfo() {
    fetch(Method.get, url: HttpApi.getLoginUser, onSuccess: (data) {
      //存 个人信息到 sp中
      state.userName = data['userName'] ?? "";
      state.userMobile = data['userMobile'] ?? "";
      if (data['headImg'] != null) {
        state.headImg = data['headImg'];
      }
      //是否实名认证
      SpUtil.putString(SPKey.userMobile, data['userMobile'] ?? "");
      SpUtil.putString(SPKey.userName, data['userName'] ?? "");
      SpUtil.putString(SPKey.userNo, data['userNo'] ?? "");
      listController.callRefresh();
      update();
    });
  }

  //获取登录人当前产品的权限的公司
  void listLoginUserProductCompany(
      int page, int pageSize, SuccessCallback success, error) {
    fetchList(Method.get,
        url: HttpApi.listUserProductCompany,
        queryParameters: {
          'productCode': AccountCenter.ownerProductCode,
          'userNo': getUserNo(),
        }, onSuccess: (response) {
      state.companyList = response;
      update();
      if (response.isEmpty) {
        response.add({'noData': true});
      }
      success(response);
    }, onError: error);
  }

  //获取登录人默认公司
  void getLoginUserDefaultCompany() {
    fetch(
      Method.get,
      url: HttpApi.getLoginUserDefaultCompany,
      queryParameters: {
        'productCode': AccountCenter.ownerProductCode,
      },
      onSuccess: (data) {
        if (data != null) {
          state.defaultCompany = data['companyName'] ?? "";
          state.defaultCompanyNo = data['companyNo'] ?? "";
        } else {
          state.defaultCompany = "";
          state.defaultCompanyNo = "";
        }
        update();
      },
    );
  }

  //切换公司
  void changeCompany(String companyNo, {String identityType = "company"}) {
    fetch(Method.get, url: HttpApi.updateAccessUserRedis, queryParameters: {
      "companyNo": companyNo,
      "identityType": identityType,
      'productCode': AccountCenter.ownerProductCode,
    }, onSuccess: (data) {
      onReady();
      AccountCenter.onIdentityChange?.call();
    });
  }

  void changeName(String text) {
    SpUtil.putString(SPKey.userName, text);
    state.userName = text;
    update();
  }
}
