package com.hai.service.pay.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.WxUtils;
import com.hai.config.*;
import com.hai.dao.HighCouponCodeOtherMapper;
import com.hai.dao.HighDiscountPackageRecordMapper;
import com.hai.dao.HighGasOrderPushMapper;
import com.hai.dao.HighUserCouponMapper;
import com.hai.entity.*;
import com.hai.enum_type.*;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.ResultProfitSharing;
import com.hai.msg.entity.MsgTopic;
import com.hai.service.*;
import com.hai.service.pay.NotifyService;
import com.hai.service.pay.PayService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/27 00:35
 */
@Service("goodsOrderService")
public class GoodsOrderServiceImpl implements PayService {

    private static Logger log = LoggerFactory.getLogger(GoodsOrderServiceImpl.class);

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighOrderPreService highOrderPreService;

    @Resource
    private HighGasOrderPushMapper highGasOrderPushMapper;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighUserCouponMapper highUserCouponMapper;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private HighProfitSharingRecordService highProfitSharingRecordService;

    @Resource
    private HighCouponCodeOtherMapper highCouponCodeOtherMapper;

    @Resource
    private HighActivityInfoService highActivityInfoService;

    @Resource
    private HighActivityUserLotteryNumService highActivityUserLotteryNumService;

    @Resource
    private HighDiscountPackageDiscountActualService discountPackageDiscountActualService;

    @Resource
    private HighDiscountPackageActualService discountPackageActualService;

    @Resource
    private HighDiscountPackageService discountPackageService;

    @Resource
    private HighDiscountPackageRecordService discountPackageRecordService;

    @Resource
    private HighDiscountUserRelService highDiscountUserRelService;

    @Resource
    private NotifyService notifyService;

    @Resource
    private HuiLianTongConfig huiLianTongConfig;

    @Resource
    private HighMerchantStoreAccountService merchantStoreAccountService;

    @Resource
    private BaiduVoiceService baiduVoiceService;

    @Resource
    private HighGasChannelConfigService gasChannelConfigService;

    @Resource
    private ShellGroupService shellGroupService;

    @Resource
    private JinZhuJiaYouService jinZhuJiaYouService;

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void paySuccess(Map<String, String> map, String payType) throws Exception {
        if (payType.equals("Alipay")) {
            // 支付宝支付 todo 暂未开发
            return;
        }
        if (payType.equals("WechatPay")) {
            // 查询订单信息
            HighOrder order = highOrderService.getOrderByOrderNo(map.get("out_trade_no"));
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
            }

            // 查询用户
            HighUser highUser = highUserService.findByUserId(order.getMemId());

            if (order.getOrderStatus() == 1) {
                order.setPaySerialNo(map.get("transaction_id")); // 支付流水号
                order.setPayRealPrice(new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100"))); // 实付金额
                order.setPayTime(new Date()); // 支付时间
                order.setPayModel(2);         // 支付模式：1 金币，2 第三方平台，3 混合
                order.setPayType(2);          // 支付方式： 1：支付宝  2：微信  3：金币
                order.setOrderStatus(2);      // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

                for (HighChildOrder highChildOrder : order.getHighChildOrderList()) {
                    // 商品类型   商品类型   1:卡卷   2:金币充值
                    if (highChildOrder.getGoodsType() == 1) {
                        highChildOrder.setChildOrdeStatus(2);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

                        HighCoupon coupon = highCouponService.getCouponById(highChildOrder.getGoodsId());
                        // 是否预约
                        if (coupon.getReserveStatus()) {
                            HighOrderPre orderPre = new HighOrderPre();
                            orderPre.setCompanyId(coupon.getCompanyId());
                            orderPre.setMerchantId(coupon.getMerchantId());
                            orderPre.setMerchantStoreId(highChildOrder.getStoreId());
                            orderPre.setPreOrderNo(System.currentTimeMillis()+"");
                            orderPre.setOrderId(order.getId());
                            orderPre.setOrderNo(order.getOrderNo());
                            orderPre.setChildOrderId(highChildOrder.getId());
                            orderPre.setPayRealPrice(order.getPayRealPrice());
                            orderPre.setGoodsType(1);
                            orderPre.setGoodsName(coupon.getCouponName());
                            orderPre.setGoodsId(coupon.getId());
                            orderPre.setPreUserId(order.getMemId());
                            orderPre.setPreUserName(order.getMemName());
                            orderPre.setPreUserPhone(order.getMemPhone());
                            orderPre.setPreUserRemark(order.getRemarks());
                            orderPre.setStatus(1);
                            highOrderPreService.insertOrderPre(orderPre);
                        }
                        // 贵州中石化
                        if (coupon.getCouponSource() == 4) {
                            Map<String,Object> push = new HashMap<>();
                            push.put("couTypeCode", coupon.getCouponKey());
                            push.put("distCouCount", highChildOrder.getSaleCount());
                            push.put("userPhone", highUser.getPhone());
                            push.put("thirdUserId", highUser.getUnionId());

                            // 推送给高速
                            JSONObject returnParam = HuiLianTongConfig.costRechargeOrder(highChildOrder.getExt2());
                            System.out.println(returnParam);
                            // 推送记录
                            HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                            highGasOrderPush.setType(OrderPushType.type6.getType());
                            highGasOrderPush.setOrderNo(order.getOrderNo());
                            highGasOrderPush.setCreateTime(new Date());
                            highGasOrderPush.setCode(returnParam.getString("result"));
                            highGasOrderPush.setRequestContent(JSONObject.toJSONString(push));
                            highGasOrderPush.setReturnContent(returnParam.toJSONString());
                            highGasOrderPushMapper.insert(highGasOrderPush);

                            if (returnParam != null && returnParam.getString("respCode").equals("0000")) {
                                // 解密
                                JSONObject jsonObject = HuiLianTongUnionCardConfig.resolveResponse(returnParam.getString("data"));
                                JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);
                                for (Object data : dataArray) {
                                    JSONObject dataObject = (JSONObject) data;
                                    HighCouponCodeOther couponCodeOther = new HighCouponCodeOther();
                                    couponCodeOther.setType(1);
                                    couponCodeOther.setOrderId(order.getId());
                                    couponCodeOther.setChildOrderId(highChildOrder.getId());
                                    couponCodeOther.setCouTypeCode(dataObject.getString("couTypeCode"));
                                    couponCodeOther.setCouNo(dataObject.getString("couNo"));
                                    couponCodeOther.setActiveTime(dataObject.getDate("activeTime"));
                                    couponCodeOther.setValidStartDate(dataObject.getDate("validStartDate"));
                                    couponCodeOther.setValidEndDate(dataObject.getDate("validEndDate"));
                                    couponCodeOther.setStatus(20);
                                    couponCodeOther.setCreateTime(new Date());
                                    highCouponCodeOtherMapper.insert(couponCodeOther);

                                    // 卡卷关联用户
                                    HighUserCoupon highUserCoupon = new HighUserCoupon();
                                    highUserCoupon.setMerchantId(coupon.getMerchantId());
                                    highUserCoupon.setCouponId(coupon.getId());
                                    highUserCoupon.setUserId(order.getMemId());
                                    highUserCoupon.setCreateTime(new Date());
                                    highUserCoupon.setQrCodeImg(dataObject.getString("couNo"));
                                    highUserCoupon.setUseEndTime(dataObject.getDate("validEndDate"));
                                    highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                                    highUserCouponMapper.insert(highUserCoupon);
                                }
                            }



                        } else {
                            HighCouponCode code = highCouponCodeService.getCouponCodeByOrderId(highChildOrder.getId());
                            code.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                            code.setReceiveTime(new Date());
                            highCouponCodeService.updateCouponCode(code);
                            // 卡卷关联用户
                            HighUserCoupon highUserCoupon = new HighUserCoupon();
                            highUserCoupon.setMerchantId(code.getMerchantId());
                            highUserCoupon.setCouponId(code.getCouponId());
                            highUserCoupon.setUserId(order.getMemId());
                            highUserCoupon.setCouponCodeId(code.getId());
                            highUserCoupon.setCreateTime(new Date());
                            highUserCoupon.setQrCodeImg(code.getExt1());

                            // 计算使用有效期
                            Calendar userEndTime = Calendar.getInstance();
                            userEndTime.setTime(new Date());
                            userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                            userEndTime.set(Calendar.MINUTE, 59);
                            userEndTime.set(Calendar.SECOND, 59);
                            userEndTime.add(Calendar.DATE, coupon.getRecycleDay());
                            if (userEndTime.getTime().compareTo(code.getUseEndTime()) == 1) {
                                highUserCoupon.setUseEndTime(code.getUseEndTime());
                            } else {
                                highUserCoupon.setUseEndTime(userEndTime.getTime());
                            }
                            highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                            highUserCouponMapper.insert(highUserCoupon);
                        }

                        // 查询卡券是否有活动
                        Map<String, Object> activity = highActivityInfoService.getNewActivityByCouponId(coupon.getId());
                        if (activity != null && MapUtils.getLong(activity, "id") != null) {
                            highActivityUserLotteryNumService.addLotteryNum(MapUtils.getLong(activity, "id"),order.getMemId(), 1);
                        }
                    }

                    if (highChildOrder.getGoodsType() == 2) {
                        highChildOrder.setChildOrdeStatus(3);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                        order.setFinishTime(new Date());
                        order.setOrderStatus(3);      // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                        // 金币 1：100
                        Integer goldNum = new BigDecimal(highChildOrder.getTotalPrice().toString()).multiply(new BigDecimal("100")).intValue();
                        String remark = "订单" + order.getOrderNo() + "积分充值积分：" +  goldNum;
                        highUserService.goldHandle(highChildOrder.getGoodsId(), goldNum, 1, 1, highChildOrder.getId() , remark);
                    }

                    if (highChildOrder.getGoodsType() == 3) {
                        highChildOrder.setChildOrdeStatus(3);
                        order.setOrderStatus(3);
                        HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highChildOrder.getGoodsId());

                        // 来源类型  1：平台自建   2：团油
                        if (store.getSourceType().equals(1)) {

                            // 预存类型  0：非预存  1：预存门店
                            if (store.getPrestoreType() != null && store.getPrestoreType().equals(1)) {
                                Map<String, Object> pushParam = new HashMap<>();
                                pushParam.put("businessType", MerStoreAmountTypeEnum.type2.getType());
                                pushParam.put("storeId", highChildOrder.getGoodsId());
                                pushParam.put("price", order.getTotalPrice());
                                pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type2.getType());
                                pushParam.put("sourceId", order.getId());
                                pushParam.put("sourceContent", "订单号：" + order.getOrderNo() + ",加油金额：￥" + order.getTotalPrice());
                                pushParam.put("opUserId", order.getMemId());
                                pushParam.put("opUserName", order.getMemName());
                                // 扣预存款
                                this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);
                            }
                        } else if (store.getSourceType().equals(2)) {
                            // 推送团油订单
                            Map<String,Object> paramMap = new HashMap<>();
                            paramMap.put("gasId", store.getStoreKey());
                            paramMap.put("oilNo", highChildOrder.getGasOilNo());
                            paramMap.put("gunNo", highChildOrder.getGasGunNo());
                            BigDecimal priceGun = highChildOrder.getGasPriceGun();
                            BigDecimal priceVip = highChildOrder.getGasPriceVip();
                            paramMap.put("priceGun", priceGun);  // 枪单价
                            paramMap.put("priceVip", priceVip);  // 优惠价
                            paramMap.put("driverPhone", order.getMemPhone());
                            paramMap.put("thirdSerialNo", order.getOrderNo());
                            paramMap.put("refuelingAmount", highChildOrder.getTotalPrice());

                            // 油品类型 1:汽油:2:柴油;3:天然气
                            if (highChildOrder.getGasOilType() == 1) {
                                paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouGasolineAccount());
                            } else if (highChildOrder.getGasOilType() == 2) {
                                paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouDieselAccount());
                            }
                            JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(paramMap);
                            // 推送团油订单记录
                            HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                            highGasOrderPush.setType(OrderPushType.type1.getType());
                            highGasOrderPush.setOrderNo(order.getOrderNo());
                            highGasOrderPush.setCreateTime(new Date());
                            highGasOrderPush.setCode(orderPushObject.getString("code"));
                            highGasOrderPush.setRequestContent(JSONObject.toJSONString(paramMap));
                            highGasOrderPush.setReturnContent(orderPushObject.toJSONString());
                            highGasOrderPushMapper.insert(highGasOrderPush);

                            if (orderPushObject != null && orderPushObject.getString("code").equals("200")) {
                                highChildOrder.setGasOrderNo(orderPushObject.getJSONObject("result").getString("orderNo"));
                            }
                        } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {

                            // 推送加好油
                            shellGroupService.gasSyncPayment(order.getOrderNo(),
                                    store.getStoreKey(),
                                    order.getPayTime(),
                                    highChildOrder.getTotalPrice(),
                                    highChildOrder.getGasOilNo(),
                                    highChildOrder.getGasGunNo(),
                                    order.getPayablePrice(),
                                    order.getDeductionPrice()
                            );
                        } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                            // 推送金猪加油
                            jinZhuJiaYouService.payOrder(order.getOrderNo(), highChildOrder.getGasPriceChannelPay());
                        }
                    }

                    if (highChildOrder.getGoodsType() == 7) {
                        HighDiscountPackageActual actual = discountPackageActualService.getDetailByChildOrderId(highChildOrder.getId());
                        if (actual != null) {
                            List<HighDiscountPackageDiscountActual> discountList = discountPackageDiscountActualService.getHighDiscountPackageDiscountActualList(actual.getId());
                            for (HighDiscountPackageDiscountActual discount : discountList) {
                                highDiscountUserRelService.receiveDiscount(order.getMemId(), discount.getAgentDiscountCodeId());
                            }
                            HighDiscountPackage discountPackage = discountPackageService.findDiscountPackageById(actual.getDiscountPackageId());
                            HighDiscountPackageRecord record = new HighDiscountPackageRecord();
                            record.setDiscountPackageId(discountPackage.getId());
                            record.setDiscountPackageTitle(discountPackage.getTitle());
                            record.setUsingAttribution(discountPackage.getUsingAttribution());
                            record.setCompanyId(discountPackage.getCompanyId());
                            record.setOrderId(order.getId().intValue());
                            record.setChildOrderId(highChildOrder.getId().intValue());
                            record.setRecordNo(System.currentTimeMillis()+"");
                            record.setSalesType(1);
                            record.setPrice(order.getPayPrice());
                            record.setUserId(order.getMemId().intValue());
                            discountPackageRecordService.insertRecord(record);
                            actual.setAllocationTime(new Date());
                            actual.setStatus(3);  // 状态： 1: 待分配 2:预分配（售卖）3:已分配
                            discountPackageActualService.updateHighDiscountPackageActual(actual);
                        }
                    }

                    if (highChildOrder.getGoodsType() == 8) {
                        // 汇联通充值
                        String goodsDesc = "汇联通充值"+order.getPayPrice()+"元";
                        String tranDesc = "";
                        String businessType = "ghk_deposit";

                        // 汇联通卡充值
                        JSONObject deposit = HuiLianTongUnionCardConfig.deposit(order.getOrderNo(), order.getMemCardNo(), order.getPayPrice(), businessType, map.get("transaction_id"), tranDesc);
                        System.out.println("工会卡支付响应参数" + deposit.toJSONString());

                        JSONObject dataObject = HuiLianTongUnionCardConfig.resolveResponse(deposit.getString("data"));

                        Map<String,Object> dataMap = new HashMap<>();
                        dataMap.put("orderNo", order.getOrderNo());
                        dataMap.put("cardType", "ghk");
                        dataMap.put("cardNo", order.getMemCardNo());
                        dataMap.put("checkPassword", "N");
                        dataMap.put("tranAmount", order.getPayPrice());
                        dataMap.put("tranChannel", "HiSen");
                        dataMap.put("businessType", businessType);
                        dataMap.put("goodsDesc", goodsDesc);
                        dataMap.put("tranDesc", tranDesc);
                        HighGasOrderPush payPush = new HighGasOrderPush();
                        payPush.setType(OrderPushType.type7.getType());
                        payPush.setOrderNo(order.getOrderNo());
                        payPush.setCreateTime(new Date());
                        payPush.setCode(deposit.getString("respCode"));
                        payPush.setRequestContent(JSON.toJSONString(dataMap));
                        payPush.setReturnContent(deposit.toJSONString());
                        highGasOrderPushMapper.insert(payPush);

                        if (!Objects.equals(deposit.getString("respCode"), "0000")) {
                            throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , deposit.getString("respMessage"));
                        }
                        // 记录回调信息
                        if (!dataObject.getBoolean("success")) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, dataObject.getString("message"));
                        }

                        // 修改订单状态
                        highChildOrder.setChildOrdeStatus(3);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                        order.setFinishTime(new Date());
                        order.setOrderStatus(3);      // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                    }
                }

                highOrderService.updateOrder(order);


                if (order.getHighChildOrderList().get(0).getGoodsType().equals(3)) {
                    new Thread(() -> {
                        try {
                            // 加油站
                            HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(order.getHighChildOrderList().get(0).getGoodsId());
                            if (store != null) {
                                if (store.getSourceType() != null && store.getSourceType().equals(1)) {
                                    new Thread(() -> {
                                        Map<String, Object> pushMsg = new HashMap<>();
                                        pushMsg.put("userId", order.getHighChildOrderList().get(0).getGoodsId());

                                        Map<String, Object> msgContent = new HashMap<>();
                                        msgContent.put("order", highOrderService.getGasOrderDetail(order.getOrderNo()));
                                        msgContent.put("voice", baiduVoiceService.text2audio(order.getHighChildOrderList().get(0).getGoodsName() + "，收款：" + order.getTotalPrice() + "元"));
                                        pushMsg.put("message", JSONObject.toJSONString(msgContent));
                                        HttpsUtils.doPost("http://127.0.0.1:9901/msg/websocket/websocket", pushMsg, new HashMap<>());
                                    }).start();
                                }
                            }
                            highOrderService.printGasOrder(order.getHighChildOrderList().get(0).getGoodsId(), order, false);
                        } catch (Exception e) {

                        }
                    }).start();

                    if (order.getProfitSharingStatus() == true) {
                        new Thread(() -> {
                            try {
                                Thread.sleep(120*1000);

                                HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(order.getHighChildOrderList().get(0).getGoodsId());
                                if (store != null) {
                                    HighGasChannelConfig gasChannelConfig;

                                    if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())) {
                                        gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type1,GasChannelPayPlatformType.type1 );

                                    } else if (store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber())) {
                                        gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type2,GasChannelPayPlatformType.type1 );

                                    } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {
                                        gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type3,GasChannelPayPlatformType.type1 );

                                    } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                                        gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type4,GasChannelPayPlatformType.type1 );

                                    } else {
                                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置分账参数");
                                    }

                                    BigDecimal rake = order.getProfitSharingRatio().divide(new BigDecimal("100"));

                                    // 计算微信收取的手续费     支付金额 * 0.002      注：如果与两个相邻数字的距离相等，则为上舍入的舍入模式。
                                    BigDecimal wxHandlingFee = order.getPayRealPrice().multiply(new BigDecimal("0.002")).setScale(2,BigDecimal.ROUND_HALF_DOWN);
                                    BigDecimal price = order.getPayRealPrice().subtract(wxHandlingFee);

                                    // 计算分账金额    手续费后的价格 * 0.05  注：如果与两个相邻数字的距离相等，则为上舍入的舍入模式。
                                    BigDecimal profitSharingAmount = price.multiply(rake).setScale(2,BigDecimal.ROUND_DOWN);
                                    this.wxGasProfitsharing(order.getExt1(), order.getAccountMerchantNum(),gasChannelConfig.getProfitSharingReceiversNo(), gasChannelConfig.getProfitSharingReceiversName(), order.getPaySerialNo(),order.getOrderNo(),profitSharingAmount);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                } else {
                    new Thread(() -> {
                        try {
                            Thread.sleep(120*1000);
                            BigDecimal rake = new BigDecimal("0.01");

                            // 计算微信收取的手续费     支付金额 * 0.002      注：如果与两个相邻数字的距离相等，则为上舍入的舍入模式。
                            BigDecimal wxHandlingFee = order.getPayRealPrice().multiply(new BigDecimal("0.002")).setScale(2,BigDecimal.ROUND_HALF_DOWN);
                            BigDecimal price = order.getPayRealPrice().subtract(wxHandlingFee);

                            // 计算分账金额    手续费后的价格 * 0.01  注：如果与两个相邻数字的距离相等，则为上舍入的舍入模式。
                            BigDecimal profitSharingAmount = price.multiply(rake).setScale(2,BigDecimal.ROUND_DOWN);
                            this.wxProfitsharing(order.getExt1(), order.getPaySerialNo(),order.getOrderNo(),profitSharingAmount);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
            }
        }
    }


    public void wxGasProfitsharing(String appid, String subMchId, String receiversAccount, String receiversAccountName,String transaction_id,String out_order_no, BigDecimal amount) {
        try {
            Map<String,String> param = new LinkedHashMap<>();
            param.put("appid", appid);
            param.put("mch_id", "1289663601");
            param.put("sub_mch_id" , subMchId);
            param.put("transaction_id" , transaction_id);
            param.put("out_order_no" , out_order_no);
            param.put("nonce_str" , WxUtils.makeNonStr());

            // 分账金额
            BigDecimal porofitSharingAmount = amount;

            List<Map<String,Object>> receiversList = new ArrayList<>();
            Map<String,Object> receiversMap = new LinkedHashMap<>();
            receiversMap.put("type", "MERCHANT_ID");
            receiversMap.put("account", receiversAccount);
            receiversMap.put("amount", porofitSharingAmount.multiply(new BigDecimal("100")).intValue());
            receiversMap.put("description", "分给商户：" + receiversAccountName);
            receiversList.add(receiversMap);
            param.put("receivers" , JSONObject.toJSONString(receiversList));
            String signStr = WxUtils.generateSignature(param, "Skufk5oi85wDFGl888i6wsRSTkdd5df5" , WXPayConstants.SignType.HMACSHA256);
            param.put("sign" , signStr);
            String resultXmL = this.doRefundRequest(param.get("mch_id"),null, WxUtils.mapToXml(param));

            // 请求分账返回的结果
            ResultProfitSharing resultProfitSharing = XmlUtil.getObjectFromXML(resultXmL, ResultProfitSharing.class);

            HighProfitSharingRecord sharingRecord = new HighProfitSharingRecord();
            sharingRecord.setOutOrderNo(out_order_no);
            sharingRecord.setTransactionId(transaction_id);
            sharingRecord.setOrderId(resultProfitSharing.getOrder_id());
            sharingRecord.setStatus(resultProfitSharing.getResult_code());
            sharingRecord.setPrice(amount);
            sharingRecord.setCreateTime(new Date());
            sharingRecord.setContent(resultXmL);
            highProfitSharingRecordService.insert(sharingRecord);

        } catch (Exception e) {
            log.error("CmsContentController --> getCorporateAdvertising() error!", e);
        }
    }

    public void wxProfitsharing(String appid,String transaction_id,String out_order_no, BigDecimal amount) {
        try {
            Map<String,String> param = new LinkedHashMap<>();
            param.put("appid", appid);
            param.put("mch_id", "1289663601");
            param.put("sub_mch_id" , "1609882817"); // 个体户黎杨珍
            param.put("transaction_id" , transaction_id);
            param.put("out_order_no" , out_order_no);
            param.put("nonce_str" , WxUtils.makeNonStr());

            // 分账金额
            BigDecimal porofitSharingAmount = amount;

            List<Map<String,Object>> receiversList = new ArrayList<>();
            Map<String,Object> receiversMap = new LinkedHashMap<>();
            receiversMap.put("type", "MERCHANT_ID");
            receiversMap.put("account", "1603942866");
            receiversMap.put("amount", porofitSharingAmount.multiply(new BigDecimal("100")).intValue());
            receiversMap.put("description", "分给商户【惠昕石化】");
            receiversList.add(receiversMap);
            param.put("receivers" , JSONObject.toJSONString(receiversList));
            String signStr = WxUtils.generateSignature(param, "Skufk5oi85wDFGl888i6wsRSTkdd5df5" , WXPayConstants.SignType.HMACSHA256);
            param.put("sign" , signStr);
            String resultXmL = this.doRefundRequest(param.get("mch_id"),null, WxUtils.mapToXml(param));

            // 请求分账返回的结果
            ResultProfitSharing resultProfitSharing = XmlUtil.getObjectFromXML(resultXmL, ResultProfitSharing.class);

            HighProfitSharingRecord sharingRecord = new HighProfitSharingRecord();
            sharingRecord.setOutOrderNo(out_order_no);
            sharingRecord.setTransactionId(transaction_id);
            sharingRecord.setOrderId(resultProfitSharing.getOrder_id());
            sharingRecord.setStatus(resultProfitSharing.getResult_code());
            sharingRecord.setPrice(amount);
            sharingRecord.setCreateTime(new Date());
            sharingRecord.setContent(resultXmL);
            highProfitSharingRecordService.insert(sharingRecord);

        } catch (Exception e) {
            log.error("CmsContentController --> getCorporateAdvertising() error!", e);
        }
    }

    public CloseableHttpClient readCertificate(String mchId) throws Exception{
        /**
         * 注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的
         */
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //P12文件目录 证书路径，这里需要你自己修改，linux下还是windows下的根路径
        FileInputStream instream = new FileInputStream("/home/project/wx_cert/1289663601_apiclient_cert.p12");
        // FileInputStream instream = new FileInputStream("G:\\hurui-project/hai-parent/hai-service/src/main/java/privatekey/1289663601_apiclient_cert.p12");
        try {
            keyStore.load(instream, "1289663601".toCharArray());//这里写密码..默认是你的MCHID
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1289663601".toCharArray()).build();//这里也是写密码的
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        // Allow TLSv1 protocol only
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    public String doRefundRequest(String mchId, String url, String data) throws Exception {

        //小程序退款需要调用双向证书的认证
        CloseableHttpClient httpClient = readCertificate(mchId);
        try {
            HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/profitsharing"); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "text/xml");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            httpClient.close();
        }
    }
}
