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.Tenant;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.ClientEnum;
import com.tuoheng.admin.enums.MarkEnum;
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.EditOidcTenantRequest;
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 EditOidcTenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private EditOidcUserService editOidcUserService;

    @Autowired
    private EditOidcUserPasswordService editOidcUserPasswordService;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult editTenant(EditOidcTenantRequest request) {
        log.info("修改租户业务");
        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("修改租户业务：校验失败：{}", result.getMsg());
            return result;
        }
        Tenant tenant = (Tenant) result.getData();

        User oldUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getUsername())
                .eq(User::getMark, MarkEnum.VALID.getCode()));
        User user = this.buildUser(request);

        //if (StringUtils.isNotEmpty(request.getClientId()) && !oldUser.getClientId().equals(user.getClientId())) {
        //    // 修改oidc用户
        //    result = editOidcUserService.edit(user);
        //    if (0 != result.getCode()) {
        //        log.info("修改租户业务：修改oidc用户信息失败：{}", result.getMsg());
        //        return result;
        //    }
        //} else {
        //    log.info("修改租户业务：用户信息不需要修改");
        //}

        if (StringUtils.isNotEmpty(request.getPassword()) && !oldUser.getPassword().equals(user.getPassword())) {
            // 修改oidc用户密码由oidc自己处理
            // oidc密码不需要业务系统去修改
//            log.info("修改租户业务：oidc密码不需要业务系统去修改");
//            result = editOidcUserPasswordService.editUserPassword(user, request.getPassword());
//            if (0 != result.getCode()) {
//                log.info("修改租户业务：修改oidc用户密码失败：{}", result.getMsg());
//                return result;
//            }
        } else {
            log.info("修改租户业务：用户密码不需要修改");
        }

        result = this.updateTenant(tenant, request);
        if (0 != result.getCode()) {
            log.info("修改租户业务：修改租户失败：{}", result.getMsg());
            return result;
        }

        result = this.editUser(user);
        if (0 != result.getCode()) {
            log.info("修改租户业务：修改用户失败：{}", result.getMsg());
            return result;
        }

        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @param
     * @return
     */
    private JsonResult check(EditOidcTenantRequest request) {
        if (StringUtils.isEmpty(request.getUsername())) {
            return JsonResult.error(400, "用户名为空");
        }
        if (StringUtils.isEmpty(request.getTenantName())) {
            return JsonResult.error(400, "租户名称为空");
        }
        if (StringUtils.isEmpty(request.getTenantCode())) {
            return JsonResult.error(400, "租户编号");
        }
        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("系统中不存在该租户");
        }
        Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getUsername())
                .eq(User::getMark, MarkEnum.VALID.getCode()));
        if (count <= 0) {
            return JsonResult.error(400, "系统中不存在该用户");
        }
        return JsonResult.success(tenant);
    }

    /**
     * 修改租户
     */
    private JsonResult updateTenant(Tenant tenant, EditOidcTenantRequest request) {
        // 如果是租户先去创建
        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());
        Integer count = tenantMapper.updateById(tenant);
        if (count <= 0) {
            log.info("修改租户失败");
            JsonResult.error("修改租户失败");
        }
        return JsonResult.success(tenant);
    }

    /**
     * 构建用户数据
     */
    private User buildUser(EditOidcTenantRequest request) {
        // 创建用户数据
        User user = new User();
        user.setUsername(request.getUsername());
        user.setRealname(request.getTenantName());
        user.setNickname(request.getTenantName());
        if (StringUtils.isNotEmpty(request.getPassword())) {
            user.setPassword(CommonUtils.password(request.getPassword()));
        }
        if (StringUtils.isNotEmpty(request.getProvinceCode())) {
            user.setProvinceCode(request.getProvinceCode());
        }
        if (StringUtils.isNotEmpty(request.getCityCode())) {
            user.setCityCode(request.getCityCode());
        }
        if (StringUtils.isNotEmpty(request.getCityName())) {
            user.setCityName(request.getCityName());
        }
        if (StringUtils.isNotEmpty(request.getDistrictCode())) {
            user.setDistrictCode(request.getDistrictCode());
        }
        for (ClientRoleDto clientRoleDto : request.getClientRoleDtoList()) {
            log.info("请求参数:{}", clientRoleDto);
            if (clientRoleDto.getClientId().contains("freeway")) {
                user.setRoleId(clientRoleDto.getRoleId());
                user.setClientId(clientRoleDto.getClientId());
            }
        }
        user.setUpdateTime(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 editUser(User user) {
        User userTmp = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, MarkEnum.VALID.getCode())
                .eq(User::getStatus, 1)
                .eq(User::getUsername, user.getUsername()));
        if (ObjectUtil.isNull(userTmp)) {
            log.info("修改租户用户，用户不存在，username：{}", user.getUsername());
            return JsonResult.error("修改租户用户，不用户存在");
        }
        user.setId(userTmp.getId());
        if (StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(userTmp.getPassword());
        }
        Integer rowCount = userMapper.updateById(user);
        if (rowCount <= 0) {
            log.info("修改租户用户失败，username：{}", user.getUsername());
            return JsonResult.error("修改租户用户失败");
        }
        return JsonResult.success();
    }
}
