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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.entity.request.third.oidc.DeletedOidcTenantRequest;
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 DeletedOidcTenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult deletedTenant(DeletedOidcTenantRequest request) {
        log.info("删除租户业务");
        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("删除租户业务：校验失败：{}", result.getMsg());
            return result;
        }
        Tenant tenant = tenantMapper.selectOne(new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getUsername, request.getUsername())
                .eq(Tenant::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(tenant)) {
            return JsonResult.error("系统中不存在该租户");
        }
        Tenant tenantTmp = new Tenant();
        tenantTmp.setId(tenant.getId());
        tenantTmp.setMark(MarkEnum.NOTVALID.getCode());
        Integer count = tenantMapper.updateById(tenantTmp);
        if (count <= 0) {
            log.info("删除租户失败，username：{}", request.getUsername());
            JsonResult.error("删除租户失败");
        }

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getUsername())
                .eq(User::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(400, "系统中不存在该用户");
        }
        User userTmp = new User();
        userTmp.setId(user.getId());
        userTmp.setMark(MarkEnum.NOTVALID.getCode());
        Integer rowCount = userMapper.updateById(userTmp);
        if (rowCount <= 0) {
            log.info("删除租户用户失败，username：{}", request.getUsername());
            return JsonResult.error("删除租户用户失败");
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @param
     * @return
     */
    private JsonResult check(DeletedOidcTenantRequest request) {
        if (StringUtils.isEmpty(request.getUsername())) {
            return JsonResult.error(400, "用户名为空");
        }
        return JsonResult.success();
    }

}
