package com.securitycontrol.auth.controller;


import com.securitycontrol.auth.form.LoginBody;
import com.securitycontrol.auth.service.SysLoginService;
import com.securitycontrol.auth.service.SysRecordLogService;
import com.securitycontrol.common.core.constant.Constant;
import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.JwtUtils;
import com.securitycontrol.common.redis.service.RedisService;
import com.securitycontrol.common.security.service.TokenService;
import com.securitycontrol.common.security.utils.SecurityUtils;
import com.securitycontrol.system.api.domain.decision.SysMenu;
import com.securitycontrol.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * token 控制
 *
 * @author czc
 */
@Api(tags = "系统登录")
@RestController
@Slf4j
public class TokenController {
    @Resource
    private TokenService tokenService;
    @Resource
    private RedisService redisUtil;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysRecordLogService recordLogService;


    @PostMapping("login")
    public Result<?> login(@RequestBody LoginBody form) {
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(), form.getLoginType(), null);
        // 获取登录token
        return Result.ok(tokenService.createToken(userInfo), "登录成功");
    }


    /**
     * 本地推出登录
     *
     * @param request
     * @return
     */
    @PostMapping("logout")
    public Result<?> loginOut(HttpServletRequest request) {
        String jwtToken = SecurityUtils.getToken(request);
        Claims claims = JwtUtils.parseToken(jwtToken);
        Integer userId = (Integer) claims.get(SecurityConstants.DETAILS_USER_ID);
        String iscUser = (String) claims.get(SecurityConstants.DETAILS_ISC_USER_ID);
        String userName = (String) claims.get(SecurityConstants.DETAILS_USERNAME);
        recordLogService.recordLogininfor(userName, Long.valueOf(userId + ""), "用户登出", null, 2);
        redisUtil.delete("token:" + jwtToken);
        redisUtil.delete("userId:" + userId);
        redisUtil.delete("ISCUserId:" + iscUser);
        redisUtil.delete("userName:" + userName);
        return Result.ok(null, "登出成功");
    }

    /**
     * @param request
     * @return Result<?>
     * @description 省侧大屏跳转施工大屏 调用后台返回用户信息
     * @author cwchen
     * @date 2024/3/26 18:10
     */
    @GetMapping("pageJump")
    public Result<?> pageJump(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(2);
        try {
            String jwtToken = SecurityUtils.getToken(request);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 获取登录token
            map.put("us", loginUser);
            map.put("access_token", jwtToken);
            return Result.ok(map, "校验成功");
        } catch (Exception e) {
            log.error("省侧大屏跳转施工大屏 用户数据获取", e);
            return Result.fail("校验失败");
        }
    }

    /**
     * 校验大屏跳转后台校验
     *
     * @param request
     * @return Result<?>
     * @description
     * @author cwchen
     * @date 2024/4/2 19:03
     */
    @GetMapping("validateToken")
    public Result<?> validateToken(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(2);
        try {
            String jwtToken = SecurityUtils.getToken(request);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String isAdmin = loginUser.getSysUser().getIsAdmin();
            String loginType = loginUser.getSysUser().getLoginType();
            List<SysMenu> sysMenuList = loginUser.getSysUser().getMenus();
            if (Objects.equals(isAdmin, Constant.IS_ADMIN) && loginType.contains(Constant.BACK_LOGIN)){
                List<SysMenu> filterSysMenuList = sysMenuList.stream().filter(e -> !Objects.equals(e.getMenuName(),Constant.SG_SCREEN_NAME)).collect(Collectors.toList());
                loginUser.getSysUser().setMenus(filterSysMenuList);
                // 获取登录token
                map.put("us", loginUser);
                map.put("access_token", jwtToken);
                return Result.ok(map, "校验成功");
            } else {
                return Result.fail("用户无访问后台权限");
            }
        } catch (Exception e) {
            log.error("施工大屏跳转后台校验", e);
            return Result.fail("校验失败");
        }
    }

}
