package com.bohuikeji.delivery.backstage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.payConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.baidu.BaiduRefundInfo;
import com.bohuikeji.delivery.backstage.entity.rental.TRentalCarOrder;
import com.bohuikeji.delivery.backstage.entity.rental.TRentalPay;
import com.bohuikeji.delivery.backstage.listener.order.OrderAliCenterListener;
import com.bohuikeji.delivery.backstage.mapper.TRefundMapper;
import com.bohuikeji.delivery.backstage.pay.*;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.JdServer;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.wx.wxPayUtil;
import com.bohuikeji.frame.module.admin.wxpay.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 退款记录表 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-12-27
 */
@Service
@Slf4j
public class TRefundServiceImpl extends ServiceImplBase<TRefundMapper, TRefund> implements ITRefundService {
    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITCourierPayService courierPayService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITSettleService settleService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    ITLogisticsService logisticsService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITGiveDetailService giveDetailService;
    @Autowired
    ITwalletDetailService twalletDetailService;
    @Autowired
    ITDiscountOrderService orderDiscountService;
    @Autowired
    ITRentalCarOrderService rentalCarOrderService;
    @Autowired
    ITRentalPayService rentalPayService;
    @Autowired
    MqTool mqTool;



    @Override
    public TRefund courierTRefund(AlipayTradeRefundResponse response, TOrder tOrder, TCourier courier, TCourierPay tCourierPay) {
        Double pric = Double.valueOf(response.getRefundFee());
        Instant instant = response.getGmtRefundPay().toInstant();
        TRefund tRefund = new TRefund();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        tRefund.setRefundModel("入驻缴费退款");
        tRefund.setPayId(tCourierPay.getCourierPayId());
        tRefund.setOrderId(courier.getCourierId());
        tRefund.setOrderNum(courier.getPayNum());
        tRefund.setRefundNum(NumberUtils.get("T"));
        tRefund.setPayNum(tCourierPay.getPayNum());
        tRefund.setRefundPrice(BigDecimal.valueOf(pric));
        tRefund.setRefundWay("全额退款");
        tRefund.setRefundStatus("退款成功");
        tRefund.setRefundChannel("支付宝");
        tRefund.setRefundChannelNum(response.getTradeNo());
        tRefund.setCreateTime(LocalDateTime.now());
        tRefund.setRefundTime(localDateTime);
        if(refundService.save(tRefund)){
            tCourierPay.setPayStatus("已退款");//支付信息表修改状态
            courierPayService.updateById(tCourierPay);
        }
        if(courier != null){
            courier.setCourierPayStatus("已退款");//派送员修改状态
            if(courierService.updateById(courier)){
                newsService.pushCourierMsg1(courier.getCourierId(),  "入驻费用退款通知",
                        "尊敬的用户您好，您的订单: {0},以被管理员退款，如有疑问请使用微信小程序，客服助手进行反馈。",tCourierPay.getPayNum());
            }
        }
        return tRefund;
    }

    @Override
    public TRefund cancel(TOrder tOrder, List<TPay> tPays) {
        TRefund refund= null;
        BigDecimal refundPrice;
        for(TPay pay : tPays){
            if("业务支付".equals(pay.getPayScenario())){
                refundPrice=pay.getPayFactPrice().subtract(deduct(tOrder));
            }else {
                refundPrice=pay.getPayFactPrice();
            }
            log.error("【订单取消日志】订单：{}，状态：{}，实付金额：{}，退款金额：{}",tOrder.getOrderNum(),tOrder.getOrderStatus(),tOrder.getOrderFactPrice(),refundPrice);
            if (refundPrice.compareTo(new BigDecimal("0"))<1){
                refundPrice=new BigDecimal("0.01");
            }
            if("微信".equals(pay.getPayChannel())){
                log.info("###########################进入微信退款中###########################");
                Map<String, String> rs;
                wxPayUtil payUtil = new wxPayUtil();
                rs = payUtil.refund(pay.getPayNum(), NumberUtils.get("T"), pay.getPayFactPrice().toString(),refundPrice.toPlainString(), "同城急送");
                if ("SUCCESS".equals(rs.get("result_code"))){
                    refund = this.wxAltRefund(rs,null,null,null,null,tOrder,pay,null,pay.getPayScenario()+"退款");
                    log.info("申请微信退款成功：[{}]",refund);
                }
            }
            if("支付宝".equals(pay.getPayChannel())){
                log.info("###########################进入支付宝退款中###########################");
                if("支付宝APP".equals(pay.getPayWay())){
                    AlipayTradeRefundResponse response = AliPay.refund(pay.getPayNum(),refundPrice.toPlainString(),pay.getPayChannelNum(),tOrder.getRefundReason(),pay.getPayNum());
                    if("Y".equals(response.getFundChange())){
                        refund = this.wxAltRefund(null,response,null,null,null,tOrder,pay,null,pay.getPayScenario()+"退款");
                        log.info("申请支付宝退款成功：[{}]",refund);
                    }
                }
                if("支付宝APPLET".equals(pay.getPayWay())){
                    JSONObject jsonObject;
                    if("支付宝小程序".equals(tOrder.getOrderChannel()) || "订单小费".equals(pay.getPayScenario())){
                        jsonObject = AliPay.clientRefund(pay.getPayNum(),refundPrice.toPlainString(),pay.getPayChannelNum(),tOrder.getRefundReason(),pay.getPayNum());
                    }else {
                        jsonObject = AliPayV2.clientRefundV2(pay.getPayNum(),tOrder.getOrderChannel(),refundPrice.toPlainString(),pay.getPayChannelNum(),tOrder.getRefundReason(),pay.getPayNum());
                    }
                    if("Success".equals(jsonObject.getString("msg"))){
                        refund = this.wxAltRefund(null,null,jsonObject,null,null,tOrder,pay,null,pay.getPayScenario()+"退款");
                        log.info("申请支付宝退款成功：[{}]",refund);
                    }
                }
                mqTool.sendMsg(tOrder.getOrderNum(), OrderAliCenterListener.class);
                newsService.pushCustomerMsg2(tOrder.getPlayerId(),"你好,你有订单已取消，请及时查看");
            }
            if("百度".equals(pay.getPayWay())){
                log.info("###########################进入百度退款中###########################");
                JSONObject jsonObject = BaiduPay.applyOrderRefund(pay,refundPrice);
                log.info("申请退款响应数据：[{}]",jsonObject);
                if("success".equals(jsonObject.get("msg"))){
                    itOrderService.updateById(tOrder.setOrderStatus("退款中"));
                }
            }
            if("抖音".equals(pay.getPayWay())){
                log.info("###########################进入抖音退款中###########################");
                JSONObject jsonObject = BytePay.douyinOrderRefund(pay,refundPrice);
                if("0".equals(jsonObject.get("err_no"))){
                    log.info("抖音小程序退款请求成功进入回调处理业务：{}",jsonObject);
                }
            }
            if("快手".equals(pay.getPayWay())){
                log.info("###########################进入快手退款中###########################");
                itOrderService.updateById(tOrder.setOrderStatus("退款中"));
                JSONObject jsonObject = KuaiShouPay.kuaishouOrderRefund(pay,refundPrice);
                if("1".equals(jsonObject.getInteger("result"))){
                    log.info("快手小程序退款请求成功进入回调处理业务：{}",jsonObject);
                }
            }
            if("钱包".equals(pay.getPayWay())){
                log.info("###########################进入钱包退款中###########################");
                if(refundPrice.compareTo(new BigDecimal("0.01")) == 0){
                    refundPrice=new BigDecimal("0.00");
                }
                refund = this.wxAltRefund(null,null,null,null,null,tOrder,pay,null,pay.getPayScenario()+"退款");
                TCustomerWallet customerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",pay.getPlayerId()));
                customerWalletService.updateById(customerWallet.setWalletPrice(customerWallet.getWalletPrice().add(refundPrice)));
                List<TGiveDetail> giveDetails = giveDetailService.list(new QueryWrapper<TGiveDetail>().eq("customer_id",customerWallet.getCustomerId()).eq("give_status","已使用"));
                if(giveDetails.size() > 0){
                    for(TGiveDetail giveDetail : giveDetails){
                        Duration duration = Duration.between(giveDetail.getUpdateTime(),LocalDateTime.now());//时间差
                        log.info("当前时间距离赠金记录修改时间的时间差:{}",duration.toHours());
                        if(duration.toHours() <=2){
                            giveDetail.setGiveStatus("未使用");
                            giveDetail.setUpdateTime(LocalDateTime.now());
                            giveDetailService.updateById(giveDetail);
                        }
                    }
                }
                twalletDetailService.saveDetail(null,pay,null,customerWallet,"支付退款");
                newsService.pushCustomerMsg2(tOrder.getPlayerId(),"你好,你有订单已取消，请及时查看");
            }
        }
        if(!tOrder.getDisId().equals(0)){
            orderDiscountService.cancelOrderDisByVoucher(tOrder);
        }
        ThirdUtils.orderCancelAll(tOrder.getOrderNum());
        TOrderCircu.insertCircu(tOrder);
        return refund;
    }

    /**
     * 租车退款业务
     * @param rentalCarOrder
     * @param rentalPays
     * @return
     */
    @Override
    public TRefund rentalCarCancel(TRentalCarOrder rentalCarOrder, List<TRentalPay> rentalPays) {
        TRefund tRefund = new TRefund();
        JSONObject jsonObject;
        for(TRentalPay rentalPay : rentalPays){
            BigDecimal refundPrice=rentalPay.getPayFactPrice();
            if("支付宝".equals(rentalPay.getPayChannel())){
                log.info("###########################进入支付宝退款中###########################");
                if("支付宝APPLET".equals(rentalPay.getRentalPayWay())){
                    if("急送平台".equals(rentalCarOrder.getOrderChannel())){
                        jsonObject = AliPayV2.clientRefundV2(rentalPay.getRentalPayNum(),rentalCarOrder.getOrderChannel(),refundPrice.toPlainString(),rentalPay.getPayChannelNum(),"租车退款",rentalPay.getRentalPayNum());
                    }else {
                        jsonObject = AliPay.clientRefund(rentalPay.getRentalPayNum(),refundPrice.toPlainString(),rentalPay.getPayChannelNum(),"租车退款",rentalPay.getRentalPayNum());
                    }
                    //JSONObject jsonObject = AliPay.clientRefund(rentalPay.getRentalPayNum(),refundPrice.toPlainString(),rentalPay.getPayChannelNum(),"租车退款",rentalPay.getRentalPayNum());
                    log.info("######################################################:{}",jsonObject);
                    if("Success".equals(jsonObject.getString("msg"))){
                        tRefund.setRefundNum(NumberUtils.get("T"));
                        tRefund.setRefundPrice(BigDecimal.valueOf(jsonObject.getDouble("refund_fee")));
                        tRefund.setRefundChannelNum(jsonObject.getString("trade_no"));
                        tRefund.setRefundTime(LocalDateTime.now());
                        tRefund.setRefundChannel("支付宝");
                        log.info("申请支付宝退款成功：[{}]",tRefund);
                    }
                }
                newsService.pushCustomerMsg2(rentalCarOrder.getPlayerId(),"你好,你有订单已取消，请及时查看");
            }
            tRefund.setOrderPayPrice(refundPrice);
            tRefund.setPayId(rentalPay.getRentalPayId());
            tRefund.setOrderId(rentalPay.getRentalId());
            tRefund.setOrderNum(rentalPay.getRentalOrderNum());
            tRefund.setPayNum(rentalPay.getRentalPayNum());
            tRefund.setRefundWay("全额退款");
            tRefund.setRefundStatus("退款成功");
            tRefund.setRefundModel("租车订单退款");
            tRefund.setCreateTime(LocalDateTime.now());
            refundService.save(tRefund);
            rentalPayService.updateById(rentalPay.setPayStatus("已退款"));
        }

        return tRefund;
    }

    /**
     * 派送员入驻费 退款
     * 微信/支付宝入住缴费退款
     * @param tCourierPays
     * @param courier
     * @return
     */
    @Override
    public TRefund ettlecCancel(List<TCourierPay> tCourierPays,TCourier courier) {
        TRefund refund = null;
        BigDecimal price = null;
        for(TCourierPay tCourierPay : tCourierPays){
            if(tCourierPay.getPayExpectPrice().compareTo(new BigDecimal(100))>-1 && Duration.between(tCourierPay.getCreateTime(),LocalDateTime.now()).toDays()<15){
                price = tCourierPay.getPayExpectPrice().subtract(tCourierPay.getPayExpectPrice().multiply(new BigDecimal("0.006")));
            }else {
                price = tCourierPay.getPayExpectPrice();
            }
            log.info("@@@@@@@@@@@@退款金额：[{}]",price);
            if ("微信".equals(tCourierPay.getPayChannel())) {
                Map<String, String> rs;
                wxPayUtil payUtil = new wxPayUtil();
                rs = payUtil.refund(tCourierPay.getPayNum(), NumberUtils.get("T"), tCourierPay.getPayExpectPrice().toString(), price.toString(), "同城急送");
                if ("SUCCESS".equals(rs.get("result_code"))) {
                    refund = this.ettlecRefund(rs, null, tCourierPay,  courier,tCourierPay.getPayScenario() + "退款");
                }
                else{
                    throw new RuntimeException(rs.get("err_code_des"));
                }
            }
            if ("支付宝".equals(tCourierPay.getPayChannel())) {
                AlipayTradeRefundResponse response = AliPay.refund(tCourierPay.getPayNum(), price.toString(), tCourierPay.getPayChannelNum(), "入驻退款", String.valueOf(System.currentTimeMillis()));
                if ("Y".equals(response.getFundChange())) {
                    refund = this.ettlecRefund(null, response, tCourierPay,  courier,tCourierPay.getPayScenario() + "退款");
                }
                else{
                    throw new RuntimeException(response.getSubMsg());
                }
            }
        }
         log.info("入驻退款成功：[{}]", refund);
         return refund;
    }

    /**
     * 微信/支付宝退款业务实现
     * @param rs
     * @param response
     * @param tOrder
     * @param tPay
     * @param courier
     * @param refundModel
     * @return
     */
    @Override
    public TRefund wxAltRefund(Map<String, String> rs, AlipayTradeRefundResponse response,JSONObject aliClientJson, BaiduRefundInfo baiduRefundInfo,JSONObject jsonObject,TOrder tOrder, TPay tPay, TCourier courier, String refundModel) {
        log.info("进入退款业务处理");
        TRefund tRefund = new TRefund();
        if(rs != null){//微信退款数据设置
            tRefund.setRefundNum(rs.get("out_refund_no"));
            tRefund.setRefundPrice((WXPayUtil.FenToDecimal(rs.get("refund_fee"))));
            tRefund.setRefundChannelNum(rs.get("refund_id"));
            tRefund.setRefundTime(LocalDateTime.now());
            tRefund.setRefundChannel("微信");
        }
        if(response != null){//支付宝退款数据设置
            Instant instant = response.getGmtRefundPay().toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
            tRefund.setRefundNum(NumberUtils.get("T"));
            tRefund.setRefundPrice(BigDecimal.valueOf(Double.parseDouble(response.getRefundFee())));
            tRefund.setRefundChannelNum(response.getTradeNo());
            tRefund.setRefundTime(localDateTime);
            tRefund.setRefundChannel("支付宝");
        }
        if(aliClientJson != null){//支付宝小程序退款数据设置
            tRefund.setRefundNum(NumberUtils.get("T"));
            tRefund.setRefundPrice(BigDecimal.valueOf(aliClientJson.getDouble("refund_fee")));
            tRefund.setRefundChannelNum(aliClientJson.getString("trade_no"));
            tRefund.setRefundTime(LocalDateTime.now());
            tRefund.setRefundChannel("支付宝");
        }
        if(baiduRefundInfo != null){//百度退款数据设置
            tRefund.setRefundNum(NumberUtils.get("T"));
            tRefund.setRefundPrice(tPay.getPayFactPrice());
            tRefund.setRefundChannelNum(baiduRefundInfo.getRefundBatchId());
            tRefund.setRefundTime(LocalDateTime.now());
            tRefund.setRefundChannel(tPay.getPayWay());
        }
        if(jsonObject != null){//快手、抖音退款数据设置
            if(jsonObject.getString("cp_refundno")!=null){
                tRefund.setRefundNum(jsonObject.getString("cp_refundno"));
                tRefund.setRefundChannelNum(jsonObject.getString("order_id"));
            }
            if(jsonObject.getString("ks_refund_no")!=null){
                tRefund.setRefundNum(jsonObject.getString("out_refund_no"));
                tRefund.setRefundChannelNum(jsonObject.getString("ks_refund_no"));
            }
            tRefund.setRefundPrice(tPay.getPayFactPrice());
            tRefund.setRefundTime(LocalDateTime.now());
            tRefund.setRefundChannel(tPay.getPayWay());
        }
        JSONObject object = refundService.getPreCancelInfo(tOrder);//退款金额明细
        if(object != null){
            log.info("退款金额明细展示：{}",object);
            tRefund.setOrderPayPrice(object.getBigDecimal("orderPayPrice"));
            tRefund.setNoLoadPrice(object.getBigDecimal("noLoadPrice"));
        }
        if(rs==null && response==null && aliClientJson == null && baiduRefundInfo == null && jsonObject == null){//钱包退款
            tRefund.setRefundNum(NumberUtils.get("T"));
            tRefund.setRefundPrice(tPay.getPayFactPrice().subtract(object.getBigDecimal("noLoadPrice")));
            tRefund.setRefundChannelNum(null);
            tRefund.setRefundTime(LocalDateTime.now());
            tRefund.setRefundChannel("钱包");
         }
        if(tRefund.getNoLoadPrice().compareTo(new BigDecimal("0.00"))==0){
            tRefund.setRefundWay("全额退款");
        }else {
            tRefund.setRefundWay("部分退款");
        }
        //微信/支付宝退款共用部分
        tRefund.setPayId(tPay.getPayId());
        tRefund.setOrderId(tOrder.getOrderId());
        tRefund.setOrderNum(tOrder.getOrderNum());
        tRefund.setPayNum(tPay.getPayNum());
        tRefund.setRefundStatus("退款成功");
        tRefund.setRefundModel(refundModel);
        tRefund.setCreateTime(LocalDateTime.now());
        if(refundService.save(tRefund)){
            tPay.setPayStatus("已退款");//订单信息状态修改
            payService.updateById(tPay);
            if("抖音".equals(tPay.getPayWay()) || "快手".equals(tPay.getPayWay())){
                TSettle settle = settleService.getOne(new QueryWrapper<TSettle>().eq("order_id",tPay.getOrderId()));
                settleService.updateById(settle.setSettleStatus("已退款"));
            }
            if(payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付")).size()<=0){
                List<TLogistics> tLogisticss = logisticsService.list(new QueryWrapper<TLogistics>().eq("order_id",tOrder.getOrderId()));
                logisticsService.updateOrderAndTLogistics(tLogisticss,"已退款");//修改物流与流转的状态
                tOrder.setOrderStatus("已取消");//订单状态修改
                tOrder.setThirdStatus("已取消");
                tOrder.setOrderFactPrice(new BigDecimal("0"));
                tOrder.setOrderActualPrice(new BigDecimal("0"));
                tOrder.setPrefAmount(new BigDecimal("0"));//优惠
                tOrder.setTipAmount(new BigDecimal("0"));//小费
                tOrder.setOrderEndTime(LocalDateTime.now());
                if(itOrderService.updateById(tOrder)){
                    //TOrderCircu.insertCircu(tOrder);//状态流转修改
                    if("微信小程序".equals(tOrder.getOrderChannel())){
                        itOrderService.cancelOrder("订单取消成功，如有疑问请联系客服",tOrder);//客户主动取消订单想哭推送订阅消息
                    }else {
                        itOrderService.customerAppPush(tOrder,"订单取消通知","订单取消成功，如有疑问请联系客服");
                    }
                    itOrderService.curAppPush(tOrder,"订单取消提醒",tOrder.getMailingAddress().getArea()+"的订单已取消");
                    newsService.pushCustomerMsg1(tOrder.getPlayerId(),  "订单退款通知",
                            "尊敬的用户您好，您的订单: {0}，已退款成功，如有疑问请使用微信小程序，客服助手进行反馈。",tOrder.getOrderNum());
                }
            }
        }
        return tRefund;
    }

    /**
     * 预退款明细
     * 开发接口也用此接口
     * @param order
     * @return
     */
    @Override
    public JSONObject getPreCancelInfo(TOrder order) {
        JSONObject jsonObject = new JSONObject(true);
        BigDecimal refundPrice=new BigDecimal("0.00");
        BigDecimal loadFee = new BigDecimal("0.00");
        TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("order_id",order.getOrderId()).eq("pay_status","已支付"));
        if(tPay == null){
            jsonObject.put("refundPrice",refundPrice);//实际退款金额
            jsonObject.put("noLoadPrice",loadFee);
            return jsonObject;
        }
        if("业务支付".equals(tPay.getPayScenario())){
            loadFee = refundService.deduct(order);
        }
        //BigDecimal loadFee = refundService.deduct(order);
        refundPrice=tPay.getPayFactPrice().subtract(loadFee);
        jsonObject.put("orderNum",order.getOrderNum());//订单号
        jsonObject.put("orderStatus",order.getOrderStatus());//订单状态
        jsonObject.put("acceptanceTime",order.getAcceptanceTime());//接单时间
        jsonObject.put("preCancelTime",LocalDateTime.now());//预取消时间
        jsonObject.put("orderPayPrice",tPay.getPayFactPrice());//订单支付金额
        jsonObject.put("refundPrice",refundPrice);//实际退款金额
        jsonObject.put("noLoadPrice",loadFee);//取消扣款金额
        jsonObject.put("chargeExplain","接单后5-8分钟取消扣款2元,超过8分钟取消扣款5元,连续取消次数超过2次扣款2元");//扣款说明
        return jsonObject;
    }

    /**
     * 微信/支付入驻退款业务处理
     * @param rs
     * @param response
     * @param tCourierPay
     * @param courier
     * @param refundModel
     * @return
     */
    @Override
    public TRefund ettlecRefund(Map<String, String> rs,AlipayTradeRefundResponse response,TCourierPay tCourierPay,TCourier courier, String refundModel) {
        TRefund tRefund = new TRefund();
        if(rs != null){//微信退款数据设置
            tRefund.setRefundNum(rs.get("out_refund_no"));
            tRefund.setRefundPrice((WXPayUtil.FenToDecimal(rs.get("refund_fee"))));
            tRefund.setRefundChannelNum(rs.get("refund_id"));
            tRefund.setRefundTime(LocalDateTime.now());
            tRefund.setRefundChannel("微信");
        }
        if(response != null){//支付宝退款数据设置
            Instant instant = response.getGmtRefundPay().toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
            tRefund.setRefundNum(NumberUtils.get("T"));
            tRefund.setRefundPrice(BigDecimal.valueOf(Double.valueOf(response.getRefundFee())));
            tRefund.setRefundChannelNum(response.getTradeNo());
            tRefund.setRefundTime(localDateTime);
            tRefund.setRefundChannel("支付宝");
        }
        //微信/支付宝退款共用部分
        tRefund.setPayId(tCourierPay.getCourierPayId());
        tRefund.setOrderId(courier.getCourierId());
        tRefund.setOrderNum(tCourierPay.getPayNum());
        tRefund.setPayNum(tCourierPay.getPayNum());
        tRefund.setRefundWay("全额退款");
        tRefund.setRefundStatus("退款成功");
        tRefund.setRefundModel(refundModel);
        tRefund.setCreateTime(LocalDateTime.now());
        if(refundService.save(tRefund)){
            tCourierPay.setPayStatus("已退款");//支付信息表修改状态
            courierPayService.updateById(tCourierPay);
            courier.setCourierSettledMoney(new BigDecimal(0));
            courier.setGrade(1);
            courier.setCourierPayStatus("已退款");//派送员修改状态
            if(courierService.updateById(courier)){
                //newsService.pushCourierMsg(courier.getCourierId(), "系统消息", "入驻费用退款通知", "尊敬的用户您好，您的订单: {0},以被管理员退款，如有疑问请使用微信小程序，客服助手进行反馈。",tCourierPay.getPayNum());
                newsService.pushCourierMsg1(courier.getCourierId(),"审核通过通知","派送员：{0}您好，您提交的退款审核已通过。如有问题，可搜索关注微信公众号：同城急送  使用对话框进行咨询。",courier.getCourierName());
            }
        }
        /*if(courier != null){
            courier.setCourierSettledMoney(new BigDecimal(0));
            courier.setGrade(1);
            courier.setCourierPayStatus("已退款");//派送员修改状态
            if(courierService.updateById(courier)){
                //newsService.pushCourierMsg(courier.getCourierId(), "系统消息", "入驻费用退款通知", "尊敬的用户您好，您的订单: {0},以被管理员退款，如有疑问请使用微信小程序，客服助手进行反馈。",tCourierPay.getPayNum());
                newsService.pushCourierMsg1(courier.getCourierId(),"审核通过通知","派送员：{0}您好，您提交的退款审核已通过。如有问题，可搜索关注微信公众号：同城急送  使用对话框进行咨询。",courier.getCourierName());
            }
        }*/
        return tRefund;
    }
    /**
     * 取消订单计算扣款金额
     * @param order
     * @return
     */
    @Override
    public  BigDecimal deduct(TOrder order){
        BigDecimal price=new BigDecimal("0.00");
        //京东订单暂时不扣款
        if (JdServer.isJdOrder(order.getOrderNum())){
            return price;
        }
        String[] states={"取件中","已取消"," 派送中"};
        for (String state : states) {
            if(state.equals(order.getOrderStatus())){
                if (order.getAcceptanceTime()!=null){
                    java.time.Duration duration = java.time.Duration.between(order.getAcceptanceTime(),LocalDateTime.now());
                    if (order.getCancelType()!=1){
                        return price;
                    }
                    if (duration.toMinutes()>8){
                        return new BigDecimal("5");
                    }
                    if (duration.toMinutes()>=5){
                        return new BigDecimal("2");
                    }
                    //每天接单后取消订单数量大于2单则扣款2元。
                    if (itOrderService.cancelOrderTimes(order.getPlayerId())>2){
                        return new BigDecimal("2");
                    }
                }
            }
        }
        return price;
    }


}
