package com.sqx.modules.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserVipDao;
import com.sqx.modules.app.dao.VipDetailsDao;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.*;
import com.sqx.modules.artificer.dao.OrdersDao;
import com.sqx.modules.artificer.dao.RealNameDao;
import com.sqx.modules.artificer.dao.UserRechargeDao;
import com.sqx.modules.artificer.entity.*;
import com.sqx.modules.artificer.service.*;
import com.sqx.modules.bl.massage.entity.MassagePackage;
import com.sqx.modules.bl.massage.service.MassagePackageService;
import com.sqx.modules.bl.order.dao.UserPackageOrderDao;
import com.sqx.modules.bl.order.entity.UserPackage;
import com.sqx.modules.bl.order.entity.UserPackageDetail;
import com.sqx.modules.bl.order.entity.UserPackageOrder;
import com.sqx.modules.bl.order.entity.UserPackageOrdersMapping;
import com.sqx.modules.bl.order.service.UserPackageDetailService;
import com.sqx.modules.bl.order.service.UserPackageOrderService;
import com.sqx.modules.bl.order.service.UserPackageOrdersMappingService;
import com.sqx.modules.bl.order.service.UserPackageService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.consortia.entity.Consortia;
import com.sqx.modules.consortia.service.ConsortiaService;
import com.sqx.modules.coupon.entity.Coupon;
import com.sqx.modules.coupon.entity.CouponIssue;
import com.sqx.modules.coupon.entity.CouponUser;
import com.sqx.modules.coupon.service.CouponIssueService;
import com.sqx.modules.coupon.service.CouponService;
import com.sqx.modules.coupon.service.CouponUserService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.pay.config.WXConfig;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayClassify;
import com.sqx.modules.pay.entity.PayClassifyDetail;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.PayClassifyDetailService;
import com.sqx.modules.pay.service.PayClassifyService;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.utils.*;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author fang
 * @date 2020/2/26
 */
@Service
@Slf4j
public class WxServiceImpl implements WxService {
    private static final String SPBILL_CREATE_IP = "127.0.0.1";
    private static final String TRADE_TYPE_APP = "APP";
    private static final String TRADE_TYPE_NATIVE = "NATIVE";
    private static final String TRADE_TYPE_JSAPI = "JSAPI";
    private static final String Wap = "MWEB";

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private RealNameDao realNameDao;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private OrdersMassageService ordersMassageService;
    @Autowired
    private MassageTypeService massageTypeService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private PayClassifyService payClassifyService;
    @Autowired
    private PayClassifyDetailService payClassifyDetailService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponIssueService couponIssueService;
    @Autowired
    private VipDetailsDao vipDetailsDao;
    @Autowired
    private UserVipDao userVipDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ConsortiaService consortiaService;
    @Autowired
    private UserMoneyArtificerService userMoneyArtificerService;
    @Autowired
    private ArtificerTimeService artificerTimeService;
    @Autowired
    private UserRechargeDao userRechargeDao;
    @Autowired
    private UserPackageOrderDao userPackageOrderDao;
    @Autowired
    MassagePackageService massagePackageService;
    @Autowired
    UserPackageService userPackageService;
    @Autowired
    UserPackageDetailService userPackageDetailService;
    @Autowired
    private UserPackageOrderService userPackageOrderService;
    @Autowired
    UserPackageOrdersMappingService userPackageOrdersMappingService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取总花费时间
     * @param duration 服务时长
     * @param serveTime 服务时间
     * @param value1 是否开启忙时
     * @param tripWay 出行方式
     * @param artificerId 技师ID
     * @return
     */
    private Map<String,Object> getTaskTime(Integer duration,String serveTime,String value1,Integer tripWay,Long artificerId){
        Map<String,Object> map = new HashMap<>();

        String beforeTime = commonInfoService.findOne(457).getValue();
        int beforeTimeInt = Integer.parseInt(beforeTime);

        String afterTime = commonInfoService.findOne(458).getValue();
        int afterTimeInt = Integer.parseInt(afterTime);

        String jyValue = commonInfoService.findOne(392).getValue();
        int jyMinuteInt = Integer.parseInt(jyValue);

        int cxsjInt = 0;
        if(Objects.nonNull(tripWay)){
            if(tripWay.equals(1)){
                String cxsj = commonInfoService.findOne(454).getValue();
                cxsjInt = Integer.parseInt(cxsj);
            }
            if(tripWay.equals(2)){
                String cxsj = commonInfoService.findOne(455).getValue();
                cxsjInt = Integer.parseInt(cxsj);
            }
            if(tripWay.equals(3)){
                String cxsj = commonInfoService.findOne(456).getValue();
                cxsjInt = Integer.parseInt(cxsj);
            }
        }
        beforeTimeInt = beforeTimeInt + cxsjInt; //服务时间前锁单时间
        int minute=0;
        int i = 0;
        int f = 0;
        int a = 0;
        if ("是".equals(value1)) {
            minute = jyMinuteInt;
            if (duration % minute == 0) {
                i = duration / minute;
            } else {
                i = duration / minute;
                i++;
            }
            if (beforeTimeInt % minute == 0) {
                f = beforeTimeInt / minute;
            } else {
                f = beforeTimeInt / minute;
                f++;
            }
            if (afterTimeInt % minute == 0) {
                a = afterTimeInt / minute;
            } else {
                a = afterTimeInt / minute;
                a++;
            }
        }
        List<String> allTime = new ArrayList<>();
        String date = serveTime.substring(0, 10);
        String time = serveTime.substring(11, 16);
        Date parse = DateUtils.stringToDate(serveTime,"yyyy-MM-dd HH:mm");
        //服务时间前锁单时间判断
        if (f > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            for (int j = 0; j < f; j++) {
                calendar.add(Calendar.MINUTE, -minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        //服务时间后锁单时间判断
        if (i > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            for (int j = 0; j < i; j++) {
                calendar.add(Calendar.MINUTE, minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        //服务中锁单时间判断
        if (a > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            calendar.add(Calendar.MINUTE, minute*i);
            for (int j = 0; j < a; j++) {
                calendar.add(Calendar.MINUTE, minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        allTime.sort(Comparator.naturalOrder());
        map.put("timeList",allTime);
        map.put("code","0");
        return map;
    }

    /**
     * 获取总花费时间，包含当前订单中得时间
     * @param duration 服务时长
     * @param serveTime 服务时间
     * @param value1 是否开启忙时
     * @param tripWay 出行方式
     * @param artificerId 技师ID
     * @param ordersId 订单ID
     * @return
     */
    private Map<String,Object> getTaskTimeIncudeOrders(Integer duration,String serveTime,String value1,Integer tripWay,Long artificerId,Long ordersId){
        Map<String,Object> map = new HashMap<>();

        String beforeTime = commonInfoService.findOne(457).getValue();
        int beforeTimeInt = Integer.parseInt(beforeTime);

        String afterTime = commonInfoService.findOne(458).getValue();
        int afterTimeInt = Integer.parseInt(afterTime);

        String jyValue = commonInfoService.findOne(392).getValue();
        int jyMinuteInt = Integer.parseInt(jyValue);

        int cxsjInt = 0;
        if(Objects.nonNull(tripWay)){
            if(tripWay.equals(1)){
                String cxsj = commonInfoService.findOne(454).getValue();
                cxsjInt = Integer.parseInt(cxsj);
            }
            if(tripWay.equals(2)){
                String cxsj = commonInfoService.findOne(455).getValue();
                cxsjInt = Integer.parseInt(cxsj);
            }
            if(tripWay.equals(3)){
                String cxsj = commonInfoService.findOne(456).getValue();
                cxsjInt = Integer.parseInt(cxsj);
            }
        }
        beforeTimeInt = beforeTimeInt + cxsjInt; //服务时间前锁单时间
        int minute=0;
        int i = 0;
        int f = 0;
        int a = 0;
        if ("是".equals(value1)) {
            minute = jyMinuteInt;
            if (duration % minute == 0) {
                i = duration / minute;
            } else {
                i = duration / minute;
                i++;
            }
            if (beforeTimeInt % minute == 0) {
                f = beforeTimeInt / minute;
            } else {
                f = beforeTimeInt / minute;
                f++;
            }
            if (afterTimeInt % minute == 0) {
                a = afterTimeInt / minute;
            } else {
                a = afterTimeInt / minute;
                a++;
            }
        }
        List<String> allTime = new ArrayList<>();
        String date = serveTime.substring(0, 10);
        String time = serveTime.substring(11, 16);
        Date parse = DateUtils.stringToDate(serveTime,"yyyy-MM-dd HH:mm");
        //服务时间前锁单时间判断
        if (f > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            for (int j = 0; j < f; j++) {
                calendar.add(Calendar.MINUTE, -minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .ne("orders_id", ordersId)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        //服务时间后锁单时间判断
        if (i > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            for (int j = 0; j < i; j++) {
                calendar.add(Calendar.MINUTE, minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .ne("orders_id", ordersId)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        //服务中锁单时间判断
        if (a > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            calendar.add(Calendar.MINUTE, minute*i);
            for (int j = 0; j < a; j++) {
                calendar.add(Calendar.MINUTE, minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .ne("orders_id", ordersId)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        allTime.sort(Comparator.naturalOrder());
        map.put("timeList",allTime);
        map.put("code","0");
        return map;
    }

    /**
     * 获取加钟总花费时间
     * @param duration 服务时长
     * @param serveTime 服务时间
     * @param value1 是否开启忙时
     * @param artificerId 技师ID
     * @return
     */
    private Map<String,Object> getAddTaskTime(Integer duration,String serveTime,String value1,Long artificerId){
        Map<String,Object> map = new HashMap<>();
        String jyValue = commonInfoService.findOne(392).getValue();
        int jyMinuteInt = Integer.parseInt(jyValue);
        int minute=0;
        int i = 0;
        if ("是".equals(value1)) {
            minute = jyMinuteInt;
            if (duration % minute == 0) {
                i = duration / minute;
            } else {
                i = duration / minute;
                i++;
            }
        }
        List<String> allTime = new ArrayList<>();
        String date = serveTime.substring(0, 10);
        String time = serveTime.substring(11, 16);
        Date parse = DateUtils.stringToDate(serveTime,"yyyy-MM-dd HH:mm");
        //服务时间后锁单时间判断
        if (i > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            for (int j = 0; j < i; j++) {
                calendar.add(Calendar.MINUTE, minute);
                String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
                allTime.add(format);
                date = format.substring(0, 10);
                time = format.substring(11, 16);
                ArtificerTime artificerTime = artificerTimeService.getOne(
                        new QueryWrapper<ArtificerTime>()
                                .eq("artificer_id", artificerId)
                                .eq("artificer_date", date)
                                .eq("artificer_time", time)
                                .last("limit 1"));
                if (artificerTime != null) {
                    map.put("code","1");
                }
            }
        }
        allTime.sort(Comparator.naturalOrder());
        map.put("timeList",allTime);
        map.put("code","0");
        return map;
    }

    /**
     * 插入技师占用时间表
     * @param allTime 时间集合
     * @param artificerId 技师ID
     * @param ordersId 订单ID
     */
    private void insertArtificerTime(List<String> allTime,Long artificerId,Long ordersId){
        if(allTime!=null && allTime.size()>0) {
            for (int i=0; i<allTime.size(); i++) {
                String serveTime2 = allTime.get(i);
                String date2 = serveTime2.substring(0, 10);
                String time2 = serveTime2.substring(11, 16);
                ArtificerTime artificerTime2 = new ArtificerTime();
                artificerTime2.setArtificerId(artificerId);
                artificerTime2.setArtificerDate(date2);
                artificerTime2.setArtificerTime(time2);
                artificerTime2.setClassify(1);
                artificerTime2.setOrdersId(ordersId);
                artificerTime2.setCreateTime(DateUtils.format(new Date()));
                artificerTimeService.save(artificerTime2);
            }
        }
    }

    @Override
    public Result payMoney(Long userId,Long payClassifyId,Integer classify, Long artificerId, Long ordersId,HttpServletRequest request) throws Exception {
        PayClassify payClassify = payClassifyService.getById(payClassifyId);
        String generalOrder = getGeneralOrder();
        PayDetails payDetails = new PayDetails();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(generalOrder);
        payDetails.setUserId(userId);
        payDetails.setMoney(payClassify.getPrice().doubleValue());
        payDetails.setClassify(classify);
        payDetails.setType(3);
        payDetails.setArtificerId(artificerId);
        payDetails.setRemark(String.valueOf(payClassifyId));
        payDetails.setMassageOrdersId(ordersId);
        payDetailsDao.insert(payDetails);
//        return pay(payClassify.getPrice().doubleValue(), classify, userId, generalOrder,request);
        payOrderResult(generalOrder);
        return Result.success();
    }

    @Override
    public Result payOrder(Long id, Integer classify,HttpServletRequest request) throws Exception {
        Orders orders = ordersService.getById(id);
        if (orders == null) {
            return Result.error("订单生成失败，请重新下单！");
        }else if(orders.getStatus()!=1){
            return Result.error("订单状态异常，请刷新页面后重试！");
        }

        if(orders.getParentId()!=null && orders.getParentId()!=0){
            Orders orders1 = ordersDao.selectById(orders.getParentId());
            OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders1.getOrdersId()));
            MassageType massageType = null;
            if(orders1.getUserPackageDetailId() !=null){
                UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                massageType = massageTypeService.getById(userPackageDetail.getMassageTypeId());
            }else{
                massageType = massageTypeService.getById(ordersMassage.getMassageId());
            }
            if (massageType.getAddNum() == null || massageType.getAddNum() == 0) {
                return Result.error("当前项目不允许加钟！");
            } else if (massageType.getAddNum() > 0) {
                if (orders1.getAddNum() != null && orders1.getAddNum().intValue() >= massageType.getAddNum().intValue()) {
                    return Result.error("当前项目已超过最大加钟次数！");
                }
            }
            String value1 = commonInfoService.findOne(395).getValue();
            if ("是".equals(value1)) {
                ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getParentId()).last(" order by artificer_time_id desc limit 1 "));
                String serveTime = artificerTime.getArtificerDate() + " " + artificerTime.getArtificerTime();
                Map<String,Object> map = getAddTaskTime(orders.getDuration(),serveTime,value1,orders.getArtificerId());
                if(map.get("code").toString().equals("1")){
                    return Result.error("预约时间正忙，请更换其他时间！");
                }
                insertArtificerTime((ArrayList)map.get("timeList"),orders.getArtificerId(),orders.getOrdersId());
            }
        }else{
            String value1 = commonInfoService.findOne(395).getValue();
            if ("是".equals(value1)) {
                if(orders.getIsSupplement() != null){
                    if(orders.getIsSupplement() == 1){
                        String serveTime = orders.getServeTime();
                        String date = serveTime.substring(0, 10);
                        String time = serveTime.substring(11, 16);
                        ArtificerTime artificerTime = artificerTimeService.getOne(
                                new QueryWrapper<ArtificerTime>()
                                        .eq("artificer_id", orders.getArtificerId())
                                        .eq("artificer_date", date)
                                        .eq("artificer_time", time)
                                        .last("limit 1"));
                        if (artificerTime != null) {
                            return Result.error("预约时间正忙，请更换其他时间！");
                        }
                        Map<String,Object> map = getTaskTime(orders.getDuration(),orders.getServeTime(),value1,orders.getTripWay(),orders.getArtificerId());
                        if(map.get("code").toString().equals("1")){
                            return Result.error("预约时间正忙，请更换其他时间！");
                        }
                        insertArtificerTime((ArrayList)map.get("timeList"),orders.getArtificerId(),orders.getOrdersId());
                    }else if(orders.getIsSupplement() == 2){
                        Orders oldOrders = ordersDao.selectById(orders.getOrdersId());
                        int timeDifference = orders.getDuration()-oldOrders.getDuration();
                        if(timeDifference>0){
                            ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()).last(" order by artificer_time_id desc limit 1 "));
                            String serveTime = artificerTime.getArtificerDate() + " " + artificerTime.getArtificerTime();
                            Map<String,Object> map = getAddTaskTime(timeDifference,serveTime,value1,oldOrders.getArtificerId());
                            if(map.get("code").toString().equals("1")){
                                return Result.error("预约时间正忙，请更换其他时间！");
                            }
                            //技师占用时间表插入新订单号的多出来的服务时间
                            insertArtificerTime((ArrayList)map.get("timeList"),orders.getArtificerId(),orders.getOrdersId());
                        }else{
                            //技师占用时间表插入新订单号的同时间
                            List<ArtificerTime> artificerTimeList = artificerTimeService.list(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()).last(" order by artificer_time_id"));
                            if(artificerTimeList!=null && artificerTimeList.size()>0){
                                for(int i=0; i<artificerTimeList.size(); i++){
                                    ArtificerTime artificerTime = artificerTimeList.get(i);
                                    artificerTime.setArtificerId(orders.getArtificerId());
                                    artificerTime.setOrdersId(orders.getOrdersId());
                                    artificerTime.setCreateTime(DateUtils.format(new Date()));
                                    artificerTimeService.save(artificerTime);
                                }
                            }
                        }
                    }else{
                        //orders.getIsSupplement() == 3 || orders.getIsSupplement() == 4
                        String serveTime = orders.getServeTime();
                        String date = serveTime.substring(0, 10);
                        String time = serveTime.substring(11, 16);
                        ArtificerTime artificerTime = artificerTimeService.getOne(
                                new QueryWrapper<ArtificerTime>()
                                        .eq("artificer_id", orders.getArtificerId())
                                        .eq("artificer_date", date)
                                        .eq("artificer_time", time)
                                        .ne("orders_id", orders.getOrdersId())
                                        .last("limit 1"));
                        if (artificerTime != null) {
                            return Result.error("预约时间正忙，请更换其他时间！");
                        }
                        Map<String,Object> map = getTaskTimeIncudeOrders(orders.getDuration(),orders.getServeTime(),value1,orders.getTripWay(),orders.getArtificerId(),orders.getOldOrdersId());
                        if(map.get("code").toString().equals("1")){
                            return Result.error("预约时间正忙，请更换其他时间！");
                        }
                        //删除技师占用时间表数据
                        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOldOrdersId()));
                        //插入技师占用时间表新订单
                        insertArtificerTime((ArrayList)map.get("timeList"),orders.getArtificerId(),orders.getOrdersId());
                        //插入技师占用时间表原订单
                        insertArtificerTime((ArrayList)map.get("timeList"),orders.getArtificerId(),orders.getOldOrdersId());
                    }
                }else{
                    String serveTime = orders.getServeTime();
                    String date = serveTime.substring(0, 10);
                    String time = serveTime.substring(11, 16);
                    ArtificerTime artificerTime = artificerTimeService.getOne(
                            new QueryWrapper<ArtificerTime>()
                                    .eq("artificer_id", orders.getArtificerId())
                                    .eq("artificer_date", date)
                                    .eq("artificer_time", time)
                                    .last("limit 1"));
                    if (artificerTime != null) {
                        return Result.error("预约时间正忙，请更换其他时间！");
                    }
                    Map<String,Object> map = getTaskTime(orders.getDuration(),orders.getServeTime(),value1,orders.getTripWay(),orders.getArtificerId());
                    if(map.get("code").toString().equals("1")){
                        return Result.error("预约时间正忙，请更换其他时间！");
                    }
                    insertArtificerTime((ArrayList)map.get("timeList"),orders.getArtificerId(),orders.getOrdersId());
                }
            }
        }

        PayDetails payDetails1 = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails1 == null) {
            PayDetails payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            if (orders.getUserPackageDetailId() != null) {
                payDetails.setMoney(orders.getTaxiMoney().doubleValue());
            } else {
                payDetails.setMoney(orders.getPayMoney().doubleValue());
            }
            payDetails.setClassify(classify);
            payDetails.setType(1);
            payDetailsDao.insert(payDetails);
        } else {
            payDetails1.setClassify(classify);
            payDetailsDao.updateById(payDetails1);
        }
//        if(orders.getUserPackageDetailId() !=null ){
//            return pay(orders.getTaxiMoney().doubleValue(), classify, orders.getUserId(), orders.getOrdersNo(),request);
//        }else{
//            return pay(orders.getPayMoney().doubleValue(), classify, orders.getUserId(), orders.getOrdersNo(),request);
//        }
        payOrderResult(orders.getOrdersNo());

        return Result.success();

    }

    @Override
    public Result payPackageOrder(Long id, Integer classify,HttpServletRequest request) throws Exception {
        UserPackageOrder orders = userPackageOrderDao.getById(id);
        if (orders == null) {
            return Result.error("订单生成失败，请重新下单！");
        }else if(orders.getStatus()==1){
            return Result.error("订单已支付！");
        }else if(orders.getStatus()==2){
            return Result.error("订单已退款！");
        }else if(orders.getStatus()==3){
            return Result.error("订单支付超时，请重新发起购买！");
        }

        PayDetails payDetails1 = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails1 == null) {
            PayDetails payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            payDetails.setMoney(orders.getPayMoney().doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(7);
            payDetailsDao.insert(payDetails);
        } else {
            payDetails1.setClassify(classify);
            payDetails1.setType(7);
            payDetailsDao.updateById(payDetails1);
        }
//        return pay(orders.getPayMoney().doubleValue(), classify, orders.getUserId(), orders.getOrdersNo(),request);
        payOrderResult(orders.getOrdersNo());

        return Result.success();
    }

    @Override
    public Result payGroupOrders(Long id, Integer classify,HttpServletRequest request) throws Exception {
        UserPackageOrder orders = userPackageOrderDao.getById(id);
        if (orders == null) {
            return Result.error("订单生成失败，请重新下单！");
        }else if(orders.getStatus()==1){
            return Result.error("订单已支付！");
        }else if(orders.getStatus()==2){
            return Result.error("订单已退款！");
        }else if(orders.getStatus()==3){
            return Result.error("订单支付超时，请重新发起购买！");
        }

        PayDetails payDetails1 = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails1 == null) {
            PayDetails payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            payDetails.setMoney(orders.getPayMoney().doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(8);
            payDetailsDao.insert(payDetails);
        } else {
            payDetails1.setClassify(classify);
            payDetails1.setType(8);
            payDetailsDao.updateById(payDetails1);
        }
//        return pay(orders.getPayMoney().doubleValue(), classify, orders.getUserId(), orders.getOrdersNo(),request);
        payOrderResult(orders.getOrdersNo());

        return Result.success();
    }

    private Result payPackageOrderResult(String ordersNo,Integer classify){
        Orders orders = ordersService.selectOrdersByOrderNo(ordersNo);
        if(orders.getIsSupplement() != null){
            if(orders.getIsSupplement() == 2){
                orders.setStatus(6);
            }else if(orders.getIsSupplement() == 3){
                orders.setStatus(2);
            }else{
                orders.setStatus(9);//用户已支付技师待接单
            }
        }else{
            if(orders.getParentId()!=null && orders.getParentId()!=0){
                orders.setStatus(6);
            }else{
                orders.setStatus(9);//用户已支付技师待接单
            }
        }
        orders.setPayWay(classify);
        orders.setPayTime(sdf.format(new Date()));

        BigDecimal rate = new BigDecimal(100);
        if(orders.getUserPackageDetailId() != null){
            OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
            UserPackage userPackage = userPackageService.getById(userPackageDetail.getMainId());
            UserPackageOrder userPackageOrder = userPackageOrderService.getById(userPackage.getOrdersId());
            Integer packagePayWay = userPackageOrder.getPayWay();
            if(packagePayWay.equals(5)){
                rate = new BigDecimal(commonInfoService.findOne(449).getValue());
            }
        }
        orders.setWalletRate(rate);
        rate = rate.divide(new BigDecimal(100));
        BigDecimal storageRate = BigDecimal.ONE.subtract(rate);

        Artificer artificer = artificerService.getById(orders.getArtificerId());
        BigDecimal taxiMoney = BigDecimal.ZERO;
        if(orders.getIsSupplement()!=null && orders.getIsSupplement() == 2){
            taxiMoney = BigDecimal.ZERO;
        }else{
            taxiMoney = orders.getTaxiMoney();
        }
        if(taxiMoney==null){
            taxiMoney = BigDecimal.ZERO;
        }
        BigDecimal artificerPrice = BigDecimal.ZERO;
        BigDecimal artificerTaxiPrice = BigDecimal.ZERO;
        BigDecimal valueStorageDeduction = BigDecimal.ZERO;
        //查询是否计算出租车扣费
        String taxi = commonInfoService.findOne(394).getValue();
        //计算技师出租车收益（按照技师表收益计算）
        if ("是".equals(taxi)) {
            //计算技师应该收取的出租车费用
            artificerTaxiPrice = taxiMoney.multiply(artificer.getRate());
            artificerTaxiPrice = artificerTaxiPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            //计算出租车扣款
            BigDecimal pingTaxiMoney = taxiMoney.subtract(artificerTaxiPrice);
            //赋值技师出租收款
            orders.setArtificerTaxiMoney(artificerTaxiPrice);
            //赋值出租车扣款
            orders.setPingTaxiMoney(pingTaxiMoney);
        } else {
            //平台不扣费 出租车收益全由技师收取
            artificerTaxiPrice = taxiMoney;
            orders.setArtificerTaxiMoney(taxiMoney);
            //设置出租车扣款为0
            orders.setPingTaxiMoney(BigDecimal.ZERO);
        }
        BigDecimal subtract = BigDecimal.ZERO;
        //用户支付减去通行费用
        if(orders.getIsSupplement()!=null && orders.getIsSupplement() == 2){
            subtract = orders.getPayMoney();
        }else{
            subtract = orders.getPayMoney().subtract(taxiMoney);
        }
        //计算用户收益 ！计算前先减去通行费用再计算技师抽成
        artificerPrice = subtract.multiply(artificer.getRate());
        artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
        //储值扣费
        valueStorageDeduction = artificerPrice.multiply(storageRate);//技师提成中扣除金额
        valueStorageDeduction = valueStorageDeduction.setScale(2, BigDecimal.ROUND_HALF_UP);
        orders.setValueStorageDeduction(valueStorageDeduction);

        //用户收益不含交通费
        artificerPrice = artificerPrice.multiply(rate);
        artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

        orders.setProjectBenefits(artificerPrice);

        UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
//        UserEntity oneArtificerUser = userService.queryByInvitationCode(artificerUser.getInviterCode());
//        BigDecimal oneArtificerMoney = BigDecimal.ZERO;
//        if (oneArtificerUser != null && oneArtificerUser.getIsAgency() != null && oneArtificerUser.getIsAgency() == 1) {
//            orders.setOneArtificerUserId(oneArtificerUser.getUserId());
//            orders.setOneArtificerUserName(oneArtificerUser.getUserName());
//            oneArtificerMoney = artificerPrice.multiply(oneArtificerUser.getShopRate());
//            oneArtificerMoney = oneArtificerMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
//        }
//        orders.setOneArtificerMoney(oneArtificerMoney);
        UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
        BigDecimal jjrMoney = BigDecimal.ZERO;
        if (jjrUser != null) {
            orders.setJjrUserId(jjrUser.getUserId());
            orders.setJjrUserName(jjrUser.getUserName());
            jjrMoney = jjrMoney.multiply(jjrUser.getBlJjrRate());
            jjrMoney = jjrMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        orders.setJjrMoney(jjrMoney);
        BigDecimal shopMoney = BigDecimal.ZERO;
        if (artificerUser.getConsortiaId() != null) {
            Consortia consortia = consortiaService.getById(artificerUser.getConsortiaId());
            if (consortia != null && consortia.getUserId() != null) {
                UserEntity consortiaUser = userService.getById(consortia.getUserId());
                if (consortiaUser != null) {
                    orders.setConsortiaId(consortia.getConsortiaId());
                    orders.setShopUserId(consortiaUser.getUserId());
                    orders.setShopUserName(consortiaUser.getUserName());
                    shopMoney = artificerPrice.multiply(consortia.getRate());
                    shopMoney = shopMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                }
            }
        }
        orders.setShopMoney(shopMoney);
        UserEntity user = userService.selectUserById(orders.getUserId());
        UserEntity oneUser = userService.queryByInvitationCode(user.getInviterCode());
        BigDecimal oneUserMoney = BigDecimal.ZERO;
        if (oneUser != null && oneUser.getIsAgency() != null && oneUser.getIsAgency() == 1) {
            orders.setOneUserId(oneUser.getUserId());
            orders.setOneUserName(oneUser.getUserName());
            oneUserMoney = artificerPrice.multiply(oneUser.getUserRate());
            oneUserMoney = oneUserMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        orders.setOneUserMoney(oneUserMoney);
//        artificerPrice = artificerPrice.subtract(oneArtificerMoney);
        artificerPrice = artificerPrice.subtract(jjrMoney);
        artificerPrice = artificerPrice.subtract(shopMoney);
        artificerPrice = artificerPrice.subtract(oneUserMoney);
        if(orders.getIsSupplement()!=null && orders.getIsSupplement().equals(2)){
        }else{
            //用户收益加上通行费用
            artificerPrice = artificerPrice.add(artificerTaxiPrice);
        }
        orders.setArtificerMoney(artificerPrice);
        orders.setSumArtificerMoney(artificerPrice);

        //平台扣款
        BigDecimal pingMoney = orders.getPayMoney();
        pingMoney = pingMoney.subtract(artificerPrice);
        pingMoney = pingMoney.subtract(shopMoney);
//        pingMoney = pingMoney.subtract(oneArtificerMoney);
        pingMoney = pingMoney.subtract(jjrMoney);
        pingMoney = pingMoney.subtract(oneUserMoney);
        orders.setPingMoney(pingMoney);

        ordersService.updateById(orders);

        if(orders.getParentId()!=null && orders.getParentId()!=0){
            Calendar calendar=Calendar.getInstance();

            Orders orders1 = ordersDao.selectById(orders.getParentId());
            if(orders1.getAddNum()==null){
                orders1.setAddNum(1);
            }else{
                orders1.setAddNum(orders1.getAddNum()+1);
            }
            //获取加钟项目的时长
            if(orders1.getAddTime()!=null){
                orders1.setAddTime(orders1.getAddTime()+orders.getAddTime());
            }else{
                orders1.setAddTime(orders.getAddTime());
            }
            boolean flag2 = false;
            if (StringUtils.isNotBlank(orders1.getEndTime())) {
                Calendar calendar2 = Calendar.getInstance();
                Date date = DateUtils.stringToDate(orders1.getEndTime(), "yyyy-MM-dd HH:mm:ss");
                calendar2.setTime(date);
                calendar2.add(Calendar.MINUTE, orders.getAddTime());
                orders1.setEndTime(DateUtils.format(calendar2.getTime()));
                flag2 = true;
            }
            if(orders1.getAddMoney()!=null){
                orders1.setAddMoney(orders1.getAddMoney().add(orders.getPayMoney()));
                orders1.setAddArtificerMoney(orders1.getAddArtificerMoney().add(orders.getArtificerMoney()));
            }else{
                orders1.setAddMoney(orders.getPayMoney());
                orders1.setAddArtificerMoney(orders.getArtificerMoney());
            }
            orders1.setSumMoney(orders1.getSumMoney().add(orders.getPayMoney()));
            orders1.setSumArtificerMoney(orders1.getSumArtificerMoney().add(orders.getArtificerMoney()));

//            orders1.setOneArtificerMoney(orders1.getOneArtificerMoney().add(orders.getOneArtificerMoney()));
            orders1.setJjrMoney(orders1.getJjrMoney().add(orders.getJjrMoney()));
            orders1.setShopMoney(orders1.getShopMoney().add(orders.getShopMoney()));
            orders1.setOneUserMoney(orders1.getOneUserMoney().add(orders.getOneUserMoney()));
            orders1.setPingMoney(orders1.getPingMoney().add(orders.getPingMoney()));

            if(orders1.getStatus().equals(6)){
//                                ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders1.getOrdersId()));
//                                massageType = massageTypeService.getById(ordersMassage.getMassageId());
//                                duration=massageType.getDuration();
                String endTime = orders1.getEndTime();
                Date date = DateUtils.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
                calendar=Calendar.getInstance();
                if(date.getTime()>System.currentTimeMillis()){
                    calendar.setTime(date);
                }
                calendar.add(Calendar.MINUTE,orders.getDuration());
                orders1.setEndTime(endTime);
            }
            orders1.setAddPrice(orders.getPrice());
            orders1.setAddMassageTypeId(orders.getMassageTypeId());
            orders1.setAddEntryName(orders.getEntryName());
            ordersDao.updateById(orders1);
            if (flag2) {
                ordersDao.update(null, Wrappers.<Orders>lambdaUpdate()
                        .set(Orders::getWarning, null)
                        .eq(Orders::getOrdersId, orders1.getOrdersId()));
            }
        }else{
            MessageInfo messageInfo=new MessageInfo();
            messageInfo.setState("16");
            messageInfo.setTitle("新订单通知");
            messageInfo.setUserId("0");
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);
            //电话通知 add 2024-06-20 by caolei
            messageService.sendNoticeByCall(artificer.getUserId());
        }

        ordersService.sendMsg(orders);

        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setManipulateType(1);
        userMoneyDetails.setMoney(orders.getTaxiMoney());
        userMoneyDetails.setUserId(orders.getUserId());
        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
        userMoneyDetails.setTitle("服务包下单");
        userMoneyDetails.setType(2);
        userMoneyDetails.setState(2);
        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userMoneyDetails.setBlRole(1);
        userMoneyDetails.setBlFlag(2);
        userMoneyDetailsService.save(userMoneyDetails);

        return Result.success();
    }

    @Override
    public Result submitRealName( Long userId,Integer type,HttpServletRequest request) throws Exception {
        CommonInfo two = commonInfoService.findOne(241);
        double money = Double.parseDouble(two.getValue());
        String generalOrder = getGeneralOrder();
        PayDetails payDetails = new PayDetails();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(generalOrder);
        payDetails.setUserId(userId);
        payDetails.setMoney(money);
        payDetails.setClassify(type);
        payDetails.setType(2);
        payDetailsDao.insert(payDetails);
//        return pays(money, type,userId, generalOrder,request);
        payOrderResult(generalOrder);
        return Result.success();
    }

    @Override
    public Result payCoupon(Long userId, Integer type, Long couponIssueId,HttpServletRequest request) throws Exception {
        CouponIssue couponIssue = couponIssueService.getById(couponIssueId);
        if(couponIssue.getIsLimit()==1){
            //是否限购
            CouponUser couponUser = couponUserService.getOne(new QueryWrapper<CouponUser>().eq("coupon_issue_id", couponIssueId));
            if(couponUser!=null){
                return Result.error("当前优惠券为限购，您已经拥有了！");
            }
            if(couponIssue.getCouponNum()<=0){
                return Result.error("优惠券已经被抢完了！");
            }
        }
        double money = couponIssue.getPrice().doubleValue();
        String generalOrder = getGeneralOrder();
        PayDetails payDetails = payDetailsDao.selectByOrderId(generalOrder);
        if(payDetails==null){
            payDetails  = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(generalOrder);
            payDetails.setUserId(userId);
            payDetails.setMoney(money);
            payDetails.setClassify(type);
            payDetails.setType(4);
            payDetails.setRemark(String.valueOf(couponIssueId));
            payDetailsDao.insert(payDetails);
        }else{
            payDetails.setClassify(type);
            payDetailsDao.updateById(payDetails);
        }
//        return pay(money, type, userId, generalOrder,request);
        payOrderResult(generalOrder);
        return Result.success();
    }

    @Override
    public Result payUserVip(Long userId, Long vipDetailsId, Integer type, HttpServletRequest request) throws Exception {
        VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", vipDetailsId));
        BigDecimal money = vipDetails.getMoney();
        String generalOrder = getGeneralOrder();
        PayDetails payDetails = new PayDetails();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(generalOrder);
        payDetails.setUserId(userId);
        payDetails.setMoney(money.doubleValue());
        payDetails.setClassify(type);
        payDetails.setType(5);
        payDetails.setRemark(String.valueOf(vipDetailsId));
        payDetailsDao.insert(payDetails);
//        return pay(money.doubleValue(), type,userId, generalOrder,request);
        payOrderResult(generalOrder);
        return Result.success();
    }

    @Override
    public Result payUserMoneyArtificer(Long userId,Long artificerId,Long payClassifyId,BigDecimal money,Integer classify,HttpServletRequest request) throws Exception {
        PayDetails payDetails = new PayDetails();
//        if(payClassifyId!=null){
//            PayClassify payClassify = payClassifyService.getById(payClassifyId);
//            money=payClassify.getPrice();
//            payDetails.setRemark(String.valueOf(payClassifyId));
//        }
        String generalOrder = getGeneralOrder();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(generalOrder);
        payDetails.setUserId(userId);
        payDetails.setMoney(money.doubleValue());
        payDetails.setClassify(classify);
        payDetails.setType(6);
        payDetails.setRemark(String.valueOf(artificerId));
        payDetailsDao.insert(payDetails);
//        return pay(money.doubleValue(), classify, userId, generalOrder,request);
        payOrderResult(generalOrder);
        return Result.success();
    }


    /**
     * 微信支付订单生成
     *
     * @param moneys     支付金额 带小数点
     * @param type       类型 1app  2 二维码支付  3小程序 公众号支付
     * @param userId     用户id
     * @param outTradeNo 单号
     * @return
     * @throws Exception
     */
    @Override
    public Result pay(Double moneys, Integer type, Long userId, String outTradeNo,HttpServletRequest request) throws Exception {
        //h5服务域名配置
        CommonInfo oneu = commonInfoService.findOne(19);
        String url;
        if (type == 3) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApi";
        } else if (type == 2 || type == 4) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyMp";
        } else {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notify";
        }
        String currentTimeMillis=(System.currentTimeMillis() / 1000)+"";
        //后台服务名称
        CommonInfo one = commonInfoService.findOne(12);
        log.info("回调地址：" + url);
        Double mul = AmountCalUtils.mul(moneys, 100);
        String money = String.valueOf(mul.intValue());
        String generateNonceStr = WXPayUtil.generateNonceStr();
        WXConfig config = new WXConfig();
        //微信小程序APPID        微信公众号APPID
        if(type==1){
            config.setAppId(commonInfoService.findOne(74).getValue());
        }else if(type == 2 || type == 4){
            config.setAppId(commonInfoService.findOne(5).getValue());
        }else{
            config.setAppId(commonInfoService.findOne(45).getValue());
        }
        //微信商户key
        config.setKey(commonInfoService.findOne(75).getValue());
        //微信商户号mchId
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", generateNonceStr);
        String body = one.getValue();
        data.put("body", body);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        if (type == 1) {
            data.put("trade_type", TRADE_TYPE_APP);
        } else if (type == 2) {
            data.put("trade_type", TRADE_TYPE_JSAPI);
        } else if (type == 3) {
            data.put("trade_type", TRADE_TYPE_JSAPI);
        } else {
            data.put("trade_type", Wap);
            data.put("spbill_create_ip", HttpClientUtil.getIpAddress(request));
        }
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        if(type==3 || type==2){
            UserEntity userEntity = userService.queryByUserId(userId);
            if(type==3){
                if(StringUtils.isNotBlank(userEntity.getOpenId())){
                    data.put("openid", userEntity.getOpenId());
                }
            }else{
                data.put("openid", userEntity.getWxOpenId());
            }
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        for (String key : response.keySet()) {
            log.info("微信支付订单微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
        }
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数

            if (type == 1) {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
                return Result.success().put("data", param);
            } else {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey();
                String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign", sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
                return Result.success().put("data", param);
            }
        }
        return Result.error("获取订单失败");
    }

    private Result pays(Double moneys, Integer type, Long userId, String outTradeNo,HttpServletRequest request) throws Exception {
        //h5服务域名配置
        CommonInfo oneu = commonInfoService.findOne(19);
        String url;
        if (type == 3) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApis";
        } else if (type == 2 || type == 4) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyMps";
        } else {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifys";
        }
        String currentTimeMillis=(System.currentTimeMillis() / 1000)+"";
        //后台服务名称
        CommonInfo one = commonInfoService.findOne(12);
        log.info("回调地址：" + url);
        Double mul = AmountCalUtils.mul(moneys, 100);
        String money = String.valueOf(mul.intValue());
        String generateNonceStr = WXPayUtil.generateNonceStr();
        WXConfig config = new WXConfig();
        //微信小程序APPID        微信公众号APPID
        if(type==1){
            config.setAppId(commonInfoService.findOne(260).getValue());//微信商户key
            config.setKey(commonInfoService.findOne(245).getValue());
            //微信商户号mchId
            config.setMchId(commonInfoService.findOne(246).getValue());
        }else if(type==2 || type == 4){
            config.setAppId(commonInfoService.findOne(5).getValue());
            //微信商户key
            config.setKey(commonInfoService.findOne(75).getValue());
            //微信商户号mchId
            config.setMchId(commonInfoService.findOne(76).getValue());
        }else{
            config.setAppId(commonInfoService.findOne(243).getValue());
            //微信商户key
            config.setKey(commonInfoService.findOne(245).getValue());
            //微信商户号mchId
            config.setMchId(commonInfoService.findOne(246).getValue());
        }

        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", generateNonceStr);
        String body = one.getValue();
        data.put("body", body);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        if (type == 1) {
            data.put("trade_type", TRADE_TYPE_APP);
        } else if (type == 2) {
            data.put("trade_type", TRADE_TYPE_JSAPI);
        } else if (type == 3) {
            data.put("trade_type", TRADE_TYPE_JSAPI);
        } else {
            data.put("trade_type", Wap);
            data.put("spbill_create_ip", HttpClientUtil.getIpAddress(request));
        }
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        if(type==3 || type==2){
            UserEntity userEntity = userService.queryByUserId(userId);
            if(type==3){
                if(StringUtils.isNotBlank(userEntity.getArtificerOpenId())){
                    data.put("openid", userEntity.getArtificerOpenId());
                }
            }else{
                data.put("openid", userEntity.getWxOpenId());
            }
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        for (String key : response.keySet()) {
            log.info("微信支付订单微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
        }
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数

            if (type == 1) {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
                return Result.success().put("data", param);
            } else {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey();
                String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign", sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
                return Result.success().put("data", param);
            }
        }
        return Result.error("获取订单失败");
    }

    public void payOrderResult(String out_trade_no) {
        try {
           //验证签名是否有效，有效则进一步处理

            log.error("验证成功222！！！");
            if (out_trade_no != null) {
                // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                //业务数据持久化
                log.error("订单号！！！" + out_trade_no);
                PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                if (payDetails.getState() == 0) {
                    payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), "");
                    if(payDetails.getType()==1){
                        Orders orders = ordersService.selectOrdersByOrderNo(payDetails.getOrderId());
                        if(orders.getIsSupplement() != null){
                            if(orders.getIsSupplement() == 2){
                                orders.setStatus(6);
                            }else if(orders.getIsSupplement() == 3){
                                orders.setStatus(2);
                            }else{
                                orders.setStatus(9);//用户已支付技师待接单
                            }
                        }else{
                            if(orders.getParentId()!=null && orders.getParentId()!=0){
                                orders.setStatus(6);
                            }else{
                                orders.setStatus(9);//用户已支付技师待接单
                            }
                        }
                        orders.setPayWay(payDetails.getClassify());
                        orders.setPayTime(sdf.format(new Date()));

                        BigDecimal rate = new BigDecimal(100);
                        if(orders.getUserPackageDetailId() != null){
                            OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
                            UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                            UserPackage userPackage = userPackageService.getById(userPackageDetail.getMainId());
                            UserPackageOrder userPackageOrder = userPackageOrderService.getById(userPackage.getOrdersId());
                            Integer packagePayWay = userPackageOrder.getPayWay();
                            if(packagePayWay.equals(5)){
                                rate = new BigDecimal(commonInfoService.findOne(449).getValue());
                            }
                        }
                        orders.setWalletRate(rate);
                        rate = rate.divide(new BigDecimal(100));
                        BigDecimal storageRate = BigDecimal.ONE.subtract(rate);

                        Artificer artificer = artificerService.getById(orders.getArtificerId());
                        BigDecimal taxiMoney = BigDecimal.ZERO;
                        if(orders.getIsSupplement()!=null && orders.getIsSupplement() == 2){
                            taxiMoney = BigDecimal.ZERO;
                        }else{
                            taxiMoney = orders.getTaxiMoney();
                        }
                        if(taxiMoney==null){
                            taxiMoney = BigDecimal.ZERO;
                        }
                        BigDecimal artificerPrice = BigDecimal.ZERO;
                        BigDecimal artificerTaxiPrice = BigDecimal.ZERO;
                        BigDecimal valueStorageDeduction = BigDecimal.ZERO;
                        //查询是否计算出租车扣费
                        String taxi = commonInfoService.findOne(394).getValue();
                        //计算技师出租车收益（按照技师表收益计算）
                        if ("是".equals(taxi)) {
                            //计算技师应该收取的出租车费用
                            artificerTaxiPrice = taxiMoney.multiply(artificer.getRate());
                            artificerTaxiPrice = artificerTaxiPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                            //计算出租车扣款
                            BigDecimal pingTaxiMoney = taxiMoney.subtract(artificerTaxiPrice);
                            //赋值技师出租收款
                            orders.setArtificerTaxiMoney(artificerTaxiPrice);
                            //赋值出租车扣款
                            orders.setPingTaxiMoney(pingTaxiMoney);
                        } else {
                            //平台不扣费 出租车收益全由技师收取
                            artificerTaxiPrice = taxiMoney;
                            orders.setArtificerTaxiMoney(taxiMoney);
                            //设置出租车扣款为0
                            orders.setPingTaxiMoney(BigDecimal.ZERO);
                        }
                        BigDecimal subtract = BigDecimal.ZERO;
                        //用户支付减去通行费用
                        if(orders.getIsSupplement()!=null && orders.getIsSupplement() == 2){
                            subtract = orders.getPayMoney();
                        }else{
                            subtract = orders.getPayMoney().subtract(taxiMoney);
                        }
                        //计算用户收益 ！计算前先减去通行费用再计算技师抽成
                        artificerPrice = subtract.multiply(artificer.getRate());
                        artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                        //储值扣费
                        valueStorageDeduction = artificerPrice.multiply(storageRate);//技师提成中扣除金额
                        valueStorageDeduction = valueStorageDeduction.setScale(2, BigDecimal.ROUND_HALF_UP);
                        orders.setValueStorageDeduction(valueStorageDeduction);

                        //用户收益不含交通费
                        artificerPrice = artificerPrice.multiply(rate);
                        artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

//                        BigDecimal projectBenefits = orders.getProjectBenefits().multiply(rate);
//                        projectBenefits = projectBenefits.setScale(2, BigDecimal.ROUND_HALF_UP);
//                        orders.setProjectBenefits(projectBenefits);
                        orders.setProjectBenefits(artificerPrice);

                        UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
//                        UserEntity oneArtificerUser = userService.queryByInvitationCode(artificerUser.getInviterCode());
//                        BigDecimal oneArtificerMoney = BigDecimal.ZERO;
//                        if (oneArtificerUser != null && oneArtificerUser.getIsAgency() != null && oneArtificerUser.getIsAgency() == 1) {
//                            orders.setOneArtificerUserId(oneArtificerUser.getUserId());
//                            orders.setOneArtificerUserName(oneArtificerUser.getUserName());
//                            oneArtificerMoney = artificerPrice.multiply(oneArtificerUser.getShopRate());
//                            oneArtificerMoney = oneArtificerMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
//                        }
//                        orders.setOneArtificerMoney(oneArtificerMoney);
                        UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
                        BigDecimal jjrMoney = BigDecimal.ZERO;
                        if (jjrUser != null) {
                            orders.setJjrUserId(jjrUser.getUserId());
                            orders.setJjrUserName(jjrUser.getUserName());
                            jjrMoney = jjrMoney.multiply(jjrUser.getBlJjrRate());
                            jjrMoney = jjrMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                        orders.setJjrMoney(jjrMoney);
                        BigDecimal shopMoney = BigDecimal.ZERO;
                        if (artificerUser.getConsortiaId() != null) {
                            Consortia consortia = consortiaService.getById(artificerUser.getConsortiaId());
                            if (consortia != null && consortia.getUserId() != null) {
                                UserEntity consortiaUser = userService.getById(consortia.getUserId());
                                if (consortiaUser != null) {
                                    orders.setConsortiaId(consortia.getConsortiaId());
                                    orders.setShopUserId(consortiaUser.getUserId());
                                    orders.setShopUserName(consortiaUser.getUserName());
                                    shopMoney = artificerPrice.multiply(consortia.getRate());
                                    shopMoney = shopMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                                }
                            }
                        }
                        orders.setShopMoney(shopMoney);
                        UserEntity user = userService.selectUserById(orders.getUserId());
                        UserEntity oneUser = userService.queryByInvitationCode(user.getInviterCode());
                        BigDecimal oneUserMoney = BigDecimal.ZERO;
                        if (oneUser != null && oneUser.getIsAgency() != null && oneUser.getIsAgency() == 1) {
                            orders.setOneUserId(oneUser.getUserId());
                            orders.setOneUserName(oneUser.getUserName());
                            oneUserMoney = artificerPrice.multiply(oneUser.getUserRate());
                            oneUserMoney = oneUserMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                        }
                        orders.setOneUserMoney(oneUserMoney);
//                        artificerPrice = artificerPrice.subtract(oneArtificerMoney);
                        artificerPrice = artificerPrice.subtract(jjrMoney);
                        artificerPrice = artificerPrice.subtract(shopMoney);
                        artificerPrice = artificerPrice.subtract(oneUserMoney);
                        if(orders.getIsSupplement()!=null && orders.getIsSupplement().equals(2)){
                        }else{
                            //用户收益加上通行费用
                            artificerPrice = artificerPrice.add(artificerTaxiPrice);
                        }
                        orders.setArtificerMoney(artificerPrice);
                        orders.setSumArtificerMoney(artificerPrice);

                        //平台扣款
                        BigDecimal pingMoney = orders.getPayMoney();
                        pingMoney = pingMoney.subtract(artificerPrice);
                        pingMoney = pingMoney.subtract(shopMoney);
//                        pingMoney = pingMoney.subtract(oneArtificerMoney);
                        pingMoney = pingMoney.subtract(jjrMoney);
                        pingMoney = pingMoney.subtract(oneUserMoney);
                        orders.setPingMoney(pingMoney);

                        ordersService.updateById(orders);

                        if(orders.getParentId()!=null && orders.getParentId()!=0){
                            Calendar calendar=Calendar.getInstance();
//                            String value1 = commonInfoService.findOne(395).getValue();
//                            OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
//                            MassageType massageType = massageTypeService.getById(ordersMassage.getMassageId());
//                            Integer duration=massageType.getDuration();
//                            if("是".equals(value1)){
//                                ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getParentId()).last(" order by artificer_time_id desc limit 1 "));
//                                String serveTime = artificerTime.getArtificerDate()+" "+artificerTime.getArtificerTime();
//                                String value = commonInfoService.findOne(392).getValue();
//                                int minute = Integer.parseInt(value);
//                                int i=1;
//                                if(duration%minute==0){
//                                    i=duration/minute;
//                                }else{
//                                    i=duration/minute;
//                                    i++;
//                                }
//
//                                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                                Date parse = sdf1.parse(serveTime);
//
//                                calendar.setTime(parse);
//                                for(int j=0;j<i;j++){
//                                    calendar.add(Calendar.MINUTE,minute);
//                                    String format = sdf1.format(calendar.getTime());
//                                    String date = format.substring(0, 10);
//                                    String time = format.substring(11, 16);
//                                    artificerTime=new ArtificerTime();
//                                    artificerTime.setArtificerId(orders.getArtificerId());
//                                    artificerTime.setArtificerDate(date);
//                                    artificerTime.setArtificerTime(time);
//                                    artificerTime.setClassify(1);
//                                    artificerTime.setOrdersId(orders.getParentId());
//                                    artificerTime.setCreateTime(DateUtils.format(new Date()));
//                                    artificerTimeService.save(artificerTime);
//                                }
//                            }

                            Orders orders1 = ordersDao.selectById(orders.getParentId());
                            if(orders1.getAddNum()==null){
                                orders1.setAddNum(1);
                            }else{
                                orders1.setAddNum(orders1.getAddNum()+1);
                            }
                            //获取加钟项目的时长
                            if(orders1.getAddTime()!=null){
                                orders1.setAddTime(orders1.getAddTime()+orders.getAddTime());
                            }else{
                                orders1.setAddTime(orders.getAddTime());
                            }
                            boolean flag2 = false;
                            if (StringUtils.isNotBlank(orders1.getEndTime())) {
                                Calendar calendar2 = Calendar.getInstance();
                                Date date = DateUtils.stringToDate(orders1.getEndTime(), "yyyy-MM-dd HH:mm:ss");
                                calendar2.setTime(date);
                                calendar2.add(Calendar.MINUTE, orders.getAddTime());
                                orders1.setEndTime(DateUtils.format(calendar2.getTime()));
                                flag2 = true;
                            }
                            if(orders1.getAddMoney()!=null){
                                orders1.setAddMoney(orders1.getAddMoney().add(orders.getPayMoney()));
                                orders1.setAddArtificerMoney(orders1.getAddArtificerMoney().add(orders.getArtificerMoney()));
                            }else{
                                orders1.setAddMoney(orders.getPayMoney());
                                orders1.setAddArtificerMoney(orders.getArtificerMoney());
                            }
                            orders1.setSumMoney(orders1.getSumMoney().add(orders.getPayMoney()));
                            orders1.setSumArtificerMoney(orders1.getSumArtificerMoney().add(orders.getArtificerMoney()));

//                            orders1.setOneArtificerMoney(orders1.getOneArtificerMoney().add(orders.getOneArtificerMoney()));
                            orders1.setJjrMoney(orders1.getJjrMoney().add(orders.getJjrMoney()));
                            orders1.setShopMoney(orders1.getShopMoney().add(orders.getShopMoney()));
                            orders1.setOneUserMoney(orders1.getOneUserMoney().add(orders.getOneUserMoney()));
                            orders1.setPingMoney(orders1.getPingMoney().add(orders.getPingMoney()));

                            if(orders1.getStatus().equals(6)){
//                                ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders1.getOrdersId()));
//                                massageType = massageTypeService.getById(ordersMassage.getMassageId());
//                                duration=massageType.getDuration();
                                String endTime = orders1.getEndTime();
                                Date date = DateUtils.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
                                calendar=Calendar.getInstance();
                                if(date.getTime()>System.currentTimeMillis()){
                                    calendar.setTime(date);
                                }
                                calendar.add(Calendar.MINUTE,orders.getDuration());
                                orders1.setEndTime(endTime);
                            }
                            orders1.setAddPrice(orders.getPrice());
                            orders1.setAddMassageTypeId(orders.getMassageTypeId());
                            orders1.setAddEntryName(orders.getEntryName());
                            ordersDao.updateById(orders1);
                            if (flag2) {
                                ordersDao.update(null, Wrappers.<Orders>lambdaUpdate()
                                        .set(Orders::getWarning, null)
                                        .eq(Orders::getOrdersId, orders1.getOrdersId()));
                            }
                        }else{
                            MessageInfo messageInfo=new MessageInfo();
                            messageInfo.setState("16");
                            messageInfo.setTitle("新订单通知");
                            messageInfo.setUserId("0");
                            messageInfo.setIsSee("0");
                            messageService.saveBody(messageInfo);
                            //电话通知 add 2024-06-20 by caolei
                            messageService.sendNoticeByCall(artificer.getUserId());
                        }

                        ordersService.sendMsg(orders);

                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setManipulateType(1);
                        if(orders.getUserPackageDetailId() != null){
                            userMoneyDetails.setMoney(orders.getTaxiMoney());
                        }else{
                            userMoneyDetails.setMoney(orders.getPayMoney());
                        }
                        userMoneyDetails.setUserId(orders.getUserId());
                        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
                        userMoneyDetails.setTitle("支付订单");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(2);
                        userMoneyDetailsService.save(userMoneyDetails);

                    }else if(payDetails.getType()==2){
                        //缴纳保证金
                        Double cashDeposit = payDetails.getMoney();
                        Long userId = payDetails.getUserId();
                        userMoneyDao.updateCashDeposit(1, userId, cashDeposit);
                        UserEntity userEntity = userService.selectUserById(userId);
                        userEntity.setIsCashDeposit(2);
                        userService.updateById(userEntity);
                        //交保证金的记录
                        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                        userMoneyDetails.setUserId(userId);
                        userMoneyDetails.setTitle("缴纳保证金");
                        userMoneyDetails.setContent("已缴纳保证金："+cashDeposit+"元");
//                                userMoneyDetails.setType(1);
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setMoney(BigDecimal.valueOf(cashDeposit));
                        userMoneyDetails.setClassify(1);
                        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        userMoneyDetails.setBlRole(2);
                        userMoneyDetails.setBlFlag(2);
                        userMoneyDetailsService.save(userMoneyDetails);
                    }else if(payDetails.getType()==3){

                        PayClassify payClassify = payClassifyService.getById(Long.parseLong(payDetails.getRemark()));
                        userMoneyDao.updateMayMoney(1, payDetails.getUserId(), payClassify.getMoney().doubleValue());
                        //查询用户当前余额
                        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(payDetails.getUserId());
                        //钱包明细需要做调整2条记录，充值时钱包类型增加金额，现金类型减少金额
                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney.getMoney());
                        userMoneyDetails.setUserId(payDetails.getUserId());
                        userMoneyDetails.setTitle("支付宝充值");
                        userMoneyDetails.setContent("支付宝花费："+payClassify.getPrice()+",钱包增加余额："+payClassify.getMoney());
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setMoney(payClassify.getMoney());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        userMoneyDetails.setCreateTime(sdf.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails);
                        userMoneyDetails.setTitle("支付宝充值");
                        userMoneyDetails.setContent("支付宝花费:"+payClassify.getPrice());
                        userMoneyDetails.setMoney(payClassify.getPrice());
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(2);
                        userMoneyDetailsService.save(userMoneyDetails);

                        List<PayClassifyDetail> list = payClassifyDetailService.findList(payClassify.getPayClassifyId());
                        if(list!=null && list.size()>0){
                            for(int m=0;m<list.size();m++){
                                PayClassifyDetail pcd = list.get(m);
                                Coupon coupon = pcd.getCoupon();
                                for(int i=0;i<pcd.getGiveNum();i++){
                                    Integer endDate = coupon.getEndDate();
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.add(Calendar.DATE, endDate);
                                    calendar.add(Calendar.DATE, 1);
                                    Date date = calendar.getTime();
                                    String expirationTime = sdf.format(date);
                                    CouponUser couponUser = new CouponUser();
                                    couponUser.setUserId(payDetails.getUserId());
                                    couponUser.setCouponName(coupon.getCouponName());
                                    couponUser.setCouponPicture(coupon.getCouponPicture());
                                    couponUser.setCreateTime(DateUtils.format(new Date()));
                                    couponUser.setExpirationTime(expirationTime);
                                    couponUser.setMinMoney(coupon.getMinMoney());
                                    couponUser.setMoney(coupon.getMoney());
                                    couponUser.setClassifyId(coupon.getClassifyId());
                                    couponUser.setStatus(0);
                                    couponUserService.save(couponUser);
                                }
                            }
                        }

                        //用户在充值余额时，指定技师ID，则充值成功后给指定技师增加业绩，入userRecharge表
                        if(payDetails.getArtificerId()!=null){
                            UserRecharge o = new UserRecharge();
                            o.setUserRecharge(payClassify.getPrice());
                            o.setType("2");
                            o.setUserId(payDetails.getUserId());
                            o.setArtificerId(payDetails.getArtificerId());
                            o.setOrdersId(payDetails.getMassageOrdersId());
                            o.setCreateTime(DateUtils.format(new Date()));
                            userRechargeDao.insert(o);
                        }

                    }else if(payDetails.getType()==4){
                        Long couponIssueId = Long.parseLong(payDetails.getRemark());
                        Long userId=payDetails.getUserId();
                        CouponIssue couponIssue = couponIssueService.getById(couponIssueId);
                        String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                        String[] couponIds = couponIssue.getCouponIds().split(",");
                        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                        userMoneyDetails.setClassify(1);
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                        userMoneyDetails.setUserId(payDetails.getUserId());
                        userMoneyDetails.setTitle("微信购买优惠券，券包："+couponIssue.getCouponIssueName());
                        userMoneyDetails.setContent("购买优惠券费用："+payDetails.getMoney());
                        userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(2);
                        userMoneyDetailsService.save(userMoneyDetails);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        for(String couponId:couponIds){
                            Coupon coupon = couponService.getById(Long.parseLong(couponId));
                            Integer endDate = coupon.getEndDate();
                            Calendar calendar = Calendar.getInstance();
                            calendar.add(Calendar.DATE, endDate);
                            calendar.add(Calendar.DATE, 1);
                            Date date = calendar.getTime();
                            String expirationTime = simpleDateFormat.format(date);
                            CouponUser couponUser=new CouponUser();
                            couponUser.setUserId(userId);
                            couponUser.setCouponName(coupon.getCouponName());
                            couponUser.setCouponPicture(coupon.getCouponPicture());
                            couponUser.setCreateTime(createTime);
                            couponUser.setExpirationTime(expirationTime);
                            couponUser.setMinMoney(coupon.getMinMoney());
                            couponUser.setMoney(coupon.getMoney());
                            couponUser.setStatus(0);
                            couponUserService.save(couponUser);
                        }
                        couponIssue.setCouponNum(couponIssue.getCouponNum()-1);
                        couponIssueService.updateById(couponIssue);
                    }else if(payDetails.getType()==5){
                        BigDecimal money=BigDecimal.valueOf(payDetails.getMoney());
                        Long userId=payDetails.getUserId();
                        VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", Long.parseLong(payDetails.getRemark())));
                        //查看用户是否是会员
                        UserVip userVip = userVipDao.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
                        Calendar cal = Calendar.getInstance();
                        if(userVip!=null){
                            Date endDate = null;
                            try {
                                endDate = sdf.parse(userVip.getEndTime());
                                if (endDate != null && System.currentTimeMillis() < (endDate.getTime())) {
                                    cal.setTime(endDate);
                                }
                            } catch (Exception e) {
                                e.getMessage();
                            }
                        }else{
                            userVip=new UserVip();
                            //设置会员类型
                            userVip.setVipNameType(vipDetails.getVipNameType());
                            //设置开通会员的用户id
                            userVip.setUserId(userId);
                            //设置会员的购买时间
                            userVip.setCreateTime(sdf.format(new Date()));
                        }

                        MessageInfo messageInfo=new MessageInfo();
                        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                        userMoneyDetails.setMoney(money);
                        userMoneyDetails.setUserId(userId);

                        if ((vipDetails.getVipNameType().equals(0))) {
                            //月
                            userMoneyDetails.setContent("微信开通月卡会员");
                            messageInfo.setContent("微信开通月卡会员");
                            cal.add(Calendar.MONTH, 1);
                        } else if ((vipDetails.getVipNameType()).equals(1)) {
                            //季
                            userMoneyDetails.setContent("微信开通季卡会员");
                            messageInfo.setContent("微信开通季卡会员");
                            cal.add(Calendar.MONTH, 3);
                        } else {
                            //年
                            userMoneyDetails.setContent("微信开通年费会员");
                            messageInfo.setContent("微信开通年费会员");
                            cal.add(Calendar.YEAR, 1);
                        }

                        userVip.setEndTime(sdf.format(cal.getTime()));
                        if(userVip.getVipId()!=null){
                            userVipDao.updateById(userVip);
                        }else{
                            userVipDao.insert(userVip);
                        }
                        userMoneyDetails.setTitle("开通会员");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setCreateTime(sdf.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(2);
                        userMoneyDetailsService.save(userMoneyDetails);
                        UserEntity userEntity = userService.selectUserById(userId);
                        messageInfo.setTitle("开通会员");
                        messageInfo.setState(String.valueOf(4));
                        messageInfo.setUserName(userEntity.getUserName());
                        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                        messageInfo.setCreateAt(sdf.format(new Date()));
                        messageInfo.setIsSee("0");
                        messageService.saveBody(messageInfo);
                        if(StringUtil.isNotBlank(userEntity.getClientid())){
                            userService.pushToSingle(messageInfo.getTitle(),messageInfo.getContent(),userEntity.getClientid());
                        }

                    }else if(payDetails.getType()==6){
                        double money=payDetails.getMoney();
                        long artificerId = Long.parseLong(payDetails.getRemark());
                        Artificer artificer = artificerService.getById(artificerId);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        //用户流水
                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setClassify(8);
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setUserId(payDetails.getUserId());
                        userMoneyDetails.setTitle("微信给技师打赏");
                        userMoneyDetails.setContent("使用微信给指定技师“"+artificer.getArtificerName()+"”打赏:"+money);
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setMoney(BigDecimal.valueOf(money));
                        userMoneyDetails.setArtificerId(artificerId);
                        userMoneyDetails.setCreateTime(sdf.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(2);
                        userMoneyDetailsService.save(userMoneyDetails);
                        //技师流水
                        UserEntity userEntity = userService.queryByUserId(artificer.getUserId());
                        userMoneyDao.updateMayMoney(1, userEntity.getUserId(), money);
                        //查询技师当前余额
                        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userEntity.getUserId());
                        UserMoneyDetails userMoneyDetails2 = new UserMoneyDetails();
                        //插入余额
                        userMoneyDetails2.setBalance(userNowMoney.getMoney());
                        userMoneyDetails2.setManipulateType(2);
                        userMoneyDetails2.setClassify(8);
                        userMoneyDetails2.setUserId(userEntity.getUserId());
                        userMoneyDetails2.setTitle("用户微信打赏");
                        userMoneyDetails2.setContent("来自用户“"+userEntity.getUserName()+"”微信打赏:"+money);
                        userMoneyDetails2.setType(1);
                        userMoneyDetails2.setState(2);
                        userMoneyDetails2.setMoney(BigDecimal.valueOf(money));
                        userMoneyDetails2.setCreateTime(sdf.format(new Date()));
                        userMoneyDetails2.setBlRole(2);
                        userMoneyDetails2.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails2);
                    }else if(payDetails.getType()==7){
                        //服务包下单，分单
                        UserPackageOrder orders = userPackageOrderDao.getByNo(out_trade_no);
                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setUserId(orders.getUserId());
                        userMoneyDetails.setMoney(orders.getPayMoney());
                        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
                        userMoneyDetails.setTitle("支付服务包订单");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setCreateTime(sdf.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails);

                        orders.setStatus(1);
                        orders.setPayWay(payDetails.getClassify());
                        orders.setPayTime(sdf.format(new Date()));
                        userPackageOrderDao.updateStatus(orders);

                        //获取订单-服务包映射关系列表
                        List<UserPackageOrdersMapping> mappingList = userPackageOrdersMappingService.findListByOrdersId(orders.getOrdersId());
                        for (UserPackageOrdersMapping ordersPackage : mappingList) {
                            int quantity = ordersPackage.getNum();
                            MassagePackage massagePackage = massagePackageService.getById(ordersPackage.getPackageId());
                            //修改服务包销量
                            int sales = massagePackage.getSales();
                            sales = sales+quantity;
                            massagePackage.setSales(sales);
                            massagePackageService.updateSales(massagePackage);
                            for(int i=0;i<quantity;i++){
                                //拆分插入用户服务包
                                UserPackage userPackage = new UserPackage();
                                userPackage.setUserId(orders.getUserId());
                                userPackage.setPackageId(massagePackage.getId());
                                userPackage.setOrdersId(orders.getOrdersId());
                                userPackage.setOrdersNo(orders.getOrdersNo());
                                userPackage.setCreateTime(sdf.format(new Date()));
                                userPackage.setTitle(massagePackage.getTitle());
                                userPackage.setType(massagePackage.getType());
                                userPackage.setOldPrice(massagePackage.getOldPrice());
                                userPackage.setPrice(massagePackage.getPrice());
                                userPackage.setPackageImg(massagePackage.getPackageImg());
                                userPackage.setContent(massagePackage.getContent());
                                userPackage.setContentImg(massagePackage.getContentImg());
                                userPackage.setLabels(massagePackage.getLabels());
                                userPackage.setCity(massagePackage.getCity());
                                userPackage.setClassifyId(massagePackage.getClassifyId());
                                userPackage.setLevel(massagePackage.getLevel());
                                userPackageService.insert(userPackage);
                                Long mainId = userPackage.getId();
                                //拆分插入用户服务器项目详情
                                UserPackageDetail userPackageDetail = new UserPackageDetail();
                                userPackageDetail.setMainId(ordersPackage.getPackageId());
                                List<UserPackageDetail> userPackageDetailList = userPackageDetailService.findMassagePackageDetails(userPackageDetail);
                                if(userPackageDetailList.size()>0){
                                    for(int j=0;j<userPackageDetailList.size();j++){
                                        UserPackageDetail upd = userPackageDetailList.get(j);
                                        upd.setMainId(mainId);
                                        upd.setCreateTime(sdf.format(new Date()));
                                        upd.setLevel(massagePackage.getLevel());
                                        int serviceCount = upd.getServiceCount();
                                        for(int k=0;k<serviceCount;k++){
                                            userPackageDetailService.insert(upd);
                                            MassageType massageType = massageTypeService.getById(upd.getMassageTypeId());
                                            massageType.setSales(massageType.getSales()+1);
                                            massageTypeService.updateById(massageType);
                                        }
                                    }
                                }
                            }
                        }
                    }else if(payDetails.getType()==8) {
                        //服务包下单，分单
                        UserPackageOrder orders = userPackageOrderDao.getByNo(out_trade_no);
                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setUserId(orders.getUserId());
                        userMoneyDetails.setMoney(orders.getPayMoney());
                        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
                        userMoneyDetails.setTitle("支付团购订单");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setCreateTime(sdf.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails);
                        orders.setStatus(4);//团购中
                        orders.setPayWay(payDetails.getClassify());
                        orders.setPayTime(sdf.format(new Date()));
                        userPackageOrderDao.updateStatus(orders);

                        //获取支付已支付的数量是否满足此次团购人数，是则完成此次拼团，并将商品发送给客户
                        int buyGroupNum = 0;
                        int groupNum = 0;
                        List<UserPackageOrder> list = userPackageOrderDao.getActivityOrderListByGroupNo(orders.getGroupNo(),null);
                        if(list.size()>0){
                            for(UserPackageOrder userPackageOrder : list) {
                                if (userPackageOrder.getStatus().equals(1) || userPackageOrder.getStatus().equals(4)) {
                                    buyGroupNum++;
                                }
                            }
                        }
                        MassagePackage massagePackage = null;
                        List<UserPackageOrdersMapping> mappingList = userPackageOrdersMappingService.findListByOrdersId(orders.getOrdersId());
                        if(mappingList.size()>0){
                            Long packageId = mappingList.get(0).getPackageId();
                            massagePackage = massagePackageService.getById(packageId);
                            groupNum = massagePackage.getGroupNum();
                        }
                        if(buyGroupNum>0 && groupNum>0 && buyGroupNum>=groupNum){
                            for(UserPackageOrder userPackageOrder : list) {
                                if (userPackageOrder.getStatus().equals(1) || userPackageOrder.getStatus().equals(4)) {
                                    //删除单据防止重复数据
                                    List<UserPackage> userPackageList = userPackageService.findList(userPackageOrder.getOrdersId());
                                    if(userPackageList.size()>0){
                                        for(UserPackage userPackage : userPackageList){
                                            userPackageService.removeById(userPackage.getId());
                                            userPackageDetailService.deleteDetailByMain(userPackage.getId());
                                        }
                                    }
                                    //插入单据
                                    List<UserPackageOrdersMapping> packageOrderMappingList = userPackageOrdersMappingService.findListByOrdersId(userPackageOrder.getOrdersId());
                                    for (UserPackageOrdersMapping ordersPackage : packageOrderMappingList) {
                                        int quantity = ordersPackage.getNum();
                                        for(int i=0;i<quantity;i++){
                                            //拆分插入用户团购
                                            UserPackage userPackage = new UserPackage();
                                            userPackage.setUserId(userPackageOrder.getUserId());
                                            userPackage.setPackageId(massagePackage.getId());
                                            userPackage.setOrdersId(userPackageOrder.getOrdersId());
                                            userPackage.setOrdersNo(userPackageOrder.getOrdersNo());
                                            userPackage.setCreateTime(DateUtils.format(new Date()));
                                            userPackage.setTitle(massagePackage.getTitle());
                                            userPackage.setType(massagePackage.getType());
                                            userPackage.setOldPrice(massagePackage.getOldPrice());
                                            userPackage.setPrice(massagePackage.getPrice());
                                            userPackage.setPackageImg(massagePackage.getPackageImg());
                                            userPackage.setContent(massagePackage.getContent());
                                            userPackage.setContentImg(massagePackage.getContentImg());
                                            userPackage.setLabels(massagePackage.getLabels());
                                            userPackage.setCity(massagePackage.getCity());
                                            userPackage.setClassifyId(massagePackage.getClassifyId());
                                            userPackage.setLevel(massagePackage.getLevel());
                                            userPackageService.insert(userPackage);
                                            Long mainId = userPackage.getId();
                                            //拆分插入用户服务器项目详情
                                            UserPackageDetail userPackageDetail = new UserPackageDetail();
                                            userPackageDetail.setMainId(ordersPackage.getPackageId());
                                            List<UserPackageDetail> userPackageDetailList = userPackageDetailService.findMassagePackageDetails(userPackageDetail);
                                            if(userPackageDetailList.size()>0){
                                                for(int j=0;j<userPackageDetailList.size();j++){
                                                    UserPackageDetail upd = userPackageDetailList.get(j);
                                                    upd.setMainId(mainId);
                                                    upd.setCreateTime(DateUtils.format(new Date()));
                                                    upd.setLevel(massagePackage.getLevel());
                                                    int serviceCount = upd.getServiceCount();
                                                    for(int k=0;k<serviceCount;k++){
                                                        userPackageDetailService.insert(upd);
                                                        MassageType massageType = massageTypeService.getById(upd.getMassageTypeId());
                                                        massageType.setSales(massageType.getSales()+1);
                                                        massageTypeService.updateById(massageType);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //完成团购
                            UserPackageOrder packageOrder = new UserPackageOrder();
                            packageOrder.setGroupNo(orders.getGroupNo());
                            packageOrder.setStatus(1);
                            userPackageOrderDao.updateStatus(packageOrder);
                            //修改团购销量
                            int sales = massagePackage.getSales();
                            sales = sales+1;
                            massagePackage.setSales(sales);
                            massagePackageService.updateSales(massagePackage);
                        }
                    }
                }
                System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
            } else {
                System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
            }


        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
        }

    }

    @Override
    public String payBack(String resXml, Integer type) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("进入回调了！！！");
        if(type==1){
            config.setAppId(commonInfoService.findOne(74).getValue());
        }else if(type==2){
            config.setAppId(commonInfoService.findOne(5).getValue());
        }else{
            config.setAppId(commonInfoService.findOne(45).getValue());
        }
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                log.error("验证成功！！！");
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    log.error("验证成功222！！！");
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        log.error("订单号！！！" + out_trade_no);
                        PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                        if (payDetails.getState() == 0) {
                            payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), "");
                            if(payDetails.getType()==1){
                                Orders orders = ordersService.selectOrdersByOrderNo(payDetails.getOrderId());
                                if(orders.getIsSupplement() != null){
                                    if(orders.getIsSupplement() == 2){
                                        orders.setStatus(6);
                                    }else if(orders.getIsSupplement() == 3){
                                        orders.setStatus(2);
                                    }else{
                                        orders.setStatus(9);//用户已支付技师待接单
                                    }
                                }else{
                                    if(orders.getParentId()!=null && orders.getParentId()!=0){
                                        orders.setStatus(6);
                                    }else{
                                        orders.setStatus(9);//用户已支付技师待接单
                                    }
                                }
                                orders.setPayWay(payDetails.getClassify());
                                orders.setPayTime(sdf.format(new Date()));

                                BigDecimal rate = new BigDecimal(100);
                                if(orders.getUserPackageDetailId() != null){
                                    OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
                                    UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                                    UserPackage userPackage = userPackageService.getById(userPackageDetail.getMainId());
                                    UserPackageOrder userPackageOrder = userPackageOrderService.getById(userPackage.getOrdersId());
                                    Integer packagePayWay = userPackageOrder.getPayWay();
                                    if(packagePayWay.equals(5)){
                                        rate = new BigDecimal(commonInfoService.findOne(449).getValue());
                                    }
                                }
                                orders.setWalletRate(rate);
                                rate = rate.divide(new BigDecimal(100));
                                BigDecimal storageRate = BigDecimal.ONE.subtract(rate);

                                Artificer artificer = artificerService.getById(orders.getArtificerId());
                                BigDecimal taxiMoney = BigDecimal.ZERO;
                                if(orders.getIsSupplement()!=null && orders.getIsSupplement() == 2){
                                    taxiMoney = BigDecimal.ZERO;
                                }else{
                                    taxiMoney = orders.getTaxiMoney();
                                }
                                if(taxiMoney==null){
                                    taxiMoney = BigDecimal.ZERO;
                                }
                                BigDecimal artificerPrice = BigDecimal.ZERO;
                                BigDecimal artificerTaxiPrice = BigDecimal.ZERO;
                                BigDecimal valueStorageDeduction = BigDecimal.ZERO;
                                //查询是否计算出租车扣费
                                String taxi = commonInfoService.findOne(394).getValue();
                                //计算技师出租车收益（按照技师表收益计算）
                                if ("是".equals(taxi)) {
                                    //计算技师应该收取的出租车费用
                                    artificerTaxiPrice = taxiMoney.multiply(artificer.getRate());
                                    artificerTaxiPrice = artificerTaxiPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    //计算出租车扣款
                                    BigDecimal pingTaxiMoney = taxiMoney.subtract(artificerTaxiPrice);
                                    //赋值技师出租收款
                                    orders.setArtificerTaxiMoney(artificerTaxiPrice);
                                    //赋值出租车扣款
                                    orders.setPingTaxiMoney(pingTaxiMoney);
                                } else {
                                    //平台不扣费 出租车收益全由技师收取
                                    artificerTaxiPrice = taxiMoney;
                                    orders.setArtificerTaxiMoney(taxiMoney);
                                    //设置出租车扣款为0
                                    orders.setPingTaxiMoney(BigDecimal.ZERO);
                                }
                                BigDecimal subtract = BigDecimal.ZERO;
                                //用户支付减去通行费用
                                if(orders.getIsSupplement()!=null && orders.getIsSupplement() == 2){
                                    subtract = orders.getPayMoney();
                                }else{
                                    subtract = orders.getPayMoney().subtract(taxiMoney);
                                }
                                //计算用户收益 ！计算前先减去通行费用再计算技师抽成
                                artificerPrice = subtract.multiply(artificer.getRate());
                                artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                                //储值扣费
                                valueStorageDeduction = artificerPrice.multiply(storageRate);//技师提成中扣除金额
                                valueStorageDeduction = valueStorageDeduction.setScale(2, BigDecimal.ROUND_HALF_UP);
                                orders.setValueStorageDeduction(valueStorageDeduction);

                                //用户收益不含交通费
                                artificerPrice = artificerPrice.multiply(rate);
                                artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

//                                BigDecimal projectBenefits = orders.getProjectBenefits().multiply(rate);
//                                projectBenefits = projectBenefits.setScale(2, BigDecimal.ROUND_HALF_UP);
//                                orders.setProjectBenefits(projectBenefits);
                                orders.setProjectBenefits(artificerPrice);

                                UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
//                                UserEntity oneArtificerUser = userService.queryByInvitationCode(artificerUser.getInviterCode());
//                                BigDecimal oneArtificerMoney = BigDecimal.ZERO;
//                                if (oneArtificerUser != null && oneArtificerUser.getIsAgency() != null && oneArtificerUser.getIsAgency() == 1) {
//                                    orders.setOneArtificerUserId(oneArtificerUser.getUserId());
//                                    orders.setOneArtificerUserName(oneArtificerUser.getUserName());
//                                    oneArtificerMoney = artificerPrice.multiply(oneArtificerUser.getShopRate());
//                                    oneArtificerMoney = oneArtificerMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
//                                }
//                                orders.setOneArtificerMoney(oneArtificerMoney);
                                UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
                                BigDecimal jjrMoney = BigDecimal.ZERO;
                                if (jjrUser != null) {
                                    orders.setJjrUserId(jjrUser.getUserId());
                                    orders.setJjrUserName(jjrUser.getUserName());
                                    jjrMoney = jjrMoney.multiply(jjrUser.getBlJjrRate());
                                    jjrMoney = jjrMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                                }
                                orders.setJjrMoney(jjrMoney);
                                BigDecimal shopMoney = BigDecimal.ZERO;
                                if (artificerUser.getConsortiaId() != null) {
                                    Consortia consortia = consortiaService.getById(artificerUser.getConsortiaId());
                                    if (consortia != null && consortia.getUserId() != null) {
                                        UserEntity consortiaUser = userService.getById(consortia.getUserId());
                                        if (consortiaUser != null) {
                                            orders.setConsortiaId(consortia.getConsortiaId());
                                            orders.setShopUserId(consortiaUser.getUserId());
                                            orders.setShopUserName(consortiaUser.getUserName());
                                            shopMoney = artificerPrice.multiply(consortia.getRate());
                                            shopMoney = shopMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                                        }
                                    }
                                }
                                orders.setShopMoney(shopMoney);
                                UserEntity user = userService.selectUserById(orders.getUserId());
                                UserEntity oneUser = userService.queryByInvitationCode(user.getInviterCode());
                                BigDecimal oneUserMoney = BigDecimal.ZERO;
                                if (oneUser != null && oneUser.getIsAgency() != null && oneUser.getIsAgency() == 1) {
                                    orders.setOneUserId(oneUser.getUserId());
                                    orders.setOneUserName(oneUser.getUserName());
                                    oneUserMoney = artificerPrice.multiply(oneUser.getUserRate());
                                    oneUserMoney = oneUserMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                                }
                                orders.setOneUserMoney(oneUserMoney);
//                                artificerPrice = artificerPrice.subtract(oneArtificerMoney);
                                artificerPrice = artificerPrice.subtract(jjrMoney);
                                artificerPrice = artificerPrice.subtract(shopMoney);
                                artificerPrice = artificerPrice.subtract(oneUserMoney);
                                if(orders.getIsSupplement()!=null && orders.getIsSupplement().equals(2)){
                                }else{
                                    //用户收益加上通行费用
                                    artificerPrice = artificerPrice.add(artificerTaxiPrice);
                                }
                                orders.setArtificerMoney(artificerPrice);
                                orders.setSumArtificerMoney(artificerPrice);

                                //平台扣款
                                BigDecimal pingMoney = orders.getPayMoney();
                                pingMoney = pingMoney.subtract(artificerPrice);
                                pingMoney = pingMoney.subtract(shopMoney);
//                                pingMoney = pingMoney.subtract(oneArtificerMoney);
                                pingMoney = pingMoney.subtract(jjrMoney);
                                pingMoney = pingMoney.subtract(oneUserMoney);
                                orders.setPingMoney(pingMoney);

                                ordersService.updateById(orders);

                                if(orders.getParentId()!=null && orders.getParentId()!=0){
                                    Calendar calendar=Calendar.getInstance();
//                                    String value1 = commonInfoService.findOne(395).getValue();
//                                    OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
//                                    MassageType massageType = massageTypeService.getById(ordersMassage.getMassageId());
//                                    Integer duration=massageType.getDuration();
//                                    if("是".equals(value1)){
//                                        ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getParentId()).last(" order by artificer_time_id desc limit 1 "));
//                                        String serveTime = artificerTime.getArtificerDate()+" "+artificerTime.getArtificerTime();
//                                        String value = commonInfoService.findOne(392).getValue();
//                                        int minute = Integer.parseInt(value);
//                                        int i=1;
//                                        if(duration%minute==0){
//                                            i=duration/minute;
//                                        }else{
//                                            i=duration/minute;
//                                            i++;
//                                        }
//
//                                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                                        Date parse = sdf1.parse(serveTime);
//
//                                        calendar.setTime(parse);
//                                        for(int j=0;j<i;j++){
//                                            calendar.add(Calendar.MINUTE,minute);
//                                            String format = sdf1.format(calendar.getTime());
//                                            String date = format.substring(0, 10);
//                                            String time = format.substring(11, 16);
//                                            artificerTime=new ArtificerTime();
//                                            artificerTime.setArtificerId(orders.getArtificerId());
//                                            artificerTime.setArtificerDate(date);
//                                            artificerTime.setArtificerTime(time);
//                                            artificerTime.setClassify(1);
//                                            artificerTime.setOrdersId(orders.getParentId());
//                                            artificerTime.setCreateTime(DateUtils.format(new Date()));
//                                            artificerTimeService.save(artificerTime);
//                                        }
//                                    }

                                    Orders orders1 = ordersDao.selectById(orders.getParentId());
                                    if(orders1.getAddNum()==null){
                                        orders1.setAddNum(1);
                                    }else{
                                        orders1.setAddNum(orders1.getAddNum()+1);
                                    }
                                    //获取加钟项目的时长
                                    if(orders1.getAddTime()!=null){
                                        orders1.setAddTime(orders1.getAddTime()+orders.getAddTime());
                                    }else{
                                        orders1.setAddTime(orders.getAddTime());
                                    }
                                    boolean flag2 = false;
                                    if (StringUtils.isNotBlank(orders1.getEndTime())) {
                                        Calendar calendar2 = Calendar.getInstance();
                                        Date date = DateUtils.stringToDate(orders1.getEndTime(), "yyyy-MM-dd HH:mm:ss");
                                        calendar2.setTime(date);
                                        calendar2.add(Calendar.MINUTE, orders.getAddTime());
                                        orders1.setEndTime(DateUtils.format(calendar2.getTime()));
                                        flag2 = true;
                                    }
                                    if(orders1.getAddMoney()!=null){
                                        orders1.setAddMoney(orders1.getAddMoney().add(orders.getPayMoney()));
                                        orders1.setAddArtificerMoney(orders1.getAddArtificerMoney().add(orders.getArtificerMoney()));
                                    }else{
                                        orders1.setAddMoney(orders.getPayMoney());
                                        orders1.setAddArtificerMoney(orders.getArtificerMoney());
                                    }
                                    orders1.setSumMoney(orders1.getSumMoney().add(orders.getPayMoney()));
                                    orders1.setSumArtificerMoney(orders1.getSumArtificerMoney().add(orders.getArtificerMoney()));

//                                    orders1.setOneArtificerMoney(orders1.getOneArtificerMoney().add(orders.getOneArtificerMoney()));
                                    orders1.setJjrMoney(orders1.getJjrMoney().add(orders.getJjrMoney()));
                                    orders1.setShopMoney(orders1.getShopMoney().add(orders.getShopMoney()));
                                    orders1.setOneUserMoney(orders1.getOneUserMoney().add(orders.getOneUserMoney()));
                                    orders1.setPingMoney(orders1.getPingMoney().add(orders.getPingMoney()));

                                    if(orders1.getStatus().equals(6)){
//                                        ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders1.getOrdersId()));
//                                        massageType = massageTypeService.getById(ordersMassage.getMassageId());
//                                        duration=massageType.getDuration();
                                        String endTime = orders1.getEndTime();
                                        Date date = DateUtils.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
                                        calendar=Calendar.getInstance();
                                        if(date.getTime()>System.currentTimeMillis()){
                                            calendar.setTime(date);
                                        }
                                        calendar.add(Calendar.MINUTE,orders.getAddTime());
                                        orders1.setEndTime(endTime);
                                    }
                                    orders1.setAddPrice(orders.getPrice());
                                    orders1.setAddMassageTypeId(orders.getMassageTypeId());
                                    orders1.setAddEntryName(orders.getEntryName());
                                    ordersDao.updateById(orders1);
                                    if (flag2) {
                                        ordersDao.update(null, Wrappers.<Orders>lambdaUpdate()
                                                .set(Orders::getWarning, null)
                                                .eq(Orders::getOrdersId, orders1.getOrdersId()));
                                    }
                                }else{
                                    MessageInfo messageInfo=new MessageInfo();
                                    messageInfo.setState("16");
                                    messageInfo.setTitle("新订单通知");
                                    messageInfo.setUserId("0");
                                    messageInfo.setIsSee("0");
                                    messageService.saveBody(messageInfo);
                                    //电话通知 add 2024-06-20 by caolei
                                    messageService.sendNoticeByCall(artificer.getUserId());
                                }

                                ordersService.sendMsg(orders);

                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setManipulateType(1);
                                if(orders.getUserPackageDetailId() != null){
                                    userMoneyDetails.setMoney(orders.getTaxiMoney());
                                }else{
                                    userMoneyDetails.setMoney(orders.getPayMoney());
                                }
                                userMoneyDetails.setUserId(orders.getUserId());
                                userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
                                userMoneyDetails.setTitle("支付订单");
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);

                            }else if(payDetails.getType()==2){
                                //缴纳保证金
                                Double cashDeposit = payDetails.getMoney();
                                Long userId = payDetails.getUserId();
                                userMoneyDao.updateCashDeposit(1, userId, cashDeposit);
                                UserEntity userEntity = userService.selectUserById(userId);
                                userEntity.setIsCashDeposit(2);
                                userService.updateById(userEntity);
                                //交保证金的记录
                                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                                userMoneyDetails.setUserId(userId);
                                userMoneyDetails.setTitle("缴纳保证金");
                                userMoneyDetails.setContent("已缴纳保证金："+cashDeposit+"元");
//                                userMoneyDetails.setType(1);
                                userMoneyDetails.setManipulateType(1);
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setMoney(BigDecimal.valueOf(cashDeposit));
                                userMoneyDetails.setClassify(1);
                                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                userMoneyDetails.setBlRole(2);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);
                            }else if(payDetails.getType()==3){

                                PayClassify payClassify = payClassifyService.getById(Long.parseLong(payDetails.getRemark()));
                                userMoneyDao.updateMayMoney(1, payDetails.getUserId(), payClassify.getMoney().doubleValue());
                                //查询用户当前余额
                                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(payDetails.getUserId());
                                //钱包明细需要做调整2条记录，充值时钱包类型增加金额，现金类型减少金额
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                //插入余额
                                userMoneyDetails.setBalance(userNowMoney.getMoney());
                                userMoneyDetails.setUserId(payDetails.getUserId());
                                userMoneyDetails.setTitle("支付宝充值");
                                userMoneyDetails.setContent("支付宝花费："+payClassify.getPrice()+",钱包增加余额："+payClassify.getMoney());
                                userMoneyDetails.setManipulateType(2);
                                userMoneyDetails.setType(1);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setMoney(payClassify.getMoney());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(1);
                                userMoneyDetailsService.save(userMoneyDetails);
                                userMoneyDetails.setTitle("支付宝充值");
                                userMoneyDetails.setContent("支付宝花费:"+payClassify.getPrice());
                                userMoneyDetails.setMoney(payClassify.getPrice());
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);

                                List<PayClassifyDetail> list = payClassifyDetailService.findList(payClassify.getPayClassifyId());
                                if(list!=null && list.size()>0){
                                    for(int m=0;m<list.size();m++){
                                        PayClassifyDetail pcd = list.get(m);
                                        Coupon coupon = pcd.getCoupon();
                                        for(int i=0;i<pcd.getGiveNum();i++){
                                            Integer endDate = coupon.getEndDate();
                                            Calendar calendar = Calendar.getInstance();
                                            calendar.add(Calendar.DATE, endDate);
                                            calendar.add(Calendar.DATE, 1);
                                            Date date = calendar.getTime();
                                            String expirationTime = sdf.format(date);
                                            CouponUser couponUser = new CouponUser();
                                            couponUser.setUserId(payDetails.getUserId());
                                            couponUser.setCouponName(coupon.getCouponName());
                                            couponUser.setCouponPicture(coupon.getCouponPicture());
                                            couponUser.setCreateTime(DateUtils.format(new Date()));
                                            couponUser.setExpirationTime(expirationTime);
                                            couponUser.setMinMoney(coupon.getMinMoney());
                                            couponUser.setMoney(coupon.getMoney());
                                            couponUser.setClassifyId(coupon.getClassifyId());
                                            couponUser.setStatus(0);
                                            couponUserService.save(couponUser);
                                        }
                                    }
                                }

                                //用户在充值余额时，指定技师ID，则充值成功后给指定技师增加业绩，入userRecharge表
                                if(payDetails.getArtificerId()!=null){
                                    UserRecharge o = new UserRecharge();
                                    o.setUserRecharge(payClassify.getPrice());
                                    o.setType("2");
                                    o.setUserId(payDetails.getUserId());
                                    o.setArtificerId(payDetails.getArtificerId());
                                    o.setOrdersId(payDetails.getMassageOrdersId());
                                    o.setCreateTime(DateUtils.format(new Date()));
                                    userRechargeDao.insert(o);
                                }

                            }else if(payDetails.getType()==4){
                                Long couponIssueId = Long.parseLong(payDetails.getRemark());
                                Long userId=payDetails.getUserId();
                                CouponIssue couponIssue = couponIssueService.getById(couponIssueId);
                                String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                                String[] couponIds = couponIssue.getCouponIds().split(",");
                                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                                userMoneyDetails.setClassify(1);
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setManipulateType(1);
                                userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                                userMoneyDetails.setUserId(payDetails.getUserId());
                                userMoneyDetails.setTitle("微信购买优惠券，券包："+couponIssue.getCouponIssueName());
                                userMoneyDetails.setContent("购买优惠券费用："+payDetails.getMoney());
                                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                for(String couponId:couponIds){
                                    Coupon coupon = couponService.getById(Long.parseLong(couponId));
                                    Integer endDate = coupon.getEndDate();
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.add(Calendar.DATE, endDate);
                                    calendar.add(Calendar.DATE, 1);
                                    Date date = calendar.getTime();
                                    String expirationTime = simpleDateFormat.format(date);
                                    CouponUser couponUser=new CouponUser();
                                    couponUser.setUserId(userId);
                                    couponUser.setCouponName(coupon.getCouponName());
                                    couponUser.setCouponPicture(coupon.getCouponPicture());
                                    couponUser.setCreateTime(createTime);
                                    couponUser.setExpirationTime(expirationTime);
                                    couponUser.setMinMoney(coupon.getMinMoney());
                                    couponUser.setMoney(coupon.getMoney());
                                    couponUser.setStatus(0);
                                    couponUserService.save(couponUser);
                                }
                                couponIssue.setCouponNum(couponIssue.getCouponNum()-1);
                                couponIssueService.updateById(couponIssue);
                            }else if(payDetails.getType()==5){
                                BigDecimal money=BigDecimal.valueOf(payDetails.getMoney());
                                Long userId=payDetails.getUserId();
                                VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", Long.parseLong(payDetails.getRemark())));
                                //查看用户是否是会员
                                UserVip userVip = userVipDao.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
                                Calendar cal = Calendar.getInstance();
                                if(userVip!=null){
                                    Date endDate = null;
                                    try {
                                        endDate = sdf.parse(userVip.getEndTime());
                                        if (endDate != null && System.currentTimeMillis() < (endDate.getTime())) {
                                            cal.setTime(endDate);
                                        }
                                    } catch (Exception e) {
                                        e.getMessage();
                                    }
                                }else{
                                    userVip=new UserVip();
                                    //设置会员类型
                                    userVip.setVipNameType(vipDetails.getVipNameType());
                                    //设置开通会员的用户id
                                    userVip.setUserId(userId);
                                    //设置会员的购买时间
                                    userVip.setCreateTime(sdf.format(new Date()));
                                }

                                MessageInfo messageInfo=new MessageInfo();
                                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                                userMoneyDetails.setMoney(money);
                                userMoneyDetails.setUserId(userId);

                                if ((vipDetails.getVipNameType().equals(0))) {
                                    //月
                                    userMoneyDetails.setContent("微信开通月卡会员");
                                    messageInfo.setContent("微信开通月卡会员");
                                    cal.add(Calendar.MONTH, 1);
                                } else if ((vipDetails.getVipNameType()).equals(1)) {
                                    //季
                                    userMoneyDetails.setContent("微信开通季卡会员");
                                    messageInfo.setContent("微信开通季卡会员");
                                    cal.add(Calendar.MONTH, 3);
                                } else {
                                    //年
                                    userMoneyDetails.setContent("微信开通年费会员");
                                    messageInfo.setContent("微信开通年费会员");
                                    cal.add(Calendar.YEAR, 1);
                                }

                                userVip.setEndTime(sdf.format(cal.getTime()));
                                if(userVip.getVipId()!=null){
                                    userVipDao.updateById(userVip);
                                }else{
                                    userVipDao.insert(userVip);
                                }
                                userMoneyDetails.setTitle("开通会员");
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setManipulateType(1);
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);
                                UserEntity userEntity = userService.selectUserById(userId);
                                messageInfo.setTitle("开通会员");
                                messageInfo.setState(String.valueOf(4));
                                messageInfo.setUserName(userEntity.getUserName());
                                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                                messageInfo.setCreateAt(sdf.format(new Date()));
                                messageInfo.setIsSee("0");
                                messageService.saveBody(messageInfo);
                                if(StringUtil.isNotBlank(userEntity.getClientid())){
                                    userService.pushToSingle(messageInfo.getTitle(),messageInfo.getContent(),userEntity.getClientid());
                                }

                            }else if(payDetails.getType()==6){
                                double money=payDetails.getMoney();
                                long artificerId = Long.parseLong(payDetails.getRemark());
                                Artificer artificer = artificerService.getById(artificerId);
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                //用户流水
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setClassify(8);
                                userMoneyDetails.setManipulateType(1);
                                userMoneyDetails.setUserId(payDetails.getUserId());
                                userMoneyDetails.setTitle("微信给技师打赏");
                                userMoneyDetails.setContent("使用微信给指定技师“"+artificer.getArtificerName()+"”打赏:"+money);
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setMoney(BigDecimal.valueOf(money));
                                userMoneyDetails.setArtificerId(artificerId);
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);
                                //技师流水
                                UserEntity userEntity = userService.queryByUserId(artificer.getUserId());
                                userMoneyDao.updateMayMoney(1, userEntity.getUserId(), money);
                                //查询技师当前余额
                                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userEntity.getUserId());
                                UserMoneyDetails userMoneyDetails2 = new UserMoneyDetails();
                                //插入余额
                                userMoneyDetails2.setBalance(userNowMoney.getMoney());
                                userMoneyDetails2.setManipulateType(2);
                                userMoneyDetails2.setClassify(8);
                                userMoneyDetails2.setUserId(userEntity.getUserId());
                                userMoneyDetails2.setTitle("用户微信打赏");
                                userMoneyDetails2.setContent("来自用户“"+userEntity.getUserName()+"”微信打赏:"+money);
                                userMoneyDetails2.setType(1);
                                userMoneyDetails2.setState(2);
                                userMoneyDetails2.setMoney(BigDecimal.valueOf(money));
                                userMoneyDetails2.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails2.setBlRole(2);
                                userMoneyDetails2.setBlFlag(1);
                                userMoneyDetailsService.save(userMoneyDetails2);
                            }else if(payDetails.getType()==7){
                                //服务包下单，分单
                                UserPackageOrder orders = userPackageOrderDao.getByNo(out_trade_no);
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setManipulateType(1);
                                userMoneyDetails.setUserId(orders.getUserId());
                                userMoneyDetails.setMoney(orders.getPayMoney());
                                userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
                                userMoneyDetails.setTitle("支付服务包订单");
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(1);
                                userMoneyDetailsService.save(userMoneyDetails);

                                orders.setStatus(1);
                                orders.setPayWay(payDetails.getClassify());
                                orders.setPayTime(sdf.format(new Date()));
                                userPackageOrderDao.updateStatus(orders);

                                //获取订单-服务包映射关系列表
                                List<UserPackageOrdersMapping> mappingList = userPackageOrdersMappingService.findListByOrdersId(orders.getOrdersId());
                                for (UserPackageOrdersMapping ordersPackage : mappingList) {
                                    int quantity = ordersPackage.getNum();
                                    MassagePackage massagePackage = massagePackageService.getById(ordersPackage.getPackageId());
                                    //修改服务包销量
                                    int sales = massagePackage.getSales();
                                    sales = sales+quantity;
                                    massagePackage.setSales(sales);
                                    massagePackageService.updateSales(massagePackage);
                                    for(int i=0;i<quantity;i++){
                                        //拆分插入用户服务包
                                        UserPackage userPackage = new UserPackage();
                                        userPackage.setUserId(orders.getUserId());
                                        userPackage.setPackageId(massagePackage.getId());
                                        userPackage.setOrdersId(orders.getOrdersId());
                                        userPackage.setOrdersNo(orders.getOrdersNo());
                                        userPackage.setCreateTime(sdf.format(new Date()));
                                        userPackage.setTitle(massagePackage.getTitle());
                                        userPackage.setType(massagePackage.getType());
                                        userPackage.setOldPrice(massagePackage.getOldPrice());
                                        userPackage.setPrice(massagePackage.getPrice());
                                        userPackage.setPackageImg(massagePackage.getPackageImg());
                                        userPackage.setContent(massagePackage.getContent());
                                        userPackage.setContentImg(massagePackage.getContentImg());
                                        userPackage.setLabels(massagePackage.getLabels());
                                        userPackage.setCity(massagePackage.getCity());
                                        userPackage.setClassifyId(massagePackage.getClassifyId());
                                        userPackage.setLevel(massagePackage.getLevel());
                                        userPackageService.insert(userPackage);
                                        Long mainId = userPackage.getId();
                                        //拆分插入用户服务器项目详情
                                        UserPackageDetail userPackageDetail = new UserPackageDetail();
                                        userPackageDetail.setMainId(ordersPackage.getPackageId());
                                        List<UserPackageDetail> userPackageDetailList = userPackageDetailService.findMassagePackageDetails(userPackageDetail);
                                        if(userPackageDetailList.size()>0){
                                            for(int j=0;j<userPackageDetailList.size();j++){
                                                UserPackageDetail upd = userPackageDetailList.get(j);
                                                upd.setMainId(mainId);
                                                upd.setCreateTime(sdf.format(new Date()));
                                                upd.setLevel(massagePackage.getLevel());
                                                int serviceCount = upd.getServiceCount();
                                                for(int k=0;k<serviceCount;k++){
                                                    userPackageDetailService.insert(upd);
                                                    MassageType massageType = massageTypeService.getById(upd.getMassageTypeId());
                                                    massageType.setSales(massageType.getSales()+1);
                                                    massageTypeService.updateById(massageType);
                                                }
                                            }
                                        }
                                    }
                                }
                            }else if(payDetails.getType()==8) {
                                //服务包下单，分单
                                UserPackageOrder orders = userPackageOrderDao.getByNo(out_trade_no);
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setManipulateType(1);
                                userMoneyDetails.setUserId(orders.getUserId());
                                userMoneyDetails.setMoney(orders.getPayMoney());
                                userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
                                userMoneyDetails.setTitle("支付团购订单");
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(1);
                                userMoneyDetailsService.save(userMoneyDetails);
                                orders.setStatus(4);//团购中
                                orders.setPayWay(payDetails.getClassify());
                                orders.setPayTime(sdf.format(new Date()));
                                userPackageOrderDao.updateStatus(orders);

                                //获取支付已支付的数量是否满足此次团购人数，是则完成此次拼团，并将商品发送给客户
                                int buyGroupNum = 0;
                                int groupNum = 0;
                                List<UserPackageOrder> list = userPackageOrderDao.getActivityOrderListByGroupNo(orders.getGroupNo(),null);
                                if(list.size()>0){
                                    for(UserPackageOrder userPackageOrder : list) {
                                        if (userPackageOrder.getStatus().equals(1) || userPackageOrder.getStatus().equals(4)) {
                                            buyGroupNum++;
                                        }
                                    }
                                }
                                MassagePackage massagePackage = null;
                                List<UserPackageOrdersMapping> mappingList = userPackageOrdersMappingService.findListByOrdersId(orders.getOrdersId());
                                if(mappingList.size()>0){
                                    Long packageId = mappingList.get(0).getPackageId();
                                    massagePackage = massagePackageService.getById(packageId);
                                    groupNum = massagePackage.getGroupNum();
                                }
                                if(buyGroupNum>0 && groupNum>0 && buyGroupNum>=groupNum){
                                    for(UserPackageOrder userPackageOrder : list) {
                                        if (userPackageOrder.getStatus().equals(1) || userPackageOrder.getStatus().equals(4)) {
                                            //删除单据防止重复数据
                                            List<UserPackage> userPackageList = userPackageService.findList(userPackageOrder.getOrdersId());
                                            if(userPackageList.size()>0){
                                                for(UserPackage userPackage : userPackageList){
                                                    userPackageService.removeById(userPackage.getId());
                                                    userPackageDetailService.deleteDetailByMain(userPackage.getId());
                                                }
                                            }
                                            //插入单据
                                            List<UserPackageOrdersMapping> packageOrderMappingList = userPackageOrdersMappingService.findListByOrdersId(userPackageOrder.getOrdersId());
                                            for (UserPackageOrdersMapping ordersPackage : packageOrderMappingList) {
                                                int quantity = ordersPackage.getNum();
                                                for(int i=0;i<quantity;i++){
                                                    //拆分插入用户团购
                                                    UserPackage userPackage = new UserPackage();
                                                    userPackage.setUserId(userPackageOrder.getUserId());
                                                    userPackage.setPackageId(massagePackage.getId());
                                                    userPackage.setOrdersId(userPackageOrder.getOrdersId());
                                                    userPackage.setOrdersNo(userPackageOrder.getOrdersNo());
                                                    userPackage.setCreateTime(DateUtils.format(new Date()));
                                                    userPackage.setTitle(massagePackage.getTitle());
                                                    userPackage.setType(massagePackage.getType());
                                                    userPackage.setOldPrice(massagePackage.getOldPrice());
                                                    userPackage.setPrice(massagePackage.getPrice());
                                                    userPackage.setPackageImg(massagePackage.getPackageImg());
                                                    userPackage.setContent(massagePackage.getContent());
                                                    userPackage.setContentImg(massagePackage.getContentImg());
                                                    userPackage.setLabels(massagePackage.getLabels());
                                                    userPackage.setCity(massagePackage.getCity());
                                                    userPackage.setClassifyId(massagePackage.getClassifyId());
                                                    userPackage.setLevel(massagePackage.getLevel());
                                                    userPackageService.insert(userPackage);
                                                    Long mainId = userPackage.getId();
                                                    //拆分插入用户服务器项目详情
                                                    UserPackageDetail userPackageDetail = new UserPackageDetail();
                                                    userPackageDetail.setMainId(ordersPackage.getPackageId());
                                                    List<UserPackageDetail> userPackageDetailList = userPackageDetailService.findMassagePackageDetails(userPackageDetail);
                                                    if(userPackageDetailList.size()>0){
                                                        for(int j=0;j<userPackageDetailList.size();j++){
                                                            UserPackageDetail upd = userPackageDetailList.get(j);
                                                            upd.setMainId(mainId);
                                                            upd.setCreateTime(DateUtils.format(new Date()));
                                                            upd.setLevel(massagePackage.getLevel());
                                                            int serviceCount = upd.getServiceCount();
                                                            for(int k=0;k<serviceCount;k++){
                                                                userPackageDetailService.insert(upd);
                                                                MassageType massageType = massageTypeService.getById(upd.getMassageTypeId());
                                                                massageType.setSales(massageType.getSales()+1);
                                                                massageTypeService.updateById(massageType);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    //完成团购
                                    UserPackageOrder packageOrder = new UserPackageOrder();
                                    packageOrder.setGroupNo(orders.getGroupNo());
                                    packageOrder.setStatus(1);
                                    userPackageOrderDao.updateStatus(packageOrder);
                                    //修改团购销量
                                    int sales = massagePackage.getSales();
                                    sales = sales+1;
                                    massagePackage.setSales(sales);
                                    massagePackageService.updateSales(massagePackage);
                                }
                            }
                        }
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                } else {
                    if (out_trade_no != null) {
                        //支付失败或者取消，删除技师占用表数据
                        PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                        if (payDetails.getState() == 0){
                            if(payDetails.getType()==1){
                                artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", payDetails.getOrderId()));
                                payDetailsDao.deleteById(payDetails.getId());
                                System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                                xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                            }
                        }
                    }else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                System.err.println("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }

    @Override
    public String payBacks(String resXml, Integer type) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("进入回调了！！！");
        if(type==1){
            config.setAppId(commonInfoService.findOne(260).getValue());
            config.setKey(commonInfoService.findOne(245).getValue());
            config.setMchId(commonInfoService.findOne(246).getValue());
        }else if(type==2){
            config.setAppId(commonInfoService.findOne(5).getValue());
            config.setKey(commonInfoService.findOne(75).getValue());
            config.setMchId(commonInfoService.findOne(76).getValue());
        }else{
            config.setAppId(commonInfoService.findOne(243).getValue());
            config.setKey(commonInfoService.findOne(245).getValue());
            config.setMchId(commonInfoService.findOne(246).getValue());
        }

        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                log.error("验证成功！！！");
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    log.error("验证成功222！！！");
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        log.error("订单号！！！" + out_trade_no);
                        PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                        if (payDetails.getState() == 0) {
                            payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), "");
                            if(payDetails.getType()==1){
                                Orders orders = ordersService.selectOrdersByOrderNo(payDetails.getOrderId());
                                orders.setStatus(2);
                                orders.setPayTime(sdf.format(new Date()));
                                ordersService.updateById(orders);
                                ordersService.sendMsg(orders);
                            }else if(payDetails.getType()==2){
                                //缴纳保证金
                                Double cashDeposit = payDetails.getMoney();
                                Long userId = payDetails.getUserId();
                                userMoneyDao.updateCashDeposit(1, userId, cashDeposit);
                                UserEntity userEntity = userService.selectUserById(userId);
                                userEntity.setIsCashDeposit(2);
                                userService.updateById(userEntity);
                                //交保证金的记录
                                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                                userMoneyDetails.setUserId(userId);
                                userMoneyDetails.setTitle("缴纳保证金");
                                userMoneyDetails.setContent("已缴纳保证金："+cashDeposit+"元");
                                userMoneyDetails.setType(1);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setMoney(BigDecimal.valueOf(cashDeposit));
                                userMoneyDetails.setClassify(1);
                                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                userMoneyDetails.setBlRole(2);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);
                            }else if(payDetails.getType()==3){
                                userMoneyDao.updateMayMoney(1, payDetails.getUserId(), payDetails.getMoney());
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setUserId(payDetails.getUserId());
                                userMoneyDetails.setTitle("微信充值");
                                userMoneyDetails.setContent("微信充值:"+payDetails.getMoney());
                                userMoneyDetails.setType(1);
                                userMoneyDetails.setState(2);
                                userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetails.setBlRole(1);
                                userMoneyDetails.setBlFlag(2);
                                userMoneyDetailsService.save(userMoneyDetails);
                            }
                        }
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                } else {
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                System.err.println("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }


    public String getGeneralOrder() {
        Date date = new Date();
        String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format + newString;
    }


    @Override
    public boolean refund(String ordersNo,BigDecimal payMoney,BigDecimal refundMoney,Integer payWay) {
        WXConfigUtil config = null;
        try {
            config = new WXConfigUtil();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int commInfoId = 0;
//        Integer payWay = null;
        //orders.getPayWay(); //支付方式 1app微信 2微信公众号 3微信小程序 4微信公众号 外链支付 6支付宝  5零钱
        switch (payWay) {
            case 1:
                commInfoId = 74;
                break; //appId
            case 2:
                commInfoId = 5;
                break; //公众号id
            case 3:
                commInfoId = 45;
                break; //小程序id
            case 4:
                commInfoId = 5;
                break; //小程序id
        }
        if(config==null){
            return false;
        }
        config.setAppId(commonInfoService.findOne(commInfoId).getValue());
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), WXPayConstants.SignType.MD5));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        data.put("out_trade_no", ordersNo); //订单号,支付单号一致
        data.put("out_refund_no", ordersNo); //退款单号，同一笔用不同的退款单号
        double total_fee = 0.00;
        data.put("total_fee", new Double(payMoney.doubleValue() * 100).intValue() + ""); //1块等于微信支付传入100);
        data.put("refund_fee", new Double(refundMoney.doubleValue() * 100).intValue() + ""); //1块等于微信支付传入100);
        //使用官方API退款
        try {
            Map<String, String> response = wxpay.refund(data);
            if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
                log.error("退款成功！");
                return true;
            } else {
                log.error("退款失败！订单号："+ordersNo);
                for (String key : response.keySet()) {
                    log.info("微信退款失败返回参数：keys:" + key + "    value:" + response.get(key).toString());
                }
                return false;
            }
        } catch (Exception e) {
            log.info("退款异常：订单号"+ordersNo,e);
            e.printStackTrace();
            return false;
        }
    }







}