package com.zt.plat.module.qms.core.util.qrcode;

import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.module.qms.resource.material.controller.vo.assist.QrCodeContent;

import java.util.Map;

public class QrCodeJsonUtil {

    @SafeVarargs
    public static String getQrCode(QrCodeContent qrCode,
                                   Func1<QrCodeContent, ?>... getters) {
        JSONObject json = JSONUtil.createObj();
        for (Func1<QrCodeContent, ?> getter : getters) {
            String methodName = LambdaUtil.getMethodName(getter);
            String fieldName = extractFieldName(methodName);
            Object value;
            try {
                value = getter.call(qrCode);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (value != null) {
                json.set(fieldName, value);
            }
        }
        return json.toString();
    }

    public static String getQrCode(Map<Func1<QrCodeContent, ?>, Object> fieldValueMap){
        JSONObject json = JSONUtil.createObj();
        for (Map.Entry<Func1<QrCodeContent, ?>, Object> entry : fieldValueMap.entrySet()) {
            Func1<QrCodeContent, ?> getter = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                String methodName = LambdaUtil.getMethodName(getter);
                String fieldName = extractFieldName(methodName);
                json.set(fieldName, value);
            }
        }
        return json.toString();
    }

    public static QrCodeContent parseQrCode(String json) {
        QrCodeContent content;
        try {
            content = JSONUtil.toBean(json, QrCodeContent.class);
        } catch (Exception e) {
            throw new ServiceException(1_032_160_000,"二维码解析失败");
        }
        return content;
    }

    private static String extractFieldName(String methodName) {
        if (methodName.startsWith("get")) {
            String prop = methodName.substring(3);
            return Character.toLowerCase(prop.charAt(0)) + prop.substring(1);
        }
        throw new UnsupportedOperationException("仅支持 getXxx 形式的 getter");
    }
}
