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.constant.SystemConstant;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.code.user.EditUserPasswordCodeEnum;
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.utils.CommonUtils;
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 ResetUserPasswordService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OidcService oidcService;

    /**
     * 修改用户密码数据
     *
     * @return
     */
    public JsonResult resetPassword(String id) {
        log.info("进入重置密码业务接口: id={}, status={}", id);
        JsonResult result = this.check(id);
        if (0 != result.getCode()) {
            log.info("重置密码业务接口：校验失败：{}", result.getMsg());
            return result;
        }
        User user = (User) result.getData();

        // 修改oidc用户密码
        result = oidcService.editUserPassword(user, SystemConstant.INIT_PASSWORD);
        if (0 != result.getCode()) {
            log.info("重置密码业务接口：修改oidc用户密码失败：{}", result.getMsg());
            return result;
        }

        user.setPassword(CommonUtils.password(SystemConstant.INIT_PASSWORD));
        Integer rowCount = userMapper.updateById(user);
        if (rowCount <= 0) {
            return JsonResult.error(EditUserPasswordCodeEnum.EDIT_IS_FAILED.getCode(), EditUserPasswordCodeEnum.EDIT_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param id
     * @return
     */
    private JsonResult check(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(EditUserPasswordCodeEnum.USER_ID_IS_NULL.getCode(), EditUserPasswordCodeEnum.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(EditUserPasswordCodeEnum.USER_IS_NOT_EXIST.getCode(), EditUserPasswordCodeEnum.USER_IS_NOT_EXIST.getMsg());
        }
        if (!user.getTenantId().equals(CurrentUserUtil.getTenantId())) {
            return JsonResult.error(EditUserPasswordCodeEnum.NON_TENANT_USER.getCode(), EditUserPasswordCodeEnum.NON_TENANT_USER.getMsg());
        }
        return JsonResult.success(user);
    }

}
