package com.usky.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.SysUserPerson;
import com.usky.system.mapper.SysUserPersonMapper;
import com.usky.system.service.SysUserPersonService;
import com.usky.common.mybatis.core.AbstractCrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 用户人员关联 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-08-22
 */
@Service
public class SysUserPersonServiceImpl extends AbstractCrudService<SysUserPersonMapper, SysUserPerson> implements SysUserPersonService {

    @Autowired
    private SysUserPersonMapper sysUserPersonMapper;

    @Override
    public Integer upIsLoginNotify(Long userId, Integer isLoginNotify) {

        // 判断 isLoginNotify 是否为 0 或 1
        if (isLoginNotify != 0 && isLoginNotify != 1) {
            throw new BusinessException("参数设置错误");
        }
        // 判断要修改的用户是否为登录用户
        if (!Objects.equals(userId, SecurityUtils.getUserId())) {
            throw new BusinessException("你不能修改非本人的登录通知设置！");
        }

        // 更新登录通知设置
        LambdaUpdateWrapper<SysUserPerson> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUserPerson::getUserId, userId)
                .set(SysUserPerson::getIsLoginNotify, isLoginNotify);
        int result = sysUserPersonMapper.update(null, wrapper);

        //  更新失败
        if (result <= 0) {
            log.error("用户：{}，操作登录通知开关操作失败！");
            throw new BusinessException("登录通知开关操作失败！请重试");
        }

        return result;
    }
}
