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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.code.user.EditUserStatusCodeEnum;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.service.third.oidc.OidcService;
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 UpdateUserStatusService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OidcService oidcService;

    /**
     * 修改用户状态数据
     *
     * @return
     */
    public JsonResult update(String id, Integer status) {
        log.info("进入修改用户状态业务接口: id={}, status={}", id, status);
        JsonResult result = this.check(id);
        if (0 != result.getCode()) {
            log.info("修改用户状态业务接口：校验失败：{}", result.getMsg());
            return result;
        }
        User user = User.builder().build().setId(id).setStatus(status);
        Integer rowCount = userMapper.updateById(user);
        if (rowCount <= 0) {
            return JsonResult.error(EditUserStatusCodeEnum.EDIT_IS_FAILED.getCode(), EditUserStatusCodeEnum.EDIT_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param id
     * @return
     */
    private JsonResult check(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(EditUserStatusCodeEnum.USER_ID_IS_NULL.getCode(), EditUserStatusCodeEnum.USER_ID_IS_NULL.getMsg());
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, id)
                .eq(User::getMark, 1));

        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(EditUserStatusCodeEnum.USER_IS_NOT_EXIST.getCode(), EditUserStatusCodeEnum.USER_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success();
    }

}
