package com.ruoyi.app.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.vo.PayResponse;
import com.ruoyi.system.domain.vo.PayVN;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class Md5Pay {
    public static final SimpleDateFormat ymdhms = new SimpleDateFormat("yyyyMMddHHmmss");

//    public JSONObject payMd5(String orderid,String amount,String customName){
//        try {
//            String merchantNo = "API8918130442359667";
//            String merchant_private_key = "6d75bb6318944312b7456193ce776a6f";
//            String signType = "MD5";
//            String url = "https://mgp-pay.com:8443/api/pay/V2";
//
//            Map<String, String> requestMap = new HashMap<String, String>();
//            requestMap.put("merchantNo", merchantNo);
//            requestMap.put("channleType", "1");
//            requestMap.put("signType", signType);
//            requestMap.put("version", "V2");// 常量V1
//            requestMap.put("date", ymdhms.format(new Date()));
//            requestMap.put("orderNo", orderid);// System.currentTimeMillis()
//            requestMap.put("bizAmt", amount); // 元
//            requestMap.put("customName", customName); // 元
//            requestMap.put("noticeUrl", "http://203.175.169.46:8080/pay/payJson");
//            String signStr = SftSignUtil.formatSignData(requestMap);
//            System.out.println("signStr签名：" + signStr);
//            String sign = SftSignUtil.sign(signType, signStr, merchant_private_key);
//            requestMap.put("sign", sign);
//            System.out.println("sign  "+sign);
//            Map<String, String> head = new HashMap<String, String>();
//            head.put("Content-Type", "application/json");
//            String rs = HttpKit.post(url, JSON.toJSONString(requestMap), head);
//            JSONObject jsonObject = JSONObject.parseObject(rs);
//            return  jsonObject;
//        } catch (Exception e) {
//            JSONObject json = new JSONObject();
//            json.put("data",null);
//            return json;
//        }
//    }

    //发起支付
    @SneakyThrows
    public String VNPay(String language, String orderid, String amount,String ip){
        String vnp_Version = "2.1.0";
        String vnp_Command = "pay";
        String orderType = "other";
        String bankCode = "";
        long pamount = Long.valueOf(amount)*100;

        String vnp_TxnRef = VNPay.getRandomNumber(8);
        String vnp_IpAddr = ip;

        String vnp_TmnCode = VNPay.vnp_TmnCode;

        Map<String, String> vnp_Params = new HashMap<>();
        vnp_Params.put("vnp_Version", vnp_Version);
        vnp_Params.put("vnp_Command", vnp_Command);
        vnp_Params.put("vnp_TmnCode", vnp_TmnCode);
        vnp_Params.put("vnp_Amount", String.valueOf(pamount));
        vnp_Params.put("vnp_CurrCode", "VND");

        if (bankCode != null && !bankCode.isEmpty()) {
            vnp_Params.put("vnp_BankCode", bankCode);
        }
        vnp_Params.put("vnp_TxnRef", orderid);
        vnp_Params.put("vnp_OrderInfo", orderid);
        vnp_Params.put("vnp_OrderType", orderType);

        String locate = language;
        if (locate != null && !locate.isEmpty()) {
            vnp_Params.put("vnp_Locale", locate);
        } else {
            vnp_Params.put("vnp_Locale", "vn");
        }
        vnp_Params.put("vnp_ReturnUrl", VNPay.vnp_ReturnUrl);
        vnp_Params.put("vnp_IpAddr", vnp_IpAddr);

        Calendar cld = Calendar.getInstance(TimeZone.getTimeZone("Etc/GMT+7"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String vnp_CreateDate = formatter.format(cld.getTime());
        vnp_Params.put("vnp_CreateDate", vnp_CreateDate);

        cld.add(Calendar.MINUTE, 15);
        String vnp_ExpireDate = formatter.format(cld.getTime());
        vnp_Params.put("vnp_ExpireDate", vnp_ExpireDate);

        List fieldNames = new ArrayList(vnp_Params.keySet());
        Collections.sort(fieldNames);
        StringBuilder hashData = new StringBuilder();
        StringBuilder query = new StringBuilder();
        Iterator itr = fieldNames.iterator();
        while (itr.hasNext()) {
            String fieldName = (String) itr.next();
            String fieldValue = (String) vnp_Params.get(fieldName);
            if ((fieldValue != null) && (fieldValue.length() > 0)) {
                //Build hash data
                hashData.append(fieldName);
                hashData.append('=');
                hashData.append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII.toString()));
                //Build query
                query.append(URLEncoder.encode(fieldName, StandardCharsets.US_ASCII.toString()));
                query.append('=');
                query.append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII.toString()));
                if (itr.hasNext()) {
                    query.append('&');
                    hashData.append('&');
                }
            }
        }
        String queryUrl = query.toString();
        String vnp_SecureHash = VNPay.hmacSHA512(VNPay.secretKey, hashData.toString());
        queryUrl += "&vnp_SecureHash=" + vnp_SecureHash;
        String paymentUrl = VNPay.vnp_PayUrl + "?" + queryUrl;

        return paymentUrl;
    }
    //查询支付订单
    public String getPay(PayResponse payResponse,String  ip) throws IOException {
        //Command:querydr

        String vnp_RequestId = VNPay.getRandomNumber(8);
        String vnp_Version = "2.1.0";
        String vnp_Command = "querydr";
        String vnp_TmnCode = VNPay.vnp_TmnCode;
        String vnp_TxnRef = payResponse.getOrder_id();
        String vnp_OrderInfo =  vnp_TxnRef;;
        //String vnp_TransactionNo = req.getParameter("transactionNo");
        String vnp_TransDate = payResponse.getTrans_date();

        Calendar cld = Calendar.getInstance(TimeZone.getTimeZone("Etc/GMT+7"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String vnp_CreateDate = formatter.format(cld.getTime());

        String vnp_IpAddr = ip;

        JSONObject  vnp_Params = new JSONObject();

        vnp_Params.put("vnp_RequestId", vnp_RequestId);
        vnp_Params.put("vnp_Version", vnp_Version);
        vnp_Params.put("vnp_Command", vnp_Command);
        vnp_Params.put("vnp_TmnCode", vnp_TmnCode);
        vnp_Params.put("vnp_TxnRef", vnp_TxnRef);
        vnp_Params.put("vnp_OrderInfo", vnp_OrderInfo);
        //vnp_Params.put("vnp_TransactionNo", vnp_TransactionNo);
        vnp_Params.put("vnp_TransactionDate", vnp_TransDate);
        vnp_Params.put("vnp_CreateDate", vnp_CreateDate);
        vnp_Params.put("vnp_IpAddr", vnp_IpAddr);

        String hash_Data= String.join("|", vnp_RequestId, vnp_Version, vnp_Command, vnp_TmnCode, vnp_TxnRef, vnp_TransDate, vnp_CreateDate, vnp_IpAddr, vnp_OrderInfo);
        String vnp_SecureHash = VNPay.hmacSHA512(VNPay.secretKey, hash_Data.toString());

        vnp_Params.put("vnp_SecureHash", vnp_SecureHash);

        URL url = new URL (VNPay.vnp_ApiUrl);
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(vnp_Params.toString());
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        System.out.println("nSending 'POST' request to URL : " + url);
        System.out.println("Post Data : " + vnp_Params);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String output;
        StringBuffer response = new StringBuffer();
        while ((output = in.readLine()) != null) {
            response.append(output);
        }
        in.close();
        System.out.println(response.toString());
        return response.toString();
    }

   //退款
   public String doPost(PayVN payVN) throws IOException {

        //Command: refund
        String vnp_RequestId = VNPay.getRandomNumber(8);
        String vnp_Version = "2.1.0";
        String vnp_Command = "refund";
        String vnp_TmnCode = VNPay.vnp_TmnCode;
        String vnp_TransactionType = payVN.getTrantype();
        String vnp_TxnRef =  payVN.getOrder_id();
        long amount = Integer.parseInt(payVN.getAmount())*100;
        String vnp_Amount = String.valueOf(amount);
        String vnp_OrderInfo = vnp_TxnRef;
        String vnp_TransactionNo = payVN.getTransaction(); //不存在则为空。
        String vnp_TransactionDate = payVN.getTrans_date();
        String vnp_CreateBy = payVN.getUser();

        Calendar cld = Calendar.getInstance(TimeZone.getTimeZone("Etc/GMT+7"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String vnp_CreateDate = formatter.format(cld.getTime());

        String vnp_IpAddr = payVN.getIpaddr();

        JSONObject  vnp_Params = new JSONObject ();

        vnp_Params.put("vnp_RequestId", vnp_RequestId);
        vnp_Params.put("vnp_Version", vnp_Version);
        vnp_Params.put("vnp_Command", vnp_Command);
        vnp_Params.put("vnp_TmnCode", vnp_TmnCode);
        vnp_Params.put("vnp_TransactionType", vnp_TransactionType);
        vnp_Params.put("vnp_TxnRef", vnp_TxnRef);
        vnp_Params.put("vnp_Amount", vnp_Amount);
        vnp_Params.put("vnp_OrderInfo", vnp_OrderInfo);

        if(vnp_TransactionNo != null && !vnp_TransactionNo.isEmpty())
        {
            vnp_Params.put("vnp_TransactionNo", payVN.getTransaction());
        }

        vnp_Params.put("vnp_TransactionDate", vnp_TransactionDate);
        vnp_Params.put("vnp_CreateBy", vnp_CreateBy);
        vnp_Params.put("vnp_CreateDate", vnp_CreateDate);
        vnp_Params.put("vnp_IpAddr", vnp_IpAddr);

        String hash_Data= String.join("|", vnp_RequestId, vnp_Version, vnp_Command, vnp_TmnCode,
                vnp_TransactionType, vnp_TxnRef, vnp_Amount, vnp_TransactionNo, vnp_TransactionDate,
                vnp_CreateBy, vnp_CreateDate, vnp_IpAddr, vnp_OrderInfo);

        String vnp_SecureHash = VNPay.hmacSHA512(VNPay.secretKey, hash_Data.toString());

        vnp_Params.put("vnp_SecureHash", vnp_SecureHash);

        URL url = new URL (VNPay.vnp_ApiUrl);
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(vnp_Params.toString());
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        System.out.println("nSending 'POST' request to URL : " + url);
        System.out.println("Post Data : " + vnp_Params);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String output;
        StringBuffer response = new StringBuffer();
        while ((output = in.readLine()) != null) {
            response.append(output);
        }
        in.close();
        System.out.println(response.toString());
        return response.toString();
    }
}
