package com.zm.order.tool.server.cipher;

import net.sf.jsqlparser.JSQLParserException;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 加解密处理器公共模块
 *
 * <p>
 *
 * </p>
 *
 * @author nianchang
 * @date 2023/12/19 5:06 下午
 */
public abstract class AbstractEncryptionHandler {

    protected static Map<String, List<String>> ext = ExtEncryptFieldDefineConst.OrderEncryptField.EXT_ENCIPHER_DEFINE;

    protected static Map<String, List<String>> refundExt = ExtEncryptFieldDefineConst.RefundEncryptField.EXT_ENCIPHER_DEFINE;

    protected static List<String> perfList = ExtEncryptFieldDefineConst.OrderEncryptField.PERFORMANCE_INFO_LIST;

    /**
     * 多层级拆分
     *
     * <p>
     *
     * </p>
     *
     * @param extraMap features
     * @param key each key
     * @param value key : list {@link ExtEncryptFieldDefineConst --> extMap}
     * @param cipher cipher type to {@link CipherEnum}
     */
    @SuppressWarnings("unchecked")
    protected Map<String, Object> parseExt(Map<String, Object> extraMap, String key, List<String> value, final CipherEnum cipher) {
        Object obj = extraMap.get(key);
        if (obj != null) {
            // 一级key
            if (value == null || CollectionUtils.isEmpty(value)) {
                try {
                    extraMap.put(key, CipherEnum.execute(cipher, obj.toString()));
                } catch (JSQLParserException e) {
                    e.printStackTrace();
                }
            } else {
                // 二级key
                if (obj instanceof Map) {
                    Map<String, Object> subMap = (Map<String, Object>) obj;
                    extraMap.put(key, lastRank(value, subMap, cipher));
                }
            }
        }
        return extraMap;
    }

    /**
     * 最后层级下，单个key处理流程
     *
     * <p>
     *
     * </p>
     *
     * @param keyList key list to {@link ExtEncryptFieldDefineConst }
     * @param bottomMap target data
     * @param cipher cipher type to {@link CipherEnum}
     *
     * @return json data
     */
    protected Map<String, Object> lastRank(List<String> keyList, Map<String, Object> bottomMap, final CipherEnum cipher) {
        keyList.forEach(eachKey -> {
            Object obj = bottomMap.get(eachKey);
            if (!StringUtils.isEmpty(obj)) {
                try {
                    bottomMap.put(eachKey, CipherEnum.execute(cipher, obj.toString()));
                } catch (JSQLParserException e) {
                    e.printStackTrace();
                }
            }
        });
        return bottomMap;
    }

}
