import 'package:account_center/api/base_model.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'invite_members_state.dart';

class InviteMembersLogic extends GetxController {
  final InviteMembersState state = InviteMembersState();

  @override
  void onInit() {
    var arg = Get.arguments;
    state.companyNo = arg['companyNo'];
    super.onInit();
  }

  @override
  void onReady() {
    _initCode();

    super.onReady();
  }

  void _initCode() {
    final String? invalidTimeStr = SpUtil.getString(companyInviteCodeInvalid);
    if (invalidTimeStr?.isNotEmpty == true) {
      int invalid =
          DateUtil.getDateTime(invalidTimeStr!)?.millisecondsSinceEpoch ?? 0;
      if (DateTime.now().millisecondsSinceEpoch >= invalid) {
        generateInviteCode();
      } else {
        state.invitationCode = SpUtil.getString(companyInviteCode) ?? '';
        state.invalidTime = invalidTimeStr;
        update();
      }
    } else {
      generateInviteCode();
    }
  }

  // 生成邀请码
  void generateInviteCode() {
    var params = {
      "companyNo": state.companyNo,
      "effectDays": state.effectDays,
    };
    fetch(Method.post, url: HttpApi.saveInvitationCode, params: params,
        onSuccess: (data) {
      SpUtil.putString(companyInviteCode, data['invitationCode']);
      SpUtil.putString(companyInviteCodeInvalid, data['invitationExpireTime']);
      state.invitationCode = data['invitationCode'];
      state.invalidTime = data['invitationExpireTime'];
      update();
    });
  }

  String get companyInviteCode => '${state.companyNo}inviteCode';
  String get companyInviteCodeInvalid => '${state.companyNo}inviteCodeInvalid';
}
