package com.kingdee.eas.custom.integration.base.util;

import com.kingdee.eas.cp.eip.sso.ltpa.LtpaTokenManager;
import com.kingdee.eas.custom.integration.base.exception.CommonErrorCodes;
import com.kingdee.eas.custom.integration.base.exception.IntegrationException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Token工具类，提供token的加密生成和解析功能
 */
public class MbosTokenUtils {

    private static final Logger logger = LoggerFactory.getLogger(MbosTokenUtils.class);
    // Token有效期 10分钟
    private static final Long EXPIRE_TIME = 600000L;

    /**
     * 生成移动端 MBOS Token
     **/
    public static HashMap<String, String> generateMbosTokenMap(String userNumber) {
        if (StringUtils.isBlank(userNumber)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "用户账号为空!");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userNumber", userNumber);

        // 设置 Token 过期时间为 10 分钟后
        params.put("expiredDate", System.currentTimeMillis() + EXPIRE_TIME);

        // 获取加密密钥
        String dominoSecret = EncryptUtil.getProperty(LtpaTokenManager.DOMINO_SECRET);
        if (StringUtils.isBlank(dominoSecret)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "移动回调失败，加密密钥为空！");
        }

        // 使用密钥对参数进行加密
        String encrypted = EncryptUtil.encryptMap(params, dominoSecret);
        logger.info("移动端回调，加密数据：{}", encrypted);

        HashMap<String, String> tokenMap = new HashMap<String, String>();
        tokenMap.put("token", encrypted);
        return tokenMap;
    }

    /**
     * 解密移动端 MBOS Token
     **/
    public static TokenParseResult decryptoMbosTokenMap(String token) throws Exception {
        TokenParseResult result = new TokenParseResult();

        try {
            if (StringUtils.isBlank(token)) {
                throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "移动端token为空！");
            }
            String dominoSecret = EncryptUtil.getProperty(LtpaTokenManager.DOMINO_SECRET);
            Map<String, Object> params = EncryptUtil.decryptToMap(token, dominoSecret);

            long expiredDate = (long) params.get("expiredDate");
            if (System.currentTimeMillis() > expiredDate) {
                throw new IntegrationException(CommonErrorCodes.SIGN_INVALID, "移动端token过期！");
            }
            //用户账号
            String userNumber = (String) params.get("userNumber");
            if (StringUtils.isBlank(userNumber)) {
                throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "移动端 用户账号为空！");
            }
            result.setStatus("0");
            result.setMessage(userNumber);
            logger.info("解密成功，账号为：{}", userNumber);
        } catch (Exception e) {
            logger.error("mbosToken解密失败");
            e.printStackTrace();
            result.setStatus("-1");
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * Token解析结果类
     */
    public static class TokenParseResult {
        private String status; // 0表示成功，-1表示异常
        private String message; // 成功时传递username，失败时传递失败信息

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}