package com.izouma.nineth.dto.pay;

import com.anji.captcha.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.MapUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 统一通知请求
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UniformNotifyRequest {


    /**
     * 商户名称（可选）
     */
    private String merchant;

    /**
     * 对应数据库的订单号
     */
    private String orderNo;

    /**
     * 请求的内容头
     */
    private Map<String,String> requestHeaders;

    /**
     * 请求的参数
     */
    private Map<String,String> requestParams;

    /**
     * 请求的内容体
     */
    private String requestBody;

    /**
     * 预处理
     */
    private void initParameter(){
        //初始化参数
        if(requestParams == null){
            requestParams = new LinkedHashMap<>();
        }

        //自动解析参数
        if(requestParams.isEmpty() && StringUtils.isNotEmpty(requestBody)){
            String[] pairAry = requestBody.split("&");
            for(String pair : pairAry){
                String[] mp = pair.split("=");
                String value = mp.length > 1 ? mp[1] : "";
                try {
                    value = URLDecoder.decode(value, StandardCharsets.UTF_8.name());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                requestParams.put(mp[0], value);
            }
        }

    }

    /**
     * 获取参数
     * @return
     */
    public Map<String,String> getRequestParams(){
        initParameter();
        return requestParams;
    }

    /**
     * 获取参数
     * @param key
     * @return
     */
    public String getParameter(String key){
        initParameter();
        String value = requestParams.get(key);
        return value;
    }

    /**
     * 获取请求头
     * @param key
     * @return
     */
    public String getHeader(String key){
        String value = "";
        if(this.requestHeaders != null){
            //直接获取
            value = this.requestHeaders.get(key);
            //小写获取
            if(StringUtils.isEmpty(value)){
                String lowerCaseKey = key.toLowerCase(Locale.ROOT);
                value = this.requestHeaders.get(lowerCaseKey);
            }

        }

        return value;
    }


}
