package com.qy.worksheetsystem.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qy.worksheetsystem.model.MessageResult;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author he
 * @date 2022/2/28
 * @description  JWT工具类
 */
public class JWTUtil {
    // 过期时间 24 小时
    private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;
    // 密钥
    private static final String SECRET = "ysh_20220228";

    /**
     * 生成 token
     */
    public static String createToken(String number) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 附带username信息
            return JWT.create()
                    .withClaim("number", number)
                    //到期时间
                    .withExpiresAt(date)
                    //创建一个新的JWT，并使用给定的算法进行标记
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String createToken(String number,String userid) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 附带username信息
            return JWT.create()
                    .withClaim("number", number)
                    .withClaim("userid", userid)
                    //到期时间
                    .withExpiresAt(date)
                    //创建一个新的JWT，并使用给定的算法进行标记
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * 校验 token 是否正确
     */
    public static boolean verify(String token, String number) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //在token中附带了username信息
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("number", number)
                    .build();
            //验证 token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public static String getNumber(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("number").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userid").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    public static boolean checkAvailableDate(LocalDate date){
        LocalDateTime nowTime = LocalDateTime.now();
        nowTime=nowTime.plusDays(5);
        LocalDateTime localDateTime8 = LocalDateTime.of(nowTime.getYear(), nowTime.getMonth(), 8, 0, 0);
        //默认可填报日期
        LocalDateTime startDate =  LocalDateTime.of(nowTime.getYear(), nowTime.getMonth(), 1, 0, 0);
        if(nowTime.compareTo(localDateTime8)<0){
            startDate=startDate.plusMonths(-1);
        }
        LocalDate begin1 = date;
        LocalDateTime begin = begin1.atTime(0,0);
        System.out.println(startDate);
        System.out.println();
        return (startDate.compareTo(begin)<=0) ? true : false;
    }

    public static void main(String[] args) throws ParseException {
        String token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJudW1iZXIiOiI4MDAxMDI5MSIsImV4cCI6MTY2OTcwNTYyMH0.c-9GI1KLFwWZBwpBFoNfoaqDCbSlqTwc_TYibsmsv7U";
        System.out.println(token);
        String userid = JWTUtil.getNumber(token);
        System.out.println(userid);
        String number = JWTUtil.createToken("80004278");
        System.out.println("main:"+number);
        Object obj = false;
        System.out.println(obj instanceof Boolean);
        System.out.println("currentTimeMillis:"+ System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormatf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateFormat.format(new Date(System.currentTimeMillis())));
        System.out.println(dateFormatf.format(dateFormat.parse(dateFormat.format(new Date(System.currentTimeMillis())))));
        //1664444625321
        //1664486400000
        //1664444946885
        //1664409600000
        LocalDate date = LocalDate.parse("2022-12-12", DateTimeFormatter.ISO_LOCAL_DATE);
        System.out.println(checkAvailableDate(date));;




        try {
            String[] dateArr = "2024-02-23".split("-");
            Month month = Month.of(Integer.parseInt(dateArr[1]));
            LocalDate localDate = LocalDate.of(Integer.parseInt(dateArr[0]), month, 1);
            LocalDate stratLocalDate = localDate.plusMonths(-2);
            LocalDate endLocalDate = LocalDate.of(Integer.parseInt(dateArr[0]),
                    month,
                    month.length(stratLocalDate.isLeapYear()));

            System.out.println( "stratLocalDate"+  stratLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
                    );
            System.out.println(  "endLocalDate"+ endLocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
                    );

            //获取shr年假额度
            Map<String, Object> holidayLimit = new HashMap<>();
            holidayLimit.put("remainLimit",BigDecimal.valueOf(13.0000000000));
            //获取在途的年假
            Map<String, Object> map = new HashMap<>();
            map.put("workinghours",11);
            int transit = 0;
            if (null != map) {
                transit = (int) map.get("workinghours");
            }
            //获取已用的年假
            Map<String, Object> map1 = new HashMap<>();
            map1.put("workinghours",12);
            int used = 0;
            if (null != map1) {
                used = (int) map1.get("workinghours");
            }
            BigDecimal remainLimit = BigDecimal.ZERO;
            if (null != holidayLimit) {
                remainLimit = (BigDecimal) holidayLimit.get("remainLimit");
            }

            int workingHours = 0;

                String dateType = "0";
                //是工作日则增加
                if ("0".equals(dateType)) {
                    workingHours += 8;
                }


            //加上在途的
            workingHours = workingHours+transit+used;
            if(remainLimit.intValue()<=0){
                MessageResult result = new MessageResult();
                result.setCode(403);
                result.setMsg("剩余年假额度不足");

            }else if (workingHours > remainLimit.intValue()) {
                MessageResult result = new MessageResult();
                result.setCode(403);
                result.setMsg("剩余年假额度不足");
            } else{
                MessageResult result = MessageResult.success();

            }

        }catch (Exception e){
            e.printStackTrace();

        }finally {

        }
    }
}