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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.Role;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.enums.code.user.EditUserCodeEnum;
import com.tuoheng.admin.mapper.RoleMapper;
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 UpdateUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private OidcService oidcService;

    /**
     * 修改用户数据
     *
     * @return
     */
    public JsonResult update(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 userOld = (User) result.getData();

        result = this.notifyOicd(userOld, user);
        if (0 != result.getCode()) {
            log.info("修改用户业务接口：校验失败：{}", result.getMsg());
            return result;
        }

        this.buildUser(user);

        Integer rowCount = userMapper.updateById(user);
        if (rowCount <= 0) {
            return JsonResult.error();
        }
        return JsonResult.success();
    }

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

    /**
     * 同步修改oicd数据
     *  1）、如果roleId和clientId没有变动，则不需要通知oicd
     *
     * @param userOld
     * @param userNew
     *
     */
    private JsonResult notifyOicd(User userOld, User userNew) {
        if (userOld.getRoleId().equals(userNew.getRoleId())
            && userOld.getClientId().equals(userNew.getClientId())) {
            log.info("修改用户业务接口：角色和clientId，没有变动，不需要同步通知oicd。");
            return JsonResult.success("角色和clientId，没有变动，不需要同步通知oicd");
        }
        log.info("修改用户业务接口：角色和clientId，变动，同步通知oicd。");
        // 修改oidc
        userNew.setUsername(userOld.getUsername());
        JsonResult result = oidcService.editUser(userNew);
        if (0 != result.getCode()) {
            log.info("修改用户业务接口：修改oidc数据失败：{}", result.getMsg());
            return result;
        }
        return JsonResult.success("角色和clientId，通知oicd成功");
    }

    /**
     * 构建实体字段数据
     *
     * @param user
     */
    private void buildUser(User user) {
        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.setUpdateUser(CurrentUserUtil.getUserId());
        user.setUpdateTime(DateUtils.now());
    }

}
