package com.tuoheng.admin.service.system.user.add;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Role;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.enums.code.user.AddUserCodeEnum;
import com.tuoheng.admin.mapper.RoleMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.service.third.oidc.OidcService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.utils.CommonUtils;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 添加用户业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-16
 */
@Slf4j
@Service
public class AddUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private OidcService oidcService;

    /**
     * 添加用户数据
     *
     * @return
     */
    public JsonResult add(User user) {
        log.info("进入添加用户业务接口");
        String tenantId = CurrentUserUtil.getTenantId();
        JsonResult result = this.check(tenantId, user);
        if (0 != result.getCode()) {
            log.info("添加用户业务接口：校验失败：{}", result.getMsg());
            return result;
        }
        user.setTenantId(tenantId);
        // 添加oidc
        result = oidcService.addUser(user, SystemConstant.INIT_PASSWORD, null);
        if (0 != result.getCode()) {
            log.info("添加用户业务接口：添加oidc数据失败：{}", result.getMsg());
            return result;
        }
        this.buildUser(user, tenantId);
        Integer rowCount = userMapper.insert(user);
        if (rowCount <= 0) {
            return JsonResult.error(AddUserCodeEnum.ADD_IS_FAILED.getCode(), AddUserCodeEnum.ADD_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param user
     * @return
     */
    private JsonResult check(String tenantId, User user) {
        if (StringUtils.isEmpty(user.getUsername())) {
            return JsonResult.error(AddUserCodeEnum.USERNAME_IS_NULL.getCode(), AddUserCodeEnum.USERNAME_IS_NULL.getMsg());
        }
        if (StringUtils.isEmpty(user.getRealname())) {
            return JsonResult.error(AddUserCodeEnum.REALNAME_IS_NULL.getCode(), AddUserCodeEnum.REALNAME_IS_NULL.getMsg());
        }
        if (ObjectUtil.isNull(user.getRoleId()) || 0 == user.getRoleId()) {
            return JsonResult.error(AddUserCodeEnum.ROLE_ID_IS_NULL.getCode(), AddUserCodeEnum.ROLE_ID_IS_NULL.getMsg());
        }
        //校验手机号
        boolean flag = CommonUtils.isMobile(user.getMobile());
        if (!flag) {
            return JsonResult.error(AddUserCodeEnum.PHONE_NOT_IMATCH.getCode(), AddUserCodeEnum.PHONE_NOT_IMATCH.getMsg());
        }
        Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getUsername, user.getUsername())
                .eq(User::getMark, 1));
        if (count > 0) {
            return JsonResult.error(AddUserCodeEnum.USERNAME_ALREADY_EXISTS.getCode(), AddUserCodeEnum.USERNAME_ALREADY_EXISTS.getMsg());
        }
        count = roleMapper.selectCount(new LambdaQueryWrapper<Role>()
                .eq(Role::getId, user.getRoleId())
                .eq(Role::getMark, 1));
        if (count < 0) {
            return JsonResult.error(AddUserCodeEnum.ROLE_IS_NOT_EXISTS.getCode(), AddUserCodeEnum.ROLE_IS_NOT_EXISTS.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 构建实体字段数据
     *
     * @param user
     * @param tenantId
     */
    private void buildUser(User user, String tenantId) {
        // 设置密码
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(CommonUtils.password(user.getPassword()));
        } else {
            //  默认密码
            user.setPassword(CommonUtils.password(SystemConstant.INIT_PASSWORD));
        }
        if (StringUtils.isNotNull(user.getAvatar()) && user.getAvatar().contains(CommonConfig.imageURL)) {
            user.setAvatar(user.getAvatar().replaceAll(CommonConfig.imageURL, ""));
        } else {
            //添加默认头像
            user.setAvatar("imagedir/n1o1j9ndau_1670488066287.png");
        }
        user.setCityName("");
        user.setTenantId(tenantId);
        user.setCreateUser(CurrentUserUtil.getUserId());
        user.setCreateTime(DateUtils.now());
    }

}
