package org.springblade.pay.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.pay.common.PayConst;
import org.springblade.pay.entity.OrderDto;
import org.springblade.pay.utils.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import javax.xml.xpath.XPathConstants;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
public class PayService {

	@Autowired
	private PayConst payConst;

	public static void main(String[] args) {
	}


	/**
	 * 智付下单
	 */
	public void payOrder(Map<String,Object> requestParams) {
		String res = HttpRequest.post(payConst.getPayUrl())
			.header("Content-Type","application/json")
			.body(JSON.toJSONString(requestParams))
			.execute().body();
		System.out.println(JSON.toJSONString(res));
		Document docResult= XmlUtil.readXML(res);
		Object value = XmlUtil.getByXPath("//dinpay/response/is_success", docResult, XPathConstants.STRING);
		System.out.println(value);
	}


	public Map<String,Object> getRequestParams(OrderDto orderDto){
		HashMap params = new HashMap() {
			{
				put("service_type", payConst.getServiceType());
				put("merchant_code", payConst.getMchId());
				put("interface_version", payConst.getInterfaceVersion());
				put("input_charset", payConst.getInputCharset());
				put("sign_type", payConst.getSignType());
				put("notify_url", payConst.getNotifyUrl());
				put("client_ip", orderDto.getClientIp());
				put("order_no", orderDto.getOrderNo());
				put("order_amount", orderDto.getOrderAmount());
				put("order_time", orderDto.getOrderTime());
				put("product_code", orderDto.getProductCode());
				put("product_num", orderDto.getProductNum());
				put("product_name", orderDto.getProductName());
				put("product_desc", orderDto.getProductDesc());
				put("second_merchant_id", payConst.getSecondMerchantId());
				put("user_id", orderDto.getOpenId());
			}
		};
		try {
			params.put("sign", RsaUtil.signByPrivateKey(params,payConst.getSecret()));
		} catch (Exception e) {
			log.error("参数签名错误：==》 "+e.getMessage());
		}
		return params;
	}

}
