package com.jiayue.ssi.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ssi.annotation.OperateLog;
import com.jiayue.ssi.backenum.AuditType;
import com.jiayue.ssi.backenum.BusinessStatus;
import com.jiayue.ssi.backenum.BusinessType;
import com.jiayue.ssi.entity.SysAlarm;
import com.jiayue.ssi.entity.SysOperLog;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.factory.OperateLogFactory;
import com.jiayue.ssi.service.SysPolicyService;
import com.jiayue.ssi.util.DateUtils;
import com.jiayue.ssi.util.IPUtils;
import com.jiayue.ssi.util.JwtTokenUtil;
import com.jiayue.ssi.util.ServletUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 权限不足：认证过的用户访问无权限资源时的异常
 *
 * @author zzy
 * @version 1.0
 * @since 2018/8/23 14:45
 */
@Service
@Slf4j
public class RestAccessDeniedHandler implements AccessDeniedHandler {
    @Autowired
    SysPolicyService sysPolicyService;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        String token = request.getHeader("Authorization");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Claims claims = jwtTokenUtil.getClaimsFromToken(token);
        String username="";
        if (claims==null){
            username = "未知用户";
        }
        else{
            username = claims.getSubject();
        }
        SysOperLog operLog = new SysOperLog();
        operLog.setStatus(BusinessStatus.FAIL.ordinal());
        // 请求的地址
        String ip = IPUtils.getIpAddr();
        operLog.setOperIp(ip);
        operLog.setOperUrl(org.apache.commons.lang3.StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        operLog.setOperName(username);
        // 设置请求方式
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        operLog.setCreateBy(username);
        // 设置action动作
        operLog.setBusinessType(BusinessType.BAC.ordinal());
        // 设置标题
        operLog.setTitle("越权访问");
        // 操作描述
        operLog.setOperdesc("越权访问");
        // 审计类型
        operLog.setAuditType(AuditType.SYS.ordinal());
        // 保存数据库
        OperateLogFactory.recordOper(operLog);
        SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
        String noticeWay = "";
        if ("0".equals(sysPolicy.getExcLevelLogin())){
            noticeWay = sysPolicy.getExcNoticeWayA();
        } else if ("1".equals(sysPolicy.getExcLevelLogin())){
            noticeWay = sysPolicy.getExcNoticeWayB();
        }

        // 通知系统管理员
        if ("0".equals(noticeWay)){
            log.info("发送邮箱越权访问\r\n" +
                    "↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓邮箱内容↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓"+
                    "\r\n  账号："+username+"  越权访问："+ org.apache.commons.lang3.StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255)+" \r\n"     +
                    "↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑邮箱内容↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
//            log.info("发送邮箱通知系统管理员后台输出======> "+"账号【"+username+"】越权访问"+org.apache.commons.lang3.StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
//                        List<SysUser> sysUserList = sysUserService.selectUserByRole("1");
//                        if (sysUserList.size()>0){
//                            String[] mailArray = new String[sysUserList.size()];
//                            for (int i=0;i<sysUserList.size();i++){
//                                mailArray[i] = AesUtils.decryptStr(sysUserList.get(i).getMailbox());
//                            }
//                            try {
//                                // 发送邮件
//                                sendMailUtil.executeSendMail(mailArray,"账号【"+user.getUsername()+"】登录失败","账号【"+user.getUsername()+"】登录失败"+errCount+"次，锁定账号！");
//                            } catch (Exception ex) {
//                                System.out.println("邮箱验证码发送失败！");
//                            }
//                        }
        }
        else if ("1".equals(noticeWay)){
            // 告警先不用了，系统里只用一种邮箱告警
        }



        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setStatus(402);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("没有接口访问权限！");
    }
}
