package com.crm.rely.backend.util;

import com.google.common.base.Strings;

import java.util.Map;

/**
 * @program: cwg-my-base
 * @description:
 * @author: houn
 * @create: 2019-05-07 10:03
 */
public class PayFormUtil {

    public static final String METHOD_POST = "POST";
    public static final String METHOD_GET = "GET";

    private static final String fromFrame = "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
            "\n" +
            "<head runat=\"server\">\n" +
            "    <title></title>\n" +
            "</head>\n" +
            "\n" +
            "<body>\n" +
            "    <form action=\"%s\" id=\"payForm\" name=\"payForm\" method=\"%s\"\n" +
            "        runat=\"server\">\n" +
            "        %s\n" +
            "        <script type=\"text/javascript\">\n" +
            "            document.getElementById(\"payForm\").submit();\n" +
            "        </script>\n" +
            "    </form>\n" +
            "</body>\n" +
            "\n" +
            "</html>";
    private static final String formInput = " <input type=\"hidden\" name=\"%s\" id=\"%s\" runat=\"server\" " +
            "value=\"%s\" /> \n";

    public static String getForm(String url, Map<String, String> map) {

        return getForm(url, map, METHOD_POST);
    }

    public static String getForm(String url, Map<String, String> map, String method) {

        StringBuffer stringBuffer = new StringBuffer(map.size());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            stringBuffer.append(String.format(formInput, entry.getKey(), entry.getKey(), entry.getValue()));
        }
        String formString = getForm(url, stringBuffer.toString(), method);

        return formString;
    }

    public static String getForm(String url, String para, String method) {
        if (Strings.isNullOrEmpty(method)) {
            method = METHOD_POST;
        }

        String formString = String.format(fromFrame, url, method, para);
        return formString;
    }
}
