//package com.younike.api.service.impl;
//
//import com.thoughtworks.xstream.XStream;
//import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
//import com.thoughtworks.xstream.io.xml.XppDriver;
//import com.younike.api.service.WeChatPayService;
//import com.younike.common.bean.APIResult;
//import com.younike.common.constant.ResultPacketCode;
//import com.younike.common.id.IDGenerate;
//import com.younike.common.wxpay.pojo.WechatPay;
//import com.younike.common.wxpay.sdk.WXPayUtil;
//import com.younike.common.wxpay.service.WechatPayService;
//import com.younike.service.pojo.TOrder;
//import com.younike.service.service.ITOrderService;
//import lombok.extern.log4j.Log4j2;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.config.RegistryBuilder;
//import org.apache.http.conn.socket.ConnectionSocketFactory;
//import org.apache.http.conn.socket.PlainConnectionSocketFactory;
//import org.apache.http.conn.ssl.DefaultHostnameVerifier;
//import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
//import org.apache.http.util.EntityUtils;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.core.io.ClassPathResource;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import javax.net.ssl.KeyManagerFactory;
//import javax.net.ssl.SSLContext;
//import java.math.BigDecimal;
//import java.security.KeyStore;
//import java.security.SecureRandom;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author Another
// * @date 2022/3/22 15:51
// */
//@Log4j2
//@Service
//public class WeChatServiceImpl implements WeChatPayService {
//
//    @Resource
//    private WechatPayService payService;
//
//    @Value("${wechatpay.appid}")
//    private String appid;
//
//    @Value("${wechatpay.mchid}")
//    private String mchid;
//
//    @Value("${wechatpay.key}")
//    private String key;
//
//    @Value("${wechatpay.notify-url}")
//    private String notifyUrl;
//
//    @Value("${wechatpay.trade-type-jsapi}")
//    private String tradeTypeApp;
//
//    @Value("${wechatpay.body}")
//    private String body;
//
//    @Value("${wechatpay.choise}")
//    private int choise;
//
//    @Value("${wechatpay.refund-url}")
//    private String refundUrl;
//
//    @Value("${wechatpay.certpath}")
//    private String certpath;
//
//    @Resource
//    private ITOrderService orderService;
//
//    @Override
//    public String refund(String orderId) {
//        APIResult<Map> result = new APIResult<>();
//
//        //拼接统一查询下单地址参数
//        Map<String, String> paraMap = new HashMap<String, String>();
//        //获取请求ip地址
//        String nonceStr = WXPayUtil.generateNonceStr(); // 随机字符串
//        // 查询订单详情
//        TOrder order = orderService.getById(orderId);
//        // 退款单号
//        String refundId = IDGenerate.nextId();
////        // 付款金额
//        String priceFloat = "0";
//        if (0 == choise) {
//            // 测试接口
//            priceFloat = "1";
//        } else {
//            priceFloat = String.valueOf(order.getPayPrice().multiply(new BigDecimal(100)).intValue());
//        }
//        //paraMap 数组用于生成sign签名
//        paraMap.put("appid", appid); // 微信分配的公众账号ID
//        paraMap.put("mch_id", mchid); //微信支付分配的商户号
//        paraMap.put("out_trade_no", orderId); // 商户订单号
//        paraMap.put("out_refund_no", refundId); // 商户退款单号
//        paraMap.put("total_fee", priceFloat); // 订单金额
//        paraMap.put("refund_fee", priceFloat); // 申请退款金额
//        paraMap.put("nonce_str", nonceStr); //不重复随机数
//        String sign = null;  //商户key  sign签名
//        try {
//            sign = WXPayUtil.generateSignature(paraMap, key);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("退款失败:"+e);
//            return "退款失败";
//        }
//        paraMap.put("sign", sign);
//
//        // wechatPay对象转义为xml格式
//        WechatPay wechatPay = new WechatPay();
//        wechatPay.setAppid(appid);
//        wechatPay.setMch_id(mchid);
//        wechatPay.setOut_trade_no(orderId);
//        wechatPay.setOut_refund_no(refundId);
//        wechatPay.setTotal_fee(priceFloat);
//        wechatPay.setRefund_fee(priceFloat);
//        wechatPay.setNonce_str(nonceStr);
//        wechatPay.setSign(sign);
//
//        XStream xstream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));
//        xstream.alias("xml", WechatPay.class);
//        String xml = xstream.toXML(wechatPay);
//        try {
//            BasicHttpClientConnectionManager connManager;
//
//            /*----4.读取证书文件,这一段是直接从微信支付平台提供的demo中copy的，所以一般不需要修改---- */
//            // 证书
//            char[] password = mchid.toCharArray();
//            KeyStore ks = KeyStore.getInstance("PKCS12");
//            ClassPathResource cl = new ClassPathResource(certpath);
//            try {
//                ks.load(cl.getInputStream(), password);
//            } finally {
//
//            }
//
//            // 实例化密钥库 & 初始化密钥工厂
//            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            kmf.init(ks, password);
//
//            // 创建 SSLContext
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
//
//            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
//                    sslContext,
//                    new String[]{"TLSv1"},
//                    null,
//                    new DefaultHostnameVerifier());
//
//            connManager = new BasicHttpClientConnectionManager(
//                    RegistryBuilder.<ConnectionSocketFactory>create()
//                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
//                            .register("https", sslConnectionSocketFactory)
//                            .build(),
//                    null,
//                    null,
//                    null
//            );
//            HttpClient httpClient = HttpClientBuilder.create()
//                    .setConnectionManager(connManager)
//                    .build();
//
//            /*----5.发送数据到微信的退款接口---- */
//            HttpPost httpPost = new HttpPost(refundUrl);
//            httpPost.setEntity(new StringEntity(xml, "UTF-8"));
//            HttpResponse weixinResponse = httpClient.execute(httpPost);
//            String jsonStr = EntityUtils.toString(weixinResponse.getEntity(), "UTF-8");
//
//            //xml转Map
//            Map<String, String> resp = WXPayUtil.xmlToMap(jsonStr);
//
//            //以下内容是返回前端页面的数据
//            if ("SUCCESS".equals(resp.get("result_code"))) {
//                System.out.println("SUCCESS");
//                // 更新订单状态
//                if(!orderService.cancelOrder(orderId)){
//                    return "退款失败";
//                }else{
//                    return "退款成功";
//                }
//            }
//            //打印微信报错信息
//            log.error("----------wxrefund-result_code-----------" + resp.get("return_code"));
//            log.error("----------wxrefund-result--err_code---------" + resp.get("err_code"));
//            log.error("----------wxrefund-result--err_code_des---------" + resp.get("err_code_des"));
//            return "退款失败";
//        } catch (Exception e) {
//            //打印微信报错信息
//            log.error("----------wxrefund-error-----------" + e);
//            result.setMsg("退款失败");
//            result.setCode(ResultPacketCode.APIResultCode.Fail.getCode());
//            return "退款失败";
//        }
//    }
//}
