package com.xjrsoft.module.organization.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.Post;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.mapper.DepartmentMapper;
import com.xjrsoft.module.organization.mapper.PostMapper;
import com.xjrsoft.module.organization.service.IPostService;
import com.xjrsoft.module.organization.vo.SwitchPostVo;
import com.xjrsoft.module.system.dto.SwitchPostDto;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 岗位 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-03-02
 */
@Service
@AllArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    private DepartmentMapper departmentMapper;

    private RedisUtil redisUtil;

    @Override
    public SwitchPostVo switchPost(SwitchPostDto dto) {
        SwitchPostVo result = new SwitchPostVo();

        Post post = getById(dto.getPostId());
        Department department = departmentMapper.selectById(post.getDeptId());

        result.setPostId(post.getId());
        result.setPostName(post.getName());
        result.setDepartmentId(department.getId());
        result.setDepartmentName(department.getName());

        SaSession tokenSession = StpUtil.getTokenSession();

        User loginUser = tokenSession.get(GlobalConstant.LOGIN_USER_INFO_KEY, new User());
        loginUser.setPostId(post.getId());
        loginUser.setDepartmentId(department.getId());

        tokenSession.set(GlobalConstant.LOGIN_USER_INFO_KEY, loginUser);
        tokenSession.set(GlobalConstant.LOGIN_USER_POST_INFO_KEY, post);
        tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);

        //将登陆人所选择的身份缓存起来
        //切换身份的时候 会一起修改
        redisUtil.set(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId(), post.getId());


        return result;
    }
}
