package com.red.circle.console.app.command.admin;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.red.circle.console.app.convertor.UserAppConvertor;
import com.red.circle.console.app.dto.cmd.admin.UserCmd;
import com.red.circle.console.infra.database.rds.entity.admin.User;
import com.red.circle.console.infra.database.rds.enums.StatusEnum;
import com.red.circle.console.infra.database.rds.service.admin.UserRoleService;
import com.red.circle.console.infra.database.rds.service.admin.UserService;
import com.red.circle.console.inner.error.ConsoleErrorCode;
import com.red.circle.framework.core.asserts.ResponseAssert;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Component;

/**
 * 添加用户.
 *
 * @author pengliang on 2023/5/15
 */
@Component
@RequiredArgsConstructor
public class UserAddCmdExe {

  private final UserService userService;
  private final UserRoleService userRoleService;
  private final UserAppConvertor userAppConvertor;

  public void execute(UserCmd cmd) {
    long count = userService.query().eq(User::getLoginName, cmd.getLoginName()).count();
    ResponseAssert.isTrue(ConsoleErrorCode.USERNAME_ALREADY_EXISTS, count == 0);
    if (Objects.isNull(cmd.getStatus())) {
      cmd.setStatus(StatusEnum.DISABLE.getValue());
    }
    User user = userAppConvertor.toUser(cmd);
    //没设置密码 设置默认密码
    if (StringUtils.isEmpty(user.getPassword())) {
      user.setPassword(Md5Crypt.apr1Crypt(user.getLoginName(), user.getLoginName()));
    }
    //默认禁用
    user.setStatus(StatusEnum.DISABLE);
    userService.save(user);
    userRoleService.saveUserRoles(user.getId(), cmd.getRoleIds());
  }

}
