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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Role;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.mapper.RoleMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.entity.request.user.UserInitRequest;
import com.tuoheng.admin.service.third.oidc.OidcService;
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-29
 */
@Slf4j
@Service
public class SystemUserInitService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private OidcService oidcService;

    /**
     * 添加租户用户数据
     *
     * @return
     */
    public JsonResult init(UserInitRequest request) {
        log.info("进入初始化系统租户用户业务接口");
        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("初始化系统租户用户业务接口：校验失败：{}", result.getMsg());
            return result;
        }
        Tenant tenant = null;
        if (1 == request.getTenantFlag()) {
            tenant = this.addTenant(request);
        }
        User user = this.buildUser(request);
        // 添加oidc
        result = oidcService.addUser(user, request.getPassword(), tenant);
        if (0 != result.getCode()) {
            log.info("初始化系统租户用户业务接口：添加oidc数据失败：{}", result.getMsg());
            return result;
        }
        // 此次不能放在上面，要等oicd添加完之后，防止tenant不为空的话，创建都是租户
        if (0 == request.getTenantFlag()) {
            tenant = tenantMapper.selectOne(Wrappers.<Tenant>lambdaQuery()
                    .eq(Tenant::getMark, 1)
                    .eq(Tenant::getCode, request.getTenantCode()));
            if (ObjectUtil.isNotNull(tenant)) {
                user.setTenantId(tenant.getId());
            } else {
                log.info("租户不存在，tenantCode:{}", request.getTenantCode());
            }
        }

        user.setTenantId(tenant.getId());
        this.addUser(user);

        return JsonResult.success();
    }

    /**
     * 构建实体字段数据
     */
    private User buildUser(UserInitRequest request) {
        User user = new User();
        user.setCode(SystemConstant.PLATFORM_CODE);
        user.setUsername(request.getName());
        user.setRealname("超级管理员");
        user.setNickname("超级管理员");
        user.setCityName("");
        user.setPassword(CommonUtils.password(request.getPassword()));
        user.setAvatar("imagedir/n1o1j9ndau_1670488066287.png");
        user.setClientId("1,2");
        user.setRoleId(1);
        user.setStatus(1);
        user.setCreateTime(DateUtils.now());
        return user;
    }

    /**
     * 检查参数
     *
     * @param request
     * @param
     *
     * @return
     */
    private JsonResult check(UserInitRequest request) {
        if (StringUtils.isEmpty(request.getName())) {
            return JsonResult.error(400, "用户名为空");
        }
        if (StringUtils.isEmpty(request.getPassword())) {
            return JsonResult.error(400, "密码为空");
        }
        if (StringUtils.isEmpty(request.getTenantCode())) {
            return JsonResult.error(400, "租户编号");
        }
        Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getName())
                .eq(User::getMark, 1));
        if (count > 0) {
            return JsonResult.error(400, "系统中已经存在该用户名");
        }
        count = roleMapper.selectCount(new LambdaQueryWrapper<Role>()
                .eq(Role::getId, 1)
                .eq(Role::getMark, 1));
        if (count <= 0) {
            return JsonResult.error(400, "该角色不存在");
        }
        return JsonResult.success();
    }
    /**
     *  添加租户
     */
    private Tenant addTenant(UserInitRequest request) {
        // 如果是租户先去创建
        Tenant tenant = new Tenant();
        tenant.setName(request.getName());
        tenant.setUsername(request.getName());
        tenant.setCode(request.getTenantCode());
        tenant.setCreateTime(DateUtils.now());
        Tenant tenantTmp = tenantMapper.selectOne(Wrappers.<Tenant>lambdaQuery()
                .eq(Tenant::getMark, 1)
                .eq(Tenant::getStatus, 1)
                .eq(Tenant::getName, request.getName())
                .eq(Tenant::getCode, request.getTenantCode()));
        if (ObjectUtil.isNull(tenantTmp)) {
            tenantMapper.insert(tenant);
            return tenant;
        } else {
            return tenantTmp;
        }
    }

    /**
     *  添加用户
     */
    private void addUser(User user) {
        User userTmp = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, 1)
                .eq(User::getStatus, 1)
                .eq(User::getUsername, user.getUsername()));
        if (ObjectUtil.isNull(userTmp)) {
            log.info("初始化系统租户用户，用户已存在，username：{}", user.getUsername());
        }

        // 如果顶级部门存在，将该超级管理员与顶级部门关联
//        Dept dept = deptMapper.selectOne(Wrappers.<Dept>lambdaQuery()
//                        .eq(Dept::getMark, 1)
//                        .eq(Dept::getTenantId, user.getTenantId())
//                        .eq(Dept::getPid, SystemConstant.ROOT_DEPT_PID));
//        if (ObjectUtil.isNotNull(dept)) {
//            user.setDeptId(dept.getId());
//        }
        Integer rowCount = userMapper.insert(user);
        if (rowCount <= 0) {
            log.info("初始化系统租户用户失败，username：{}", user.getUsername());
        }
    }

}
