package com.red.circle.other.app.command.user;

import com.red.circle.common.business.core.ImageSizeConst;
import com.red.circle.common.business.core.enums.ApprovalStatusEnum;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.external.inner.endpoint.oss.OssServiceClient;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.cmd.user.user.BankIdentityInfoCmd;
import com.red.circle.other.infra.database.rds.entity.user.user.BankIdentityInfo;
import com.red.circle.other.infra.database.rds.service.user.user.BankIdentityInfoService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户身份信息上传.
 *
 * @author pengliang on 2023/6/15
 */
@Component
@RequiredArgsConstructor
public class UserBankIdentityCmdExe {

  private final RedisService redisService;
  private final OssServiceClient ossServiceClient;
  private final BankIdentityInfoService bankIdentityInfoService;

  public void execute(BankIdentityInfoCmd cmd) {
    String key = "submitback_" + cmd.requiredReqUserId();
    redisService.lock(key, 60);

    try {
      BankIdentityInfo latestSubmit = bankIdentityInfoService.getLatest(cmd.requiredReqUserId());

      boolean status = Objects.nonNull(latestSubmit)
          && ApprovalStatusEnum.NOT_PASS.eq(latestSubmit.getStatus());

      ResponseAssert.isFalse(CommonErrorCode.SUBMIT_FAIL, status && Objects.isNull(cmd.getId()));

      BankIdentityInfo info = new BankIdentityInfo();
      info.setId(cmd.getId());
      info.setUserId(cmd.requiredReqUserId());
      info.setSysOrigin(cmd.requireReqSysOrigin());
      info.setIdentityCover(ResponseAssert.requiredSuccess(
          ossServiceClient.processImgSaveAsCompressZoom(cmd.getIdentityCover(),
              ImageSizeConst.COVER_HEIGHT)
      ));
      info.setContact(cmd.getContact());
      info.setStatus(ApprovalStatusEnum.PENDING.name());
      info.setType("DEFAULT");
      info.setDescription("");
      info.setAuditDescription("");
      bankIdentityInfoService.saveOrUpdate(info);
    } finally {
      redisService.unlock(key);
    }

  }
}
