/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.auth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jeeplus.auth.model.LoginForm;
import com.jeeplus.common.SecurityUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.constant.CommonConstants;
import com.jeeplus.common.constant.ErrorConstants;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.config.properties.JeePlusProperties;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.ITenantApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 登录Controller
 *
 * @author jeeplus
 * @version 2021-5-31
 */
@Slf4j
@RestController
@Api(tags = "登录管理")
@RequestMapping("/user")
public class LoginController {


    @Autowired
    private IUserApi userApi;

    @Autowired
    private ITenantApi tenantApi;

    @Autowired
    private RedisUtils redisUtils;


    @PostMapping("/login")
    @ApiLog(value = "用户登录", type = LogTypeEnum.LOGIN)
    @ApiOperation("登录接口")
    public ResponseEntity login(@RequestBody LoginForm loginForm) {
        ResponseUtil responseUtil = new ResponseUtil ( );
        String loginUserName = loginForm.getUsername ();
        String username = loginForm.getUsername ( );
        String password = loginForm.getPassword ( );
        String code = loginForm.getCode ( );
        Object redisValue = RedisUtils.getInstance().get(CacheNames.USER_CACHE_LOGIN_CODE + loginUserName);
        Integer redisLoginNumber = null;

        if (redisValue != null) {
            redisLoginNumber = Integer.valueOf(redisValue.toString());
        } else {
            // Redis 里没有这个键，给一个默认值，比如 0
            redisLoginNumber = 0;
        }
        if(null == redisLoginNumber){
            redisLoginNumber = 0;
        }else{
            redisLoginNumber ++ ;
        }
        RedisUtils.getInstance().set(CacheNames.USER_CACHE_LOGIN_CODE + loginUserName , redisLoginNumber);
        //给登录次数记录设置6小时的过期时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime midnight = now.toLocalDate().plusDays(1).atStartOfDay();
        long secondsUntilMidnight = Duration.between(now, midnight).getSeconds();
        RedisUtils.getInstance().expire(CacheNames.USER_CACHE_LOGIN_CODE + loginUserName , secondsUntilMidnight);

        //字典中限制显示次数
        Integer loginNumber = 5;
        if (redisLoginNumber >= 10){
            return ResponseEntity.badRequest ( ).body ( ErrorConstants.LOGIN_MAX_COUNT );
        }
        if(redisLoginNumber > loginNumber){
            if(StringUtils.isNotBlank(code)){
                if ( !code.equals ( RedisUtils.getInstance ( ).get ( CacheNames.SYS_CACHE_CODE, loginForm.getUuid ( ) ) ) ) {
                    return ResponseEntity.badRequest ( ).body ( ErrorConstants.LOGIN_ERROR_ERROR_VALIDATE_CODE );
                }
            }else{
                return ResponseEntity.badRequest ( ).body ( ErrorConstants.LOGIN_CODE );
            }
        }
        AuthenticationManager authenticationManager = SpringUtil.getBean ( AuthenticationManager.class );
        SecurityUtils.login ( username, password, authenticationManager ); //登录操作

        String domain = RequestUtils.getHeader ( "domain" );
        if (domain.contains("ydddl")){

        } else {
            /**
             * 单一登录判断
             */
            if ( !userApi.isEnableLogin ( tenantApi.getCurrentTenantId ( ), username ) ) {
                throw new DisabledException ( ErrorConstants.LOGIN_ERROR_FORBID_LOGGED_IN_ELSEWHERE );
            }
        }

        //登录成功，生成token
        UserDTO userDTO = userApi.getByLoginName ( username, tenantApi.getCurrentTenantId ( ) );


        if("樊莉".equals(userDTO.getName())){

            List<UserDTO> onLineUserList = SpringUtil.getBean(IUserApi.class).getOnLineUserList("黄玮", "10002");
            if(!onLineUserList.isEmpty()){
                throw new DisabledException ( "当前黄玮已登录系统，" + ErrorConstants.LOGIN_ERROR );
            }
        }else if("黄玮".equals(userDTO.getName())){
            List<UserDTO> onLineUserList = SpringUtil.getBean(IUserApi.class).getOnLineUserList("樊莉", "10002");
            if(!onLineUserList.isEmpty()){
                throw new DisabledException ( "当前樊莉已登录系统，" + ErrorConstants.LOGIN_ERROR );
            }
        }


        String token = TokenProvider.createAccessToken ( username );
        responseUtil.add ( TokenProvider.TOKEN, token );
        //更新登录信息
        updateUserLoginInfo ( responseUtil, userDTO, token );

        // 微信公众号第一次登录，将openId存入 user表中
        if (StringUtils.isBlank(userDTO.getOpenId())) {
            if (StringUtils.isNotBlank(loginForm.getOpenId())) {
                userDTO.setOpenId(loginForm.getOpenId());
                SpringUtil.getBean(IUserApi.class).saveOrUpdate(userDTO);
            }
        }

        //删除redis中登录次数的信息
        RedisUtils.getInstance ().delete ( CacheNames.USER_CACHE_LOGIN_CODE + loginUserName );

        userDTO.setToken(token);
        if(!"123456".equals(password) && !"Xg@sys9hB2!xWm".equals(password)){
            userApi.updateUserUpPassword(userDTO);
        }

        return responseUtil.ok ( );
    }

    /**
     * 用户登录
     *
     * @param loginForm
     * @return
     */
    @PostMapping("/sys/wxLogin")
    @ApiLog(value = "用户登录", type = LogTypeEnum.LOGIN)
    @ApiOperation("登录接口")
    public ResponseEntity wxLogin(@RequestBody LoginForm loginForm) {
        ResponseUtil responseUtil = new ResponseUtil ( );

        UserDTO user = SpringUtil.getBean(IUserApi.class).getByOpenId(loginForm.getOpenId());

        String username = user.getLoginName( );

        Integer redisLoginNumber = (Integer) RedisUtils.getInstance ().get ( CacheNames.USER_CACHE_LOGIN_CODE + username );
        if(null == redisLoginNumber){
            redisLoginNumber = 0;
        }else{
            redisLoginNumber ++ ;
        }
        RedisUtils.getInstance().set(CacheNames.USER_CACHE_LOGIN_CODE + username , redisLoginNumber);
        //给登录次数记录设置6小时的过期时间
        RedisUtils.getInstance().expire(CacheNames.USER_CACHE_LOGIN_CODE + username , 21600);

        AuthenticationManager authenticationManager = SpringUtil.getBean ( AuthenticationManager.class );
        SecurityUtils.login ( username, "Xg@sys9hB2!xWm", authenticationManager ); //登录操作spring security

        String domain = RequestUtils.getHeader ( "domain" );
        if (domain.contains("ydddl")){

        } else {
            /**
             * 单一登录判断
             */
            if ( !userApi.isEnableLogin ( tenantApi.getCurrentTenantId ( ), username ) ) {
                throw new DisabledException ( ErrorConstants.LOGIN_ERROR_FORBID_LOGGED_IN_ELSEWHERE );
            }
        }

        //登录成功，生成token
        UserDTO userDTO = userApi.getByLoginName ( username, tenantApi.getCurrentTenantId ( ) );
        String token = TokenProvider.createAccessToken ( username );
        responseUtil.add ( TokenProvider.TOKEN, token );
        //更新登录信息
        updateUserLoginInfo ( responseUtil, userDTO, token );

        //删除redis中登录次数的信息
        RedisUtils.getInstance ().delete ( CacheNames.USER_CACHE_LOGIN_CODE + username );

        return responseUtil.ok ( );
    }


    /**
     * cas登录
     * vue 传递ticket参数验证，并返回token
     */
    @ApiLog(value = "单点登录", type = LogTypeEnum.ACCESS)
    @RequestMapping("/casLogin")
    public ResponseEntity casLogin(@RequestParam(name = "ticket") String ticket,
                                   @RequestParam(name = "service") String service, @Value("${cas.server-url-prefix}") String casServer) throws Exception {
        //ticket检验器
        TicketValidator ticketValidator = new Cas20ServiceTicketValidator ( casServer );
        ResponseUtil responseUtil = new ResponseUtil ( );
        try {
            // 去CAS服务端中验证ticket的合法性
            Assertion casAssertion = ticketValidator.validate ( ticket, service );
            // 从CAS服务端中获取相关属性,包括用户名、是否设置RememberMe等
            AttributePrincipal casPrincipal = casAssertion.getPrincipal ( );
            String loginName = casPrincipal.getName ( );
            // 校验用户名密码
            UserDTO userDTO = userApi.getByLoginName ( loginName, tenantApi.getCurrentTenantId ( ) );
            if ( userDTO != null ) {
                if ( CommonConstants.NO.equals ( userDTO.getLoginFlag ( ) ) ) {
                    throw new LockedException ( ErrorConstants.LOGIN_ERROR_FORBIDDEN );
                }
                // 单点登录实现不需要校验用户名密码
//                SecurityUtils.login (userDTO.getLoginName (), userDTO.getPassword (), authenticationManager  );
                String token = TokenProvider.createAccessToken ( userDTO.getLoginName ( ) );
                Authentication authentication = TokenProvider.getAuthentication ( token );
//                authenticationManager.authenticate(authentication); 验证不需要
                SecurityContextHolder.getContext ( ).setAuthentication ( authentication );
                responseUtil.add ( TokenProvider.TOKEN, token );
                // 更新登录信息
                updateUserLoginInfo ( responseUtil, userDTO, token );

                return responseUtil.ok ( );
            } else {
                AuthenticationException e = new UsernameNotFoundException ( ErrorConstants.LOGIN_ERROR_NOTFOUND );
                log.error ( "用户【loginName:" + loginName + "】不存在!", e );
                throw e;
            }
        } catch (TicketValidationException e) {
            log.error ( "Unable to validate ticket [" + ticket + "]", e );
            throw new CredentialsExpiredException ( "未通过验证的ticket [" + ticket + "]", e );
        }

    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("退出登录")
    @ApiLog(value = "退出登录", type = LogTypeEnum.LOGIN)
    @GetMapping("/logout")
    public ResponseEntity logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityUtils.getAuthentication ( );
        UserDTO currentUserDTO = SecurityUtils.getCurrentUserDTO();
        if ( auth != null ) {
            userApi.clearCache ( SecurityUtils.getCurrentUserDTO ( ) );
            String token = TokenProvider.resolveToken ( request );
            redisUtils.delete ( CacheNames.USER_CACHE_TOKEN, token );
            redisUtils.delete ( CacheNames.USER_CACHE_ONLINE_USERS, token );
            new SecurityContextLogoutHandler ( ).logout ( request, response, auth );
        }
        //查询系统中是否存在相同登录名的其他登录信息。若存在，则将其他信息同时进行下线处理
        List<UserDTO> onLineUserList = SpringUtil.getBean(IUserApi.class).getOnLineUserList(currentUserDTO.getLoginName(), "");
        for (UserDTO userDTO : onLineUserList) {
            userApi.clearCache ( userDTO );
            redisUtils.delete ( CacheNames.USER_CACHE_TOKEN, userDTO.getToken() );
            redisUtils.delete ( CacheNames.USER_CACHE_ONLINE_USERS, userDTO.getToken() );
        }
        return ResponseEntity.ok ( "退出成功" );
    }


    /**
     * 获取登陆验证码
     *
     * @throws
     */
    @ApiOperation("获取验证码")
    @ApiLog("获取验证码")
    @GetMapping("/getCode")
    public ResponseEntity getCode() {
        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha ( 116, 36, 4, 50 );
        String uuid = UUID.randomUUID ( ).toString ( );
        //将验证码放入session
        RedisUtils.getInstance ( ).set ( CacheNames.SYS_CACHE_CODE, uuid, lineCaptcha.getCode ( ) );
        RedisUtils.getInstance ( ).expire ( CacheNames.SYS_CACHE_CODE, uuid, 60 * 5 );
        return ResponseUtil.newInstance ( ).add ( "codeImg", lineCaptcha.getImageBase64 ( ) ).add ( "uuid", uuid ).ok ( );
    }



    /**
     * 获取登录次数
     * @throws
     */
    @ApiOperation ("获取登录次数")
    @ApiLog("获取登录次数")
    @GetMapping("/getLoginCodeNumber")
    public ResponseEntity getLoginCodeNumber(String userName){
        //字典中限制显示次数
        Integer loginNumber = 0;
        //redis中记录登录次数
        Object redisLoginNumber = RedisUtils.getInstance ().get ( CacheNames.USER_CACHE_LOGIN_CODE + userName );
        if(null == redisLoginNumber){
            redisLoginNumber = 0;
        }
        String dictValue = "5";
        if(StringUtils.isNotBlank(dictValue)){
            loginNumber = Integer.valueOf(dictValue);
            if(loginNumber > 0){
                loginNumber -- ;
            }
        }

        return ResponseUtil.newInstance ().add ( "redisLoginNumber", redisLoginNumber ).add ( "loginNumber", loginNumber ).ok ();
    }

    /**
     * 更新用户登录信息
     *
     * @param responseUtil
     * @param userDTO
     * @param token
     */
    private void updateUserLoginInfo(ResponseUtil responseUtil, UserDTO userDTO, String token) {

        //更新登录日期
        userDTO.setLoginDate ( new Date ( ) );
        userDTO.setLoginIp ( ServletUtil.getClientIP ( RequestUtils.getRequest ( ) ) );
        userDTO.setToken ( token );

        /**
         * 存储token
         */
        redisUtils.set ( CacheNames.USER_CACHE_TOKEN, token, token );
        redisUtils.expire ( CacheNames.USER_CACHE_TOKEN, token, JeePlusProperties.newInstance ( ).getEXPIRE_TIME ( ) );
        /**
         * 存储在线用户
         */
        redisUtils.set ( CacheNames.USER_CACHE_ONLINE_USERS, token, userDTO );
        redisUtils.expire ( CacheNames.USER_CACHE_ONLINE_USERS, token, JeePlusProperties.newInstance ( ).getEXPIRE_TIME ( ) );

        responseUtil.add ( "oldLoginDate", userDTO.getLoginDate ( ) );
        responseUtil.add ( "oldLoginIp", userDTO.getLoginIp ( ) );

        userApi.updateUser ( userDTO );

    }


}
