package com.tuoheng.admin.service.third.oidc;

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.dto.ClientRoleDto;
import com.tuoheng.admin.entity.Role;
import com.tuoheng.admin.entity.Tenant;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.ClientEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.mapper.RoleMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.request.third.oidc.CreateOidcTenantRequest;
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;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AddOidcTenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AddOidcUserService addOidcUserService;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult createTenant(CreateOidcTenantRequest request) {
        log.info("创建租户业务");
        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("创建租户业务：校验失败：{}", result.getMsg());
            return result;
        }

        Tenant tenant = this.buildTenant(request);
        User user = this.buildUser(request);

        //// 添加oidc
        //result = addOidcUserService.add(user, request.getPassword(), tenant);
        //if (0 != result.getCode()) {
        //    log.info("创建租户业务：添加oidc数据失败：{}", result.getMsg());
        //    return result;
        //}

        result = this.addTenant(tenant);
        if (0 != result.getCode()) {
            log.info("创建租户业务：添加租户失败：{}", result.getMsg());
            return result;
        }

        user.setTenantId(tenant.getId());
        result = this.addUser(user);
        if (0 != result.getCode()) {
            log.info("创建租户业务：添加用户失败：{}", result.getMsg());
            return result;
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @param
     * @return
     */
    private JsonResult check(CreateOidcTenantRequest request) {
        if (StringUtils.isEmpty(request.getUsername())) {
            return JsonResult.error(400, "用户名为空");
        }
        if (StringUtils.isEmpty(request.getTenantName())) {
            return JsonResult.error(400, "租户名称为空");
        }
        if (StringUtils.isEmpty(request.getPassword())) {
            return JsonResult.error(400, "密码为空");
        }
        if (StringUtils.isEmpty(request.getTenantCode())) {
            return JsonResult.error(400, "租户编号");
        }
        Integer count = tenantMapper.selectCount(new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getUsername, request.getUsername())
                .eq(Tenant::getMark, MarkEnum.VALID.getCode()));
        if (count > 0) {
            return JsonResult.error("系统中已经存在该租户名");
        }
        count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getUsername())
                .eq(User::getMark, MarkEnum.VALID.getCode()));
        if (count > 0) {
            return JsonResult.error(400, "系统中已经存在该用户名");
        }
        count = roleMapper.selectCount(new LambdaQueryWrapper<Role>()
                .eq(Role::getId, DataPermissionEnum.ALL.getCode())
                .eq(Role::getMark, MarkEnum.VALID.getCode()));
        if (count <= 0) {
            return JsonResult.error(400, "角色不存在");
        }
        return JsonResult.success();
    }

    private Tenant buildTenant(CreateOidcTenantRequest request) {
        // 创建租户数据
        Tenant tenant = new Tenant();
        tenant.setCode(request.getTenantCode());
        tenant.setUsername(request.getUsername());
        tenant.setName(request.getTenantName());
        tenant.setProvinceCode(request.getProvinceCode());
        tenant.setProvinceName(request.getProvinceName());
        tenant.setDistrictCode(request.getDistrictCode());
        tenant.setDistrictName(request.getDistrictName());
        tenant.setCityCode(request.getCityCode());
        tenant.setCityName(request.getCityName());
        return tenant;
    }

    /**
     * 添加租户
     */
    private JsonResult addTenant(Tenant tenant) {
        Integer count = tenantMapper.insert(tenant);
        if (count <= 0) {
            log.info("创建租户失败");
            JsonResult.error("创建租户失败");
        }
        return JsonResult.success(tenant);
    }

    /**
     * 构建实体字段数据
     */
    private User buildUser(CreateOidcTenantRequest request) {
        // 创建用户数据
        User user = new User();
        user.setCode(request.getTenantCode());
        user.setUsername(request.getUsername());
        user.setRealname(request.getTenantName());
        user.setNickname(request.getTenantName());
        user.setPassword(CommonUtils.password(request.getPassword()));
        user.setProvinceCode(request.getProvinceCode());
        user.setCityCode(request.getCityCode());
        user.setCityName(request.getCityName());
        user.setDistrictCode(request.getDistrictCode());
        user.setAvatar("imagedir/n1o1j9ndau_1670488066287.png");
        for (ClientRoleDto clientRoleDto : request.getClientRoleDtoList()) {
            log.info("请求参数:{}", clientRoleDto);
            if (clientRoleDto.getClientId().contains("freeway")) {
                user.setRoleId(clientRoleDto.getRoleId());
                user.setClientId(clientRoleDto.getClientId());
            }
        }
        user.setDeptId("");
        user.setStatus(1);
        user.setCreateTime(DateUtils.now());
        return user;
    }

    private String getClientId(String clientId) {
        String result = "";
        if (StringUtils.isNotEmpty(clientId)) {
            String[] clientValueArr = clientId.split(",");
            for (String clientValue : clientValueArr) {
                ClientEnum clientEnum = ClientEnum.parse(clientValue);
                if (null != clientEnum) {
                    result += clientEnum.getCode() + ",";
                }
            }
        }
        if (StringUtils.isNotEmpty(result)) {
            result = result.substring(0, result.length() - 1);
        } else {
            result = "1,2";
        }
        return result;
    }

    /**
     * 添加用户
     */
    private JsonResult 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.isNotNull(userTmp)) {
            log.info("创建租户用户，用户已存在，username：{}", user.getUsername());
            return JsonResult.error("创建租户用户，用户已存在");
        }

        // 如果顶级部门存在，将该超级管理员与顶级部门关联
//        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());
            return JsonResult.error("创建租户用户失败");
        }
        return JsonResult.success();
    }
}
