package com.nokia.hb.service;

import com.alibaba.fastjson2.JSON;
import com.nokia.common.R;
import com.nokia.hb.dao.entity.User;
import com.nokia.hb.dao.mapper.UserAreaMapper;
import com.nokia.hb.dao.mapper.UserMapper;
import com.nokia.hb.pojo.dto.LoginDto;
import com.nokia.hb.pojo.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AuthService {
    private final UserMapper userMapper;
    private final UserAreaMapper userAreaMapper;
    private final SessionService sessionService;

    public AuthService(UserMapper userMapper, UserAreaMapper userAreaMapper, SessionService sessionService) {
        this.userMapper = userMapper;
        this.userAreaMapper = userAreaMapper;
        this.sessionService = sessionService;
    }

    public R<LoginVo> userLogin(LoginDto dto, HttpSession session) {
        if (sessionService.logged(dto.getUsername())) {
            return R.error("账号已在其他设备登录！");
        }
        User user = userMapper.getByUsername(dto.getUsername());
        if (user == null || !dto.getPassword().equals(user.getPassword())) {
            return R.error("用户名或密码错误！");
        }
        // 查询用户地区权限
        List<String> areas = userAreaMapper.listByUsername(dto.getUsername());
        Map<String, String> map = new HashMap<>();
        areas.forEach(t -> map.put(t, ""));
        log.debug("areas: {}", JSON.toJSONString(map.keySet()));
        // 保存session
        session.setAttribute("username", dto.getUsername());
        session.setAttribute("areas", map);
        sessionService.update(session);
        return R.ok(new LoginVo(dto.getUsername()));
    }

    public R<Object> logout(HttpSession session) {
        sessionService.invalidate(session);
        return R.ok();
    }
}
