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

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dyvmsapi20170525.Client;
import com.aliyun.dyvmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.map.CommonMapUtils;
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.ArtificerDao;
import com.sqx.modules.artificer.dao.OrdersDao;
import com.sqx.modules.artificer.entity.*;
import com.sqx.modules.artificer.service.*;
import com.sqx.modules.bl.order.entity.UserPackage;
import com.sqx.modules.bl.order.entity.UserPackageOrder;
import com.sqx.modules.bl.order.service.UserPackageOrderService;
import com.sqx.modules.bl.order.service.UserPackageService;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.bl.order.entity.UserPackageDetail;
import com.sqx.modules.bl.order.service.UserPackageDetailService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.enums.CommonEnum;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.common.utils.CommonConfigUtil;
import com.sqx.modules.consortia.entity.Consortia;
import com.sqx.modules.consortia.service.ConsortiaService;
import com.sqx.modules.coupon.entity.CouponUser;
import com.sqx.modules.coupon.service.CouponUserService;
import com.sqx.modules.material.dao.MaterialArtificerMapper;
import com.sqx.modules.material.dao.MaterialMapper;
import com.sqx.modules.material.dao.MaterialMassageMapper;
import com.sqx.modules.material.entity.Material;
import com.sqx.modules.material.entity.MaterialArtificer;
import com.sqx.modules.material.entity.MaterialMassage;
import com.sqx.modules.material.service.MaterialArtificerService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.sys.entity.SysDictEntity;
import com.sqx.modules.sys.service.SysDictService;
import com.sqx.modules.taking.dao.OrderTakingCommentDao;
import com.sqx.modules.travelconf.service.TravelConfService;
import com.sqx.modules.travelconf.vo.TravelPriceVo;
import com.sqx.modules.trip.entity.Trip;
import com.sqx.modules.trip.service.TripService;
import com.sqx.modules.utils.AppNotifyUtil;
import com.sqx.modules.utils.LonLatUtil;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.address.AddressUtil;
import com.sqx.modules.utils.address.WSSsdrAddress;
import com.sqx.modules.utils.excel.ExcelData;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private MassageTypeService massageTypeService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private OrdersMassageService ordersMassageService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private VipDetailsDao vipDetailsDao;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserVipDao userVipDao;
    @Autowired
    private OrderTakingCommentDao orderTakingCommentDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private CollectArtificerService collectArtificerService;
    @Autowired
    private ArtificerTimeService artificerTimeService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private WxService wxService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private TripService tripService;
    @Autowired
    private ConsortiaService consortiaService;
    @Autowired
    private UserMoneyArtificerService userMoneyArtificerService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private MaterialArtificerService materialArtificerService;
    @Autowired
    private ArtificerDao artificerDao;
    @Autowired
    private UserPackageDetailService userPackageDetailService;
    @Autowired
    private UserPackageService userPackageService;
    @Autowired
    private UserPackageOrderService userPackageOrderService;
    @Autowired
    private MaterialMassageMapper materialMassageMapper;
    @Autowired
    private MaterialArtificerMapper materialArtificerMapper;
    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    public CommonInfoDao commonInfoDao;

    @Autowired
    private TravelConfService travelConfService;

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(30, 100,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());


    @Override
    public Map<String, Object> selectTaxiMoney(Long artificerId, String latitude, String longitude, String city) {

        Artificer artificer = artificerService.getById(artificerId);
        GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(latitude), Double.parseDouble(longitude));
        GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(artificer.getLatitude()), Double.parseDouble(artificer.getLongitude()));
        Integer distances = (int) LonLatUtil.getDistanceMeter(source, target, Ellipsoid.Sphere);

        //起步价
        String tripPrice;
        //每公里价格
        String tripMoney;
        //起步公里数
        String tripNum;
        Trip trip = tripService.getOne(new QueryWrapper<Trip>().like("city", city));
        if (trip == null) {
            return Result.error("当前地址暂无出行方式，请更换其他地址！");
        }

        //获取城市名称
        JSONObject mapRes = CommonMapUtils.calcTaxiMoneyInfo(artificer.getTripWay(), longitude, latitude, artificer.getLongitude(), artificer.getLatitude());//根据出行方式计算距离

        //判断技师的出行方式
        if (artificer.getTripWay() == null || artificer.getTripWay() == 1) {
            //公交
            tripPrice = trip.getBusStartingFare();
            tripMoney = trip.getBusKmMoney();
            tripNum = trip.getBusStartingKm();
            distances = mapRes.getInteger("distance");
        } else if (artificer.getTripWay() == 2) {
            //出租
            tripPrice = trip.getTaxiStartingFare();
            tripMoney = trip.getTaxiKmMoney();
            tripNum = trip.getTaxiStartingKm();
            distances = mapRes.getInteger("distance");
        } else {
            tripPrice = "0";
            tripMoney = "0";
            tripNum = "1";
        }


        int i = Integer.parseInt(tripNum);
        i = i * 1000;
        BigDecimal taxiMoney = new BigDecimal(tripPrice);
        if (artificer.getTripWay() == null || artificer.getTripWay() == 1 || artificer.getTripWay() == 2) {
            if (distances > i) {
                int distancess = distances;
                //大于起步公里
                distances = distances - i;
                BigDecimal bigDecimal = BigDecimal.valueOf(distances).divide(BigDecimal.valueOf(1000), 2, BigDecimal.ROUND_HALF_UP);
                double downd = Math.ceil(bigDecimal.doubleValue());
                distances = new Double(downd).intValue();
                BigDecimal xuMoney = BigDecimal.valueOf(distances).multiply(new BigDecimal(tripMoney));
                taxiMoney = taxiMoney.add(xuMoney);
                distances = distancess;
                bigDecimal = BigDecimal.valueOf(distances).divide(BigDecimal.valueOf(1000), 2, BigDecimal.ROUND_HALF_UP);
                downd = Math.ceil(bigDecimal.doubleValue());
                distances = new Double(downd).intValue();
            } else {
                BigDecimal bigDecimal = BigDecimal.valueOf(distances).divide(BigDecimal.valueOf(1000), 2, BigDecimal.ROUND_HALF_UP);
                double downd = Math.ceil(bigDecimal.doubleValue());
                distances = new Double(downd).intValue();
            }
        } else {
            BigDecimal bigDecimal = BigDecimal.valueOf(distances).divide(BigDecimal.valueOf(1000), 2, BigDecimal.ROUND_HALF_UP);
            double downd = Math.ceil(bigDecimal.doubleValue());
            distances = new Double(downd).intValue();
        }

        String value = commonInfoService.findOne(426).getValue();
        if ("是".equals(value)) {
            distances = distances * 2;
            taxiMoney = taxiMoney.multiply(BigDecimal.valueOf(2));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("tripPrice", tripPrice);
        result.put("tripNum", tripNum);
        result.put("distances", distances);
        result.put("xuMoney", tripMoney);
        result.put("taxiMoney", taxiMoney);
        return result;
    }

    /**
     * 获取总花费时间
     * @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");
                    return map;
                }
            }
        }
        //服务时间后锁单时间判断
        if (i >= 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parse);
            String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
            allTime.add(format);
            for (int j = 0; j < i; j++) {
                calendar.add(Calendar.MINUTE, minute);
                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");
                    return map;
                }
            }
        }
        //服务中锁单时间判断
        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");
                    return map;
                }
            }
        }
        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");
                    return map;
                }
            }
        }
        //服务时间后锁单时间判断
        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");
                    return map;
                }
            }
        }
        //服务中锁单时间判断
        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");
                    return map;
                }
            }
        }
        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");
                    return map;
                }
            }
        }
        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 insertOrders(Orders orders) {
        String msg = "";
//        reentrantReadWriteLock.writeLock().lock();
        Artificer artificer1 = artificerDao.selectOne(Wrappers.<Artificer>lambdaQuery()
                .eq(Artificer::getArtificerId, orders.getArtificerId()));
        orders.setClassifyId(artificer1.getClassifyId());
        try {
            if(orders.getUserPackageDetailId() !=null ){
                //套餐订单
                return insertPackageOrders(orders);
            }else{
                //项目订单
                return insertMassageOrders(orders);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加订单异常" + e.getMessage(), e);
            msg = e.getMessage();
        } finally {
//            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error(msg);
//        return Result.error("系统繁忙，请稍后再试！");
    }

    private Result insertMassageOrders(Orders orders) throws Exception{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        BigDecimal couponMinMoney = BigDecimal.ZERO;//所有代金券的使用额度总和
        //获取并判断代金券信息
        List<CouponUser> CouponUserList = Lists.newArrayList();
        if(orders.getCouponId() != null){
            String couponIds = orders.getCouponId();
            if(StringUtils.isNotBlank(couponIds)){
                String[] couponArr = couponIds.trim().split(",");
                BigDecimal couponMoney = new BigDecimal(0);
                StringBuffer couponNameSb = new StringBuffer();
                for(int i=0;i<couponArr.length;i++){
                    if(couponArr[i]!=null && !couponArr[i].equals("")){
                        Long couponId = Long.valueOf(couponArr[i]);
                        CouponUser couponUser = couponUserService.getById(couponId);
                        if (!couponUser.getStatus().equals(0)) {
                            return Result.error("优惠券已被使用！");
                        }
                        if(couponUser.getClassifyId()!=0){
                            if(!orders.getClassifyId() .equals(couponUser.getClassifyId())){
                                return Result.error("优惠券不满足使用条件！");
                            }
                        }
                        couponMinMoney = couponMinMoney.add(couponUser.getMinMoney());
                        CouponUserList.add(couponUser);
                        BigDecimal money = couponUser.getMoney();
                        couponMoney = couponMoney.add(money);
                        couponNameSb.append(couponUser.getCouponName());
                        couponNameSb.append(",");
                    }
                }
                orders.setCouponName(couponNameSb.toString());
                orders.setCouponMoney(couponMoney);
            }else{
                orders.setCouponName("");
                orders.setCouponMoney(BigDecimal.ZERO);
            }
        }else{
            orders.setCouponName("");
            orders.setCouponMoney(BigDecimal.ZERO);
        }

        //获取用户VIP的优惠信息
        BigDecimal vipRate = new BigDecimal(100);
        UserVip userVip = userVipService.selectUserVipByUserId(orders.getUserId());
        if (userVip != null) {
            if (userVip.getIsVip() == 1) {
                //获取用户到期时间
                Date date = null;
                try {
                    date = simpleDateFormat.parse(userVip.getEndTime());
                    if (date.getTime() >= System.currentTimeMillis()) {
                        VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", userVip.getVipNameType()));
                        if (vipDetails != null) {
                            vipRate = vipDetails.getRate();
                        }
                    }
                } catch (Exception e) {
                    e.getMessage();
                }
            }
        }
        orders.setVipRate(vipRate);

        Artificer artificer = artificerService.getById(orders.getArtificerId());
        orders.setTechnicianType(artificer.getTechnicianType());
        BigDecimal artificerVipRate = BigDecimal.ZERO;
        VipDetails artificerVipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", artificer.getTechnicianType()));
        if (artificerVipDetails != null) {
            artificerVipRate = artificerVipDetails.getRate();
        }
        orders.setTechnicianRate(artificerVipRate);

        List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
        MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
        if(massageType == null){
            Long id = ordersMassageList.get(0).getMassageId();
            Orders tempOrders = baseMapper.selectById(id);
            if(tempOrders != null){
                return Result.error("该订单已生成，请到订单列表进行支付！");
            }
        }

        BigDecimal price = BigDecimal.ZERO;
        String massageTypeName = "";
        BigDecimal artificerPrice = BigDecimal.ZERO;

        orders.setDuration(massageType.getDuration());
        for (OrdersMassage ordersMassage : ordersMassageList) {
            orders.setMassageNum(ordersMassage.getNum());
            price = massageType.getPrice().multiply(BigDecimal.valueOf(ordersMassage.getNum()));
            price = price.setScale(2,BigDecimal.ROUND_HALF_UP);
            if (orders.getParentId() != null && orders.getParentId() != 0) {
                orders.setAddTime(massageType.getDuration());
                List<Orders> parentList = baseMapper.getParentOrders(orders.getParentId());
                if(parentList.size()>0){
                    for(Orders parentOrder : parentList){
                        if(parentOrder.getStatus()==1 || parentOrder.getStatus()==4){
                            baseMapper.deleteById(parentOrder.getOrdersId());
                            ordersMassageService.removeByOrdersId(parentOrder.getOrdersId());
                        }
                    }
                }
                parentList = baseMapper.getParentOrders(orders.getParentId());
                if(parentList.size()>0){
                    return Result.error("当前订单已有加钟订单，无法继续加钟！");
                }
            }
            orders.setMassageTypeId(massageType.getMassageTypeId());
        }
        massageTypeName = massageType.getTitle();
        orders.setEntryName(massageTypeName);
        orders.setMassagePrice(price);
        //保存现价
        orders.setPrice(price);

        //技师加成金额
        BigDecimal technicianMoney = price.multiply(orders.getTechnicianRate()).divide(new BigDecimal(100));
        technicianMoney = technicianMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
        orders.setTechnicianMoney(technicianMoney);

        //技师加成后总额
        BigDecimal priceMarkup = technicianMoney.add(price);
        priceMarkup = priceMarkup.setScale(2,BigDecimal.ROUND_HALF_UP);
        orders.setPriceMarkup(priceMarkup);

        //会员优惠后金额，及会员减免金额
        BigDecimal vipMoney = priceMarkup.multiply(orders.getVipRate()).divide(new BigDecimal(100));
        vipMoney = vipMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal vipReductionMoney = priceMarkup.subtract(vipMoney);
        orders.setVipReductionMoney(vipReductionMoney);

        //项目价格 = 原金额+技师加成金额-会员减免金额
        BigDecimal payMoney = vipMoney;
        orders.setMassageMoney(payMoney);

        //判断金额是否满足代金券金额最少消费额度
        if(orders.getMassagePrice().compareTo(couponMinMoney) < 0){
            return Result.error("当前应付总金额不满足优惠券使用的最小额度，请重新选择优惠券！");
        }

        //减去代金券的金额
        payMoney = payMoney.subtract(orders.getCouponMoney());

        String value1 = commonInfoService.findOne(395).getValue();
        Integer tripWay = orders.getTripWay();
        BigDecimal taxiMoney = BigDecimal.ZERO;
        if (orders.getParentId() == null || orders.getParentId() == 0) {
            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(massageType.getDuration(),serveTime,value1,tripWay,orders.getArtificerId());
            if(map.get("code").toString().equals("1")){
                return Result.error("预约时间正忙，请更换其他时间！");
            }
            //计算车费
            TravelPriceVo travelPriceVo = travelConfService.calcTravelPrice(orders.getArtificerId(), orders.getLongitude(), orders.getLatitude(),orders.getServeTime());
            if (travelPriceVo == null) {
                return Result.error("暂不支持当前地址，请更换其他地址！");
            }
            taxiMoney = new BigDecimal(travelPriceVo.getTravelPrice());
            taxiMoney = taxiMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
            orders.setTaxiMoney(taxiMoney);
            orders.setKm(travelPriceVo.getKilometerNum());
            orders.setUsualTravelMoney(travelPriceVo.getUsualTravelMoney());
            orders.setNightTravelMoney(travelPriceVo.getNightTravelMoney());
        } else {
            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("预约时间正忙，请更换其他时间！");
                }
            }
        }
        //加上车费
        BigDecimal subtract = payMoney;
        payMoney = payMoney.add(taxiMoney);
        payMoney = payMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
        orders.setPayMoney(payMoney);

        //计算用户收益 ！计算前先减去通行费用再计算技师抽成
        artificerPrice = subtract.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
        //查询是否计算出租车扣费
        String taxi = commonInfoService.findOne(394).getValue();
        //计算技师出租车收益（按照技师表收益计算）
        if ("是".equals(taxi)) {
            //计算技师应该收取的出租车费用
            BigDecimal artificerTaxiMoney = taxiMoney.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
            //计算出租车扣款
            BigDecimal pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney).setScale(2,BigDecimal.ROUND_HALF_UP);
            //赋值技师出租收款
            orders.setArtificerTaxiMoney(artificerTaxiMoney);
            //赋值出租车扣款
            orders.setPingTaxiMoney(pingTaxiMoney);
            //用户收益加上通行费用
            artificerPrice = artificerPrice.add(artificerTaxiMoney);
        } else {
            //平台不扣费 出租车收益全由技师收取
            orders.setArtificerTaxiMoney(orders.getTaxiMoney());
            //设置出租车扣款为0
            orders.setPingTaxiMoney(BigDecimal.ZERO);
            //用户收益加上通行费用
            artificerPrice = artificerPrice.add(taxiMoney);
        }
        orders.setArtificerMoney(artificerPrice);
        orders.setSumArtificerMoney(orders.getArtificerMoney());

//        //计算项目收益
//        BigDecimal massageMoney = orders.getMassageMoney();
//        if(orders.getCouponMoney()!=null){
//            massageMoney = massageMoney.subtract(orders.getCouponMoney());
//        }
//        //获取项目应支付金额
//        BigDecimal projectBenefits  = massageMoney;
        BigDecimal projectBenefits  = subtract;
        //计算技师项目提成金额
        orders.setProjectBenefits(projectBenefits.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP));

        orders.setOrdersNo(getGeneralOrder());
        orders.setStatus(1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orders.setCreateTime(sdf.format(new Date()));
        //留存订单生成时的技师分成比例
        orders.setArtificerRate(artificer.getRate());
        orders.setSumMoney(orders.getPayMoney().setScale(2,BigDecimal.ROUND_HALF_UP));
        //保存订单
        baseMapper.insert(orders);

        //更新代金券状态
        if(CouponUserList.size()>0){
            for (CouponUser couponUser : CouponUserList) {
                couponUser.setStatus(1);
                couponUserService.updateById(couponUser);
            }
            orders.setCouponUserList(CouponUserList);
        }
//下单时不做电话通知，2024-06-20 10：11 by caolei
//        if(ObjectUtil.equals(orders.getParentId(),null) || ObjectUtil.equals(orders.getParentId(),0L)){
//            //技师电话通知业务
//            UserEntity byId = userService.getById(artificer.getUserId());
//            //accountId
//            String accountId = commonInfoService.findOne(428).getValue();
//            //token
//            String token = commonInfoService.findOne(429).getValue();
//            //templateId
//            String templateId = commonInfoService.findOne(430).getValue();
//            AppNotifyUtil.AppNotify(byId.getPhone(),accountId,token,templateId);
//        }
        for (OrdersMassage ordersMassage : ordersMassageList) {
            ordersMassage.setOrdersId(orders.getOrdersId());
            ordersMassageService.save(ordersMassage);
        }
        return Result.success().put("data", orders);
    }

    private Result insertPackageOrders(Orders orders) throws Exception{
        List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
        UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
        if(userPackageDetail == null){
            Long id = ordersMassageList.get(0).getMassageId();
            Orders tempOrders = baseMapper.selectById(id);
            if(tempOrders != null){
                return Result.error("该订单已生成，请到订单列表进行支付！");
            }
        }
        orders.setUserPackageId(userPackageDetail.getMainId());
        orders.setUserPackageDetailId(userPackageDetail.getId());
        if(userPackageDetail.getStatus().equals(1)){
            return Result.error("此服务项目已经被使用，无法重复使用！");
        }

        orders.setVipRate(new BigDecimal(100));

        Artificer artificer = artificerService.getById(orders.getArtificerId());
        orders.setTechnicianType(artificer.getTechnicianType());
        BigDecimal artificerVipRate = BigDecimal.ZERO;
        VipDetails artificerVipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", artificer.getTechnicianType()));
        if (artificerVipDetails != null) {
            artificerVipRate = artificerVipDetails.getRate();
        }
        orders.setTechnicianRate(artificerVipRate);

        BigDecimal price = BigDecimal.ZERO;
        BigDecimal packagePrice = BigDecimal.ZERO;
        String massageTypeName = "";
        BigDecimal artificerPrice = BigDecimal.ZERO;

        orders.setDuration(userPackageDetail.getDuration());
        for (OrdersMassage ordersMassage : ordersMassageList) {
            orders.setMassageNum(ordersMassage.getNum());
            price = userPackageDetail.getPrice().multiply(BigDecimal.valueOf(ordersMassage.getNum())).setScale(2,BigDecimal.ROUND_HALF_UP);
            packagePrice = userPackageDetail.getPackagePrice().multiply(BigDecimal.valueOf(ordersMassage.getNum())).setScale(2,BigDecimal.ROUND_HALF_UP);

            if (orders.getParentId() != null && orders.getParentId() != 0) {
                orders.setAddTime(userPackageDetail.getDuration());
                List<Orders> parentList = baseMapper.getParentOrders(orders.getParentId());
                if(parentList.size()>0){
                    for(Orders parentOrder : parentList){
                        if(parentOrder.getStatus()==1 || parentOrder.getStatus()==4){
                            baseMapper.deleteById(parentOrder.getOrdersId());
                            ordersMassageService.removeByOrdersId(parentOrder.getOrdersId());
                        }
                    }
                }
                parentList = baseMapper.getParentOrders(orders.getParentId());
                if(parentList.size()>0){
                    return Result.error("当前订单已有加钟订单，无法继续加钟！");
                }
            }
            orders.setMassageTypeId(userPackageDetail.getMassageTypeId());
        }
        massageTypeName = userPackageDetail.getTitle();
        orders.setEntryName(massageTypeName);
        orders.setMassagePrice(packagePrice);
        //保存现价
        orders.setPrice(price);

        //技师加成金额
        orders.setTechnicianMoney(BigDecimal.ZERO);
        //技师加成后总额
        orders.setPriceMarkup(packagePrice);
        //会员减免金额
        orders.setVipReductionMoney(BigDecimal.ZERO);

        BigDecimal payMoney = packagePrice;
        orders.setMassageMoney(payMoney);

        String value1 = commonInfoService.findOne(395).getValue();
        Integer tripWay = orders.getTripWay();
        BigDecimal taxiMoney = BigDecimal.ZERO;

        String isTravelFree = commonInfoService.findOne(460).getValue();
        if(isTravelFree.equals("是")){
            taxiMoney = BigDecimal.ZERO;
            tripWay = 3;
            orders.setTripWay(3);
        }
        TravelPriceVo travelPriceVo = travelConfService.calcTravelPrice(orders.getArtificerId(), orders.getLongitude(), orders.getLatitude(),orders.getServeTime(),tripWay);
        if (travelPriceVo == null) {
            return Result.error("暂不支持当前地址，请更换其他地址！");
        }
        taxiMoney = new BigDecimal(travelPriceVo.getTravelPrice());
        orders.setTaxiMoney(taxiMoney);
        orders.setKm(travelPriceVo.getKilometerNum());
        orders.setUsualTravelMoney(travelPriceVo.getUsualTravelMoney());
        orders.setNightTravelMoney(travelPriceVo.getNightTravelMoney());
        if (orders.getParentId() == null || orders.getParentId() == 0) {
            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(userPackageDetail.getDuration(),serveTime,value1,tripWay,orders.getArtificerId());
            if(map.get("code").toString().equals("1")){
                return Result.error("预约时间正忙，请更换其他时间！");
            }
        } else {
            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(userPackageDetail.getDuration(),serveTime,value1,orders.getArtificerId());
                if(map.get("code").toString().equals("1")){
                    return Result.error("预约时间正忙，请更换其他时间！");
                }
            }
        }
        //加上车费
        BigDecimal subtract = payMoney;
        payMoney = payMoney.add(taxiMoney);
        payMoney = payMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
        orders.setPayMoney(payMoney);

        //计算用户收益 ！计算前先减去通行费用再计算技师抽成
        artificerPrice = subtract.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
        //查询是否计算出租车扣费
        String taxi = commonInfoService.findOne(394).getValue();
        //计算技师出租车收益（按照技师表收益计算）
        if ("是".equals(taxi)) {
            //计算技师应该收取的出租车费用
            BigDecimal artificerTaxiMoney = taxiMoney.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
            //计算出租车扣款
            BigDecimal pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney).setScale(2,BigDecimal.ROUND_HALF_UP);
            //赋值技师出租收款
            orders.setArtificerTaxiMoney(artificerTaxiMoney);
            //赋值出租车扣款
            orders.setPingTaxiMoney(pingTaxiMoney);
            //用户收益加上通行费用
            artificerPrice = artificerPrice.add(artificerTaxiMoney);
        } else {
            //平台不扣费 出租车收益全由技师收取
            orders.setArtificerTaxiMoney(orders.getTaxiMoney());
            //设置出租车扣款为0
            orders.setPingTaxiMoney(BigDecimal.ZERO);
            //用户收益加上通行费用
            artificerPrice = artificerPrice.add(taxiMoney);
        }
        orders.setArtificerMoney(artificerPrice);
        orders.setSumArtificerMoney(orders.getArtificerMoney());

        //计算项目收益
        //获取项目应支付金额
//        BigDecimal projectBenefits  = orders.getMassageMoney();
        BigDecimal projectBenefits  = subtract;
        //计算技师项目提成金额
        orders.setProjectBenefits(projectBenefits.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP));

        orders.setOrdersNo(getGeneralOrder());
        orders.setStatus(1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orders.setCreateTime(sdf.format(new Date()));
        //留存订单生成时的技师分成比例
        orders.setArtificerRate(artificer.getRate());
        orders.setSumMoney(orders.getPayMoney().setScale(2,BigDecimal.ROUND_HALF_UP));
        //保存订单
        baseMapper.insert(orders);

        //更新服务套餐子项使用状态
        userPackageDetail.setStatus(1);
        userPackageDetailService.updateById(userPackageDetail);

//下单时不做电话通知，2024-06-20 10：11 by caolei
//        if(ObjectUtil.equals(orders.getParentId(),null) || ObjectUtil.equals(orders.getParentId(),0L)){
//            //技师电话通知业务
//            UserEntity byId = userService.getById(artificer.getUserId());
//            //accountId
//            String accountId = commonInfoService.findOne(428).getValue();
//            //token
//            String token = commonInfoService.findOne(429).getValue();
//            //templateId
//            String templateId = commonInfoService.findOne(430).getValue();
//            AppNotifyUtil.AppNotify(byId.getPhone(),accountId,token,templateId);
//        }
        for (OrdersMassage ordersMassage : ordersMassageList) {
            ordersMassage.setOrdersId(orders.getOrdersId());
            ordersMassageService.save(ordersMassage);
        }
        return Result.success().put("data", orders);
    }

    /**
     * 入参与insertOrders一致，就是没有代金券
     * 判断差额，如差额为0则修改原单据，如差额不为0则新增单据。
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public Result updateOrders(Orders orders) {
        try {
            Orders oldOrders = baseMapper.selectById(orders.getOrdersId());

            if (oldOrders.getStatus() == 3 || oldOrders.getStatus() == 5) {
                return Result.error("已完成的订单不可修改！");
            }
            if (oldOrders.getStatus() == 4) {
                return Result.error("已取消的订单不可修改！");
            }
            if (oldOrders.getStatus() == 1) {
                return Result.error("未支付的订单不可修改，请取消后重新下单！");
            }
            int dbd = 0;
            int sjd = 0;
            int xgd = 0;
            if(oldOrders.getStatus().equals(11)){
                List<Orders> newOrders = baseMapper.getNewOrdersByOld(orders.getOrdersId());
                if(newOrders.size()>0){
                    for(Orders newOrder : newOrders){
                        if(newOrder.getStatus()==1 || newOrder.getStatus()==4) {
                            if (newOrder.getIsSupplement().equals(1)) {
                                dbd = 1;
                                break;
                            }
                            if (newOrder.getIsSupplement().equals(2)) {
                                sjd = 1;
                                break;
                            }
                            if (newOrder.getIsSupplement().equals(3) || newOrder.getIsSupplement().equals(4)) {
                                xgd = 1;
                                break;
                            }
                        }
                    }
                }
            }
            //待补单修改
            if (oldOrders.getStatus() == 10 || dbd == 1) {
                //只能修改，技师和时间 （技师等级大于等于原单据等级）
                Long massageTypeId;
                if (orders.getOrdersMassageList() != null) {
                    List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                    if(orders.getUserPackageDetailId() != null) {
                        UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
                        massageTypeId = userPackageDetail.getMassageTypeId();
                        orders.setUserPackageId(userPackageDetail.getMainId());
                    }else{
                        massageTypeId = ordersMassageList.get(0).getMassageId();
                    }
                } else {
                    return Result.error("当前订单没有选择服务项目！");
                }
                Long oldMassageTypeId = oldOrders.getMassageTypeId();
                if (!massageTypeId.equals(oldMassageTypeId)) {
                    return Result.error("当前订单无法修改服务项目！");
                }
                Artificer artificer = artificerService.getById(orders.getArtificerId());
                Artificer oldArtificer = artificerService.getById(oldOrders.getArtificerId());
                if (artificer.getTechnicianType() != oldArtificer.getTechnicianType()) {
                    return Result.error("当前订单技师等级与原订单技师等级不一致！");
                }

                MassageType massageType = massageTypeService.getById(massageTypeId);
                orders.setMassageTypeId(massageTypeId);
                orders.setEntryName(massageType.getTitle());
                orders.setDuration(massageType.getDuration());
                orders.setPrice(BigDecimal.ZERO);
                orders.setMassageMoney(oldOrders.getMassageMoney());

                Date serveTimeDate = DateUtils.stringToDate(orders.getServeTime(), "yyyy-MM-dd HH:mm");
                if(serveTimeDate.getTime() < (new Date()).getTime()){
                    return Result.error("服务时间不能晚于当前时间！");
                }

                String value1 = commonInfoService.findOne(395).getValue();
                Integer tripWay = orders.getTripWay();

                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(),serveTime,value1,tripWay,orders.getArtificerId());
                if(map.get("code").toString().equals("1")){
                    return Result.error("预约时间正忙，请更换其他时间！");
                }

                TravelPriceVo travelPriceVo = null;
                if(orders.getUserPackageDetailId() != null) {
                    String isTravelFree = commonInfoService.findOne(460).getValue();
                    if(isTravelFree.equals("是")){
                        tripWay = 3;
                        orders.setTripWay(3);
                        travelPriceVo = travelConfService.calcTravelPrice(orders.getArtificerId(), orders.getLongitude(), orders.getLatitude(),orders.getServeTime(),tripWay);
                    }
                }else{
                    travelPriceVo = travelConfService.calcTravelPrice(orders.getArtificerId(), orders.getLongitude(), orders.getLatitude(),orders.getServeTime());
                }
                if (travelPriceVo == null) {
                    return Result.error("暂不支持当前地址，请更换其他地址！");
                }
                //删除未支付，无用的升级新单据
                List<Orders> newList = baseMapper.getNewOrdersByOld(oldOrders.getOrdersId());
                if(newList.size()>0){
                    for(Orders newOrder : newList){
                        if(newOrder.getStatus()==1 || newOrder.getStatus()==4){
                            baseMapper.deleteById(newOrder.getOrdersId());
                            ordersMassageService.removeByOrdersId(newOrder.getOrdersId());
                        }
                    }
                }
                BigDecimal taxiMoney = new BigDecimal(travelPriceVo.getTravelPrice());
                taxiMoney = taxiMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
                orders.setTaxiMoney(taxiMoney);
                orders.setKm(travelPriceVo.getKilometerNum());
                orders.setUsualTravelMoney(travelPriceVo.getUsualTravelMoney());
                orders.setNightTravelMoney(travelPriceVo.getNightTravelMoney());
                orders.setPayMoney(taxiMoney);
                orders.setStatus(1);
                orders.setCreateTime(DateUtils.format(new Date()));
//            Artificer artificer = artificerService.getById(orders.getArtificerId());
                orders.setArtificerRate(artificer.getRate());
                orders.setSumMoney(orders.getPayMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
                orders.setIsSupplement(1);
                orders.setProjectBenefits(BigDecimal.ZERO);
                orders.setVipRate(oldOrders.getVipRate());
                orders.setMassagePrice(oldOrders.getMassagePrice());
                orders.setMassageNum(oldOrders.getMassageNum());
                orders.setOrdersNo(getGeneralOrder());
                orders.setPrice(oldOrders.getPrice());
                orders.setCouponMoney(oldOrders.getCouponMoney());
                orders.setTechnicianType(artificer.getTechnicianType());
                orders.setTechnicianRate(oldOrders.getTechnicianRate());
                orders.setDuration(oldOrders.getDuration());

                orders.setTechnicianMoney(oldOrders.getTechnicianMoney());
                orders.setPriceMarkup(oldOrders.getPriceMarkup());
                orders.setVipReductionMoney(oldOrders.getVipReductionMoney());

                orders.setOldOrdersId(oldOrders.getOrdersId());
                orders.setOldMassageMoney(oldOrders.getMassageMoney());
                orders.setOldPayMoney(oldOrders.getPayMoney());
                orders.setOldMassageTypeId(oldOrders.getMassageTypeId());
                orders.setOldEntryName(oldOrders.getEntryName());
                orders.setOldMassagePrice(oldOrders.getMassagePrice());
                orders.setOldMassageNum(oldOrders.getMassageNum());
                orders.setOldMassageDuration(oldOrders.getDuration());
                orders.setOldPriceMarkup(oldOrders.getPriceMarkup());
                orders.setOldTechnicianMoney(oldOrders.getTechnicianMoney());
                orders.setOldVipReductionMoney(oldOrders.getVipReductionMoney());

                Orders ordersOld = new Orders();
                ordersOld.setOrdersId(oldOrders.getOrdersId());
                ordersOld.setStatus(11);
                ordersOld.setArtificerId(orders.getArtificerId());
                ordersOld.setArtificerRate(orders.getArtificerRate());
                ordersOld.setArtificerTaxiMoney(BigDecimal.ZERO);
                ordersOld.setPingTaxiMoney(BigDecimal.ZERO);

                BigDecimal massageMoney = oldOrders.getMassageMoney();
                if(oldOrders.getCouponMoney()!=null){
                    massageMoney = massageMoney.subtract(oldOrders.getCouponMoney());
                }
                BigDecimal subtract = oldOrders.getPayMoney();
                //计算用户收益
                BigDecimal artificerPrice = subtract.multiply(artificer.getRate());
                artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

                if(oldOrders.getPayWay().equals(5)){
                    BigDecimal rate = new BigDecimal(commonInfoService.findOne(449).getValue());
                    ordersOld.setWalletRate(rate);
                    rate = rate.divide(new BigDecimal(100));

                    BigDecimal valueStorageDeduction = artificerPrice;

                    artificerPrice = artificerPrice.multiply(rate);
                    artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

                    valueStorageDeduction = valueStorageDeduction.subtract(artificerPrice);
                    ordersOld.setValueStorageDeduction(valueStorageDeduction);
                    ordersOld.setProjectBenefits(artificerPrice);
                }else{
                    ordersOld.setValueStorageDeduction(BigDecimal.ZERO);
                    //计算技师项目提成金额
                    ordersOld.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) {
//                    ordersOld.setOneArtificerUserId(oneArtificerUser.getUserId());
//                    ordersOld.setOneArtificerUserName(oneArtificerUser.getUserName());
//                    oneArtificerMoney = artificerPrice.multiply(oneArtificerUser.getShopRate());
//                    oneArtificerMoney = oneArtificerMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
//                }
//                ordersOld.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) {
                            ordersOld.setConsortiaId(consortia.getConsortiaId());
                            ordersOld.setShopUserId(consortiaUser.getUserId());
                            ordersOld.setShopUserName(consortiaUser.getUserName());
                            shopMoney = artificerPrice.multiply(consortia.getRate());
                            shopMoney = shopMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }
                ordersOld.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) {
                    ordersOld.setOneUserId(oneUser.getUserId());
                    ordersOld.setOneUserName(oneUser.getUserName());
                    oneUserMoney = artificerPrice.multiply(oneUser.getUserRate());
                    oneUserMoney = oneUserMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                ordersOld.setOneUserMoney(oneUserMoney);
//                artificerPrice = artificerPrice.subtract(oneArtificerMoney);
                artificerPrice = artificerPrice.subtract(jjrMoney);
                artificerPrice = artificerPrice.subtract(shopMoney);
                artificerPrice = artificerPrice.subtract(oneUserMoney);
                ordersOld.setArtificerMoney(artificerPrice);
                ordersOld.setSumArtificerMoney(artificerPrice);

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

                baseMapper.updateById(ordersOld);//原单暂变成挂单状态

                orders.setOldArtificerMoney(ordersOld.getArtificerMoney());
                orders.setOldProjectBenefits(ordersOld.getProjectBenefits());

                baseMapper.insert(orders);

                ordersMassageService.removeByOrdersId(orders.getOrdersId());
                List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                for (OrdersMassage ordersMassage : ordersMassageList) {
                    ordersMassage.setOrdersId(orders.getOrdersId());
                    ordersMassageService.save(ordersMassage);
                }

                return Result.success().put("data", orders);
            }
            //进行中项目升级
            if (oldOrders.getStatus() == 6 || sjd == 1) {
                //升级项目操作，只能修改，项目（金额大于等于当前项目金额）
                if (StringUtils.isNotBlank(orders.getServeTime()) && !orders.getServeTime().equals(oldOrders.getServeTime())) {
                    return Result.error("当前订单无法修改时间！");
                }
                if (orders.getArtificerId() != null && !orders.getArtificerId().equals(oldOrders.getArtificerId())) {
                    return Result.error("当前订单无法修改技师！");
                }
                if (oldOrders.getParentId() != null && oldOrders.getParentId() != 0) {
                    return Result.error("当前加钟订单无法升级套餐！");
                }
                Long massageTypeId;
                BigDecimal price = BigDecimal.ZERO;
                int timeDifference = 0;//服务时长差
                if (orders.getOrdersMassageList() != null) {
                    List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                    massageTypeId = ordersMassageList.get(0).getMassageId();
                    MassageType massageType = massageTypeService.getById(massageTypeId);
                    orders.setDuration(massageType.getDuration());
                    if(massageType.getDuration().compareTo(oldOrders.getDuration()) > 0){
                        timeDifference = massageType.getDuration()-oldOrders.getDuration();
                    }else{
                        orders.setDuration(oldOrders.getDuration());
                    }
                    for (OrdersMassage ordersMassage : ordersMassageList) {
                        orders.setMassageNum(ordersMassage.getNum());
                        price = massageType.getPrice().multiply(BigDecimal.valueOf(ordersMassage.getNum())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }

                    orders.setMassagePrice(price);
                    orders.setPrice(price);
                    orders.setMassageTypeId(massageTypeId);
                    orders.setEntryName(massageType.getTitle());

                    //判断新price是否大于旧price
                    if (orders.getPrice().compareTo(oldOrders.getPrice()) <= 0) {
                        return Result.error("要升级的服务项目金额应大于原服务项目金额！");
                    }
                } else {
                    return Result.error("当前订单没有选择服务项目！");
                }

                String value1 = commonInfoService.findOne(395).getValue();
                if ("是".equals(value1)) {
                    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("预约时间正忙，请更换其他时间！");
                    }
                }
                //删除未支付，无用的升级新单据
                List<Orders> newList = baseMapper.getNewOrdersByOld(oldOrders.getOrdersId());
                if(newList.size()>0){
                    for(Orders newOrder : newList){
                        if(newOrder.getStatus()==1 || newOrder.getStatus()==4){
                            baseMapper.deleteById(newOrder.getOrdersId());
                            ordersMassageService.removeByOrdersId(newOrder.getOrdersId());
                        }
                    }
                }

                //使用原价计算差额
                orders.setUserId(oldOrders.getUserId());
                orders.setUserName(oldOrders.getUserName());
                orders.setPhone(oldOrders.getPhone());
                orders.setAddress(oldOrders.getAddress());
                orders.setRemark(oldOrders.getRemark());
                orders.setServeTime(oldOrders.getServeTime());
                orders.setArtificerStartTime(oldOrders.getArtificerStartTime());
                orders.setArtificerEndTime(oldOrders.getArtificerEndTime());
                orders.setLongitude(oldOrders.getLongitude());
                orders.setLatitude(oldOrders.getLatitude());
                orders.setStartLongitude(oldOrders.getStartLongitude());
                orders.setStartLatitude(oldOrders.getStartLatitude());
                orders.setTripWay(oldOrders.getTripWay());
                orders.setTaxiMoney(oldOrders.getTaxiMoney());
                orders.setKm(oldOrders.getKm());
                orders.setUsualTravelMoney(oldOrders.getUsualTravelMoney());
                orders.setNightTravelMoney(oldOrders.getNightTravelMoney());
                orders.setStartAddress(oldOrders.getStartAddress());
                orders.setStartTime(oldOrders.getStartTime());
                orders.setCouponId(oldOrders.getCouponId());
                orders.setCouponName(oldOrders.getCouponName());
                orders.setCouponMoney(oldOrders.getCouponMoney());
                orders.setEndTime(oldOrders.getEndTime());
                orders.setStartImg(oldOrders.getStartImg());
                orders.setOldOrdersId(oldOrders.getOrdersId());
                orders.setOldMassageMoney(oldOrders.getMassageMoney());
                orders.setOldPayMoney(oldOrders.getPayMoney());
                orders.setOldMassageTypeId(oldOrders.getMassageTypeId());
                orders.setOldEntryName(oldOrders.getEntryName());
                orders.setOldMassagePrice(oldOrders.getMassagePrice());
                orders.setOldMassageNum(oldOrders.getMassageNum());
                orders.setOldMassageDuration(oldOrders.getDuration());
                orders.setOldArtificerMoney(oldOrders.getArtificerMoney());
                orders.setArtificerTaxiMoney(oldOrders.getArtificerTaxiMoney());
                orders.setOldPriceMarkup(oldOrders.getPriceMarkup());
                orders.setOldTechnicianMoney(oldOrders.getTechnicianMoney());
                orders.setOldVipReductionMoney(oldOrders.getVipReductionMoney());
                if(oldOrders.getIsSupplement()!=null){
                    if(oldOrders.getIsSupplement().equals(1)){
                        BigDecimal projectBenefits = oldOrders.getProjectBenefits().add(oldOrders.getOldProjectBenefits());
                        orders.setOldProjectBenefits(projectBenefits);
                    }else{
                        orders.setOldProjectBenefits(oldOrders.getProjectBenefits());
                    }
                }else{
                    orders.setOldProjectBenefits(oldOrders.getProjectBenefits());
                }

                //获取用户VIP的优惠信息
                BigDecimal vipRate = new BigDecimal(100);
                UserVip userVip = userVipService.selectUserVipByUserId(oldOrders.getUserId());
                if (userVip != null) {
                    if (userVip.getIsVip() == 1) {
                        //获取用户到期时间
                        Date date = null;
                        try {
                            date = DateUtils.stringToDate(userVip.getEndTime(), DateUtils.DATE_TIME_PATTERN);
                            if (date.getTime() >= System.currentTimeMillis()) {
                                VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", userVip.getVipNameType()));
                                if (vipDetails != null) {
                                    vipRate = vipDetails.getRate();
                                }
                            }
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                }
                orders.setVipRate(vipRate);
                Artificer artificer = artificerService.getById(oldOrders.getArtificerId());
                orders.setArtificerId(artificer.getArtificerId());
                orders.setTechnicianType(artificer.getTechnicianType());

                BigDecimal artificerVipRate = BigDecimal.ZERO;
                VipDetails artificerVipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", artificer.getTechnicianType()));
                if (artificerVipDetails != null) {
                    artificerVipRate = artificerVipDetails.getRate();
                }
                orders.setTechnicianRate(artificerVipRate);

                //技师加成金额
                BigDecimal technicianMoney = price.multiply(orders.getTechnicianRate()).divide(new BigDecimal(100));
                technicianMoney = technicianMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
                orders.setTechnicianMoney(technicianMoney);
                //技师加成后总额
                BigDecimal priceMarkup = technicianMoney.add(price);
                priceMarkup = priceMarkup.setScale(2,BigDecimal.ROUND_HALF_UP);
                orders.setPriceMarkup(priceMarkup);

                //会员优惠后金额，及会员减免金额
                BigDecimal vipMoney = priceMarkup.multiply(orders.getVipRate()).divide(new BigDecimal(100));
                vipMoney = vipMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
                BigDecimal vipReductionMoney = priceMarkup.subtract(vipMoney);
                orders.setVipReductionMoney(vipReductionMoney);

                BigDecimal chajia = orders.getPriceMarkup().subtract(oldOrders.getPriceMarkup());

//                BigDecimal chajiaTechnicianMoney = chajia.multiply(orders.getTechnicianRate()).divide(new BigDecimal(100));
//                chajiaTechnicianMoney = chajiaTechnicianMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
//                orders.setTechnicianMoney(chajiaTechnicianMoney);

//                BigDecimal chajiaPriceMarkup = chajiaTechnicianMoney.add(chajia);

                BigDecimal chajiaVipMoney = chajia.subtract(vipReductionMoney);

//                BigDecimal chajiaVipMoney = chajia.multiply(orders.getVipRate()).divide(new BigDecimal(100));
//                chajiaVipMoney = chajiaVipMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
//                BigDecimal chajiaVipReductionMoney = chajia.subtract(chajiaVipMoney);
//                orders.setVipReductionMoney(chajiaVipReductionMoney);

                //项目价格 = 会员金额
                BigDecimal massagePrice = chajiaVipMoney;
                orders.setMassageMoney(massagePrice);
                orders.setPayMoney(massagePrice);//差价

                //计算技师项目提成金额
                BigDecimal artificerPrice = massagePrice.multiply(artificer.getRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                orders.setProjectBenefits(artificerPrice);
                orders.setArtificerMoney(artificerPrice);
                orders.setSumArtificerMoney(artificerPrice);
                orders.setOrdersNo(getGeneralOrder());
                orders.setStatus(1);
                orders.setCreateTime(DateUtils.format(new Date()));
                orders.setIsSupplement(2);
                orders.setArtificerRate(artificer.getRate());
                orders.setSumMoney(orders.getPayMoney());
                baseMapper.insert(orders);

                ordersMassageService.removeByOrdersId(orders.getOrdersId());
                List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                for (OrdersMassage ordersMassage : ordersMassageList) {
                    ordersMassage.setOrdersId(orders.getOrdersId());
                    ordersMassageService.save(ordersMassage);
                }

                Orders ordersOld = new Orders();
                ordersOld.setOrdersId(oldOrders.getOrdersId());
                ordersOld.setStatus(11);
                baseMapper.updateById(ordersOld);//原单暂变成挂单状态
                return Result.success().put("data", orders);
            }
            if (oldOrders.getStatus() == 2 || oldOrders.getStatus() == 9 || xgd == 1) {
                //只能修改，技师和时间 （技师等级大于等于原单据等级）
                //判断是否是可修改，状态2 9
                boolean canUpdate = commonInfoService.isCheckEditOrder(DateUtils.stringToDate(oldOrders.getServeTime(), "yyyy-MM-dd HH:mm"), new Date());
                if (!canUpdate) {
                    return Result.error("当前订单已过修改时限无法修改！");
                }
                //判断是否是修改后的订单再继续修改

                if (oldOrders.getOldOrdersId() != null && oldOrders.getOldOrdersId() != 0) {
                    return Result.error("当前订单是修改后生成的新订单无法修改！");
                }
                Long massageTypeId;
                BigDecimal price = BigDecimal.ZERO;
                MassageType massageType = null;
                if (orders.getOrdersMassageList() != null) {
                    List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                    if(orders.getUserPackageDetailId() != null) {
                        UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
                        massageTypeId = userPackageDetail.getMassageTypeId();
                        orders.setUserPackageId(userPackageDetail.getMainId());
                    }else{
                        massageTypeId = ordersMassageList.get(0).getMassageId();
                    }

                    massageType = massageTypeService.getById(massageTypeId);
                    orders.setMassageTypeId(massageTypeId);
                    orders.setEntryName(massageType.getTitle());
                    orders.setDuration(massageType.getDuration());

                    for (OrdersMassage ordersMassage : ordersMassageList) {
                        orders.setMassageNum(ordersMassage.getNum());
                        price = massageType.getPrice().multiply(BigDecimal.valueOf(ordersMassage.getNum())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    orders.setMassagePrice(price);
                    orders.setPrice(price);
                } else {
                    return Result.error("当前订单没有选择服务项目！");
                }

                Date serveTimeDate = DateUtils.stringToDate(orders.getServeTime(), "yyyy-MM-dd HH:mm");
                if(serveTimeDate.getTime() < (new Date()).getTime()){
                    return Result.error("服务时间不能晚于当前时间！");
                }

                //判断新price是否大于旧price
                if (price.compareTo(oldOrders.getPrice()) < 0) {
                    return Result.error("当前订单的服务项目金额不能小于原服务项目金额！");
                }

                String value1 = commonInfoService.findOne(395).getValue();
                Integer tripWay = orders.getTripWay();
                BigDecimal taxiMoney = BigDecimal.ZERO;
                if(orders.getUserPackageDetailId() != null) {
                    String isTravelFree = commonInfoService.findOne(460).getValue();
                    if(isTravelFree.equals("是")){
                        taxiMoney = BigDecimal.ZERO;
                        tripWay = 3;
                        orders.setTripWay(3);
                    }
                }

                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(massageType.getDuration(),serveTime,value1,tripWay,orders.getArtificerId(),orders.getOrdersId());
                if(map.get("code").toString().equals("1")){
                    return Result.error("预约时间正忙，请更换其他时间！");
                }

                Artificer artificer = artificerService.getById(orders.getArtificerId());
                Artificer oldArtificer = artificerService.getById(oldOrders.getArtificerId());
                if (artificer.getTechnicianType() < oldArtificer.getTechnicianType()) {
                    return Result.error("当前订单技师等级不能低于原订单技师等级！");
                }

                orders.setArtificerId(artificer.getArtificerId());
                orders.setTechnicianType(artificer.getTechnicianType());
                orders.setArtificerRate(artificer.getRate());
                BigDecimal artificerVipRate = BigDecimal.ZERO;
                VipDetails artificerVipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", artificer.getTechnicianType()));
                if (artificerVipDetails != null) {
                    artificerVipRate = artificerVipDetails.getRate();
                }
                orders.setTechnicianRate(artificerVipRate);
                //获取用户VIP的优惠信息
                BigDecimal vipRate = new BigDecimal(100);
                UserVip userVip = userVipService.selectUserVipByUserId(oldOrders.getUserId());
                if (userVip != null) {
                    if (userVip.getIsVip() == 1) {
                        //获取用户到期时间
                        Date date2 = null;
                        try {
                            date2 = DateUtils.stringToDate(userVip.getEndTime(), DateUtils.DATE_TIME_PATTERN);
                            if (date2.getTime() >= System.currentTimeMillis()) {
                                VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("vip_name_type", userVip.getVipNameType()));
                                if (vipDetails != null) {
                                    vipRate = vipDetails.getRate();
                                }
                            }
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                }
                orders.setVipRate(vipRate);

                if(orders.getUserPackageDetailId() != null) {
                    //技师加成金额
                    orders.setTechnicianMoney(BigDecimal.ZERO);
                    //技师加成后总额
                    orders.setPriceMarkup(price);
                    //会员优惠后金额，及会员减免金额
                    orders.setVipReductionMoney(BigDecimal.ZERO);
                    //项目价格 = 会员金额
                    orders.setMassageMoney(price);
                }else{
                    //技师加成金额
                    BigDecimal technicianMoney = price.multiply(orders.getTechnicianRate()).divide(new BigDecimal(100));
                    technicianMoney = technicianMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
                    orders.setTechnicianMoney(technicianMoney);

                    //技师加成后总额
                    BigDecimal priceMarkup = technicianMoney.add(price);
                    priceMarkup = priceMarkup.setScale(2,BigDecimal.ROUND_HALF_UP);
                    orders.setPriceMarkup(priceMarkup);

                    //会员优惠后金额，及会员减免金额
                    BigDecimal vipMoney = priceMarkup.multiply(orders.getVipRate()).divide(new BigDecimal(100));
                    vipMoney = vipMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal vipReductionMoney = priceMarkup.subtract(vipMoney);
                    orders.setVipReductionMoney(vipReductionMoney);

                    //项目价格 = 会员金额
                    BigDecimal payMoney = vipMoney;
                    orders.setMassageMoney(payMoney);
                }


                //项目差价
                BigDecimal xmchajia = orders.getMassageMoney().subtract(oldOrders.getMassageMoney());
                TravelPriceVo travelPriceVo = null;
                if(orders.getUserPackageDetailId() != null) {
                    travelPriceVo = travelConfService.calcTravelPrice(orders.getArtificerId(), orders.getLongitude(), orders.getLatitude(),orders.getServeTime(),tripWay);
                }else{
                    travelPriceVo = travelConfService.calcTravelPrice(orders.getArtificerId(), orders.getLongitude(), orders.getLatitude(),orders.getServeTime());
                }
                if (travelPriceVo == null) {
                    return Result.error("暂不支持当前地址，请更换其他地址！");
                }
                //删除未支付，无用的升级新单据
                List<Orders> newList = baseMapper.getNewOrdersByOld(oldOrders.getOrdersId());
                if(newList.size()>0){
                    for(Orders newOrder : newList){
                        if(newOrder.getStatus()==1 || newOrder.getStatus()==4){
                            baseMapper.deleteById(newOrder.getOrdersId());
                            ordersMassageService.removeByOrdersId(newOrder.getOrdersId());
                        }
                    }
                }
                taxiMoney = new BigDecimal(travelPriceVo.getTravelPrice());
                BigDecimal usualTravelMoney = travelPriceVo.getUsualTravelMoney();
                BigDecimal nightTravelMoney = travelPriceVo.getNightTravelMoney();
                taxiMoney = taxiMoney.setScale(2,BigDecimal.ROUND_HALF_UP);
                BigDecimal oldTaxiMoney = oldOrders.getTaxiMoney();
                BigDecimal oldUsualTravelMoney = oldOrders.getUsualTravelMoney();
                BigDecimal oldNightTravelMoney = oldOrders.getNightTravelMoney();
                if (taxiMoney.compareTo(oldTaxiMoney) < 0) {
                    taxiMoney = oldTaxiMoney;
                    usualTravelMoney = oldUsualTravelMoney;
                    nightTravelMoney = oldNightTravelMoney;
                }
                orders.setTaxiMoney(taxiMoney);
                orders.setKm(travelPriceVo.getKilometerNum());
                orders.setUsualTravelMoney(usualTravelMoney);
                orders.setNightTravelMoney(nightTravelMoney);
                //出行交通费差价
//                BigDecimal cxchajia = taxiMoney.subtract(oldTaxiMoney);
                BigDecimal pccxchajia = usualTravelMoney.subtract(oldUsualTravelMoney);
                BigDecimal yjcxchajia = nightTravelMoney.subtract(oldNightTravelMoney);
                BigDecimal cxchajia = pccxchajia.subtract(yjcxchajia);
                //总差价
                BigDecimal chajia = xmchajia.add(cxchajia);

                if (chajia.compareTo(BigDecimal.ZERO) == 0) {
                    orders.setPayMoney(oldOrders.getPayMoney());
                    BigDecimal artificerPrice = orders.getPayMoney().subtract(taxiMoney);
                    artificerPrice = artificerPrice.multiply(artificer.getRate());
                    artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

                    if(oldOrders.getPayWay().equals(5)){
                        BigDecimal valueStorageDeduction = artificerPrice;
                        BigDecimal rate = new BigDecimal(commonInfoService.findOne(449).getValue());
                        orders.setWalletRate(rate);
                        rate = rate.divide(new BigDecimal(100));
                        artificerPrice = artificerPrice.multiply(rate);
                        artificerPrice = artificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                        valueStorageDeduction = valueStorageDeduction.subtract(artificerPrice);
                        orders.setValueStorageDeduction(valueStorageDeduction);
                        orders.setProjectBenefits(artificerPrice);
                    }else{
                        orders.setValueStorageDeduction(BigDecimal.ZERO);
                        //计算技师项目提成金额
                        orders.setProjectBenefits(artificerPrice);
                    }

                    UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
                    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);
                    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);
                    orders.setStatus(9);
                    //总差价不变，则修改原单据
                    baseMapper.updateById(orders);
                    ordersMassageService.removeByOrdersId(orders.getOrdersId());
                    List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                    for (OrdersMassage ordersMassage : ordersMassageList) {
                        ordersMassage.setOrdersId(orders.getOrdersId());
                        ordersMassageService.save(ordersMassage);
                    }

                    //删除技师占用时间表数据
                    artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
                    //插入技师占用时间表时间差数据
                    List<String> allTime = (ArrayList)map.get("timeList");
                    if(allTime!=null && allTime.size()>0) {
                        for (int x=0;x<allTime.size();x++) {
                            String serveTime1 = allTime.get(x);
                            String date1 = serveTime1.substring(0, 10);
                            String time1 = serveTime1.substring(11, 16);
                            ArtificerTime artificerTime1 = new ArtificerTime();
                            artificerTime1.setArtificerId(orders.getArtificerId());
                            artificerTime1.setArtificerDate(date1);
                            artificerTime1.setArtificerTime(time1);
                            artificerTime1.setClassify(1);
                            artificerTime1.setOrdersId(orders.getOrdersId());
                            artificerTime1.setCreateTime(DateUtils.format(new Date()));
                            artificerTimeService.save(artificerTime1);
                        }
                    }
                    return Result.success().put("data", orders);
                } else {
                    //新增单据xmchajia
                    orders.setPayMoney(chajia);
                    orders.setTaxiMoney(cxchajia);
                    orders.setUsualTravelMoney(pccxchajia);
                    orders.setNightTravelMoney(yjcxchajia);
                    BigDecimal artificerPrice = BigDecimal.ZERO;
                    BigDecimal artificerTaxiPrice = BigDecimal.ZERO;
                    //查询是否计算出租车扣费
                    String taxi = commonInfoService.findOne(394).getValue();
                    //计算技师出租车收益（按照技师表收益计算）
                    if ("是".equals(taxi)) {
                        //计算技师应该收取的出租车费用
                        artificerTaxiPrice = cxchajia.multiply(artificer.getRate());
                        artificerTaxiPrice = artificerTaxiPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                        //计算出租车扣款
                        BigDecimal pingTaxiMoney = cxchajia.subtract(artificerTaxiPrice);
                        //赋值技师出租收款
                        orders.setArtificerTaxiMoney(artificerTaxiPrice);
                        //赋值出租车扣款
                        orders.setPingTaxiMoney(pingTaxiMoney);
                    } else {
                        //平台不扣费 出租车收益全由技师收取
                        artificerTaxiPrice = cxchajia;
                        orders.setArtificerTaxiMoney(cxchajia);
                        //设置出租车扣款为0
                        orders.setPingTaxiMoney(BigDecimal.ZERO);
                    }

                    //计算项目收益
                    //计算技师项目提成金额
                    artificerPrice = xmchajia.multiply(artificer.getRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    orders.setProjectBenefits(artificerPrice);
                    artificerPrice = artificerPrice.add(artificerTaxiPrice);
                    orders.setArtificerMoney(artificerPrice);
                    orders.setSumArtificerMoney(artificerPrice);
                    orders.setOrdersNo(getGeneralOrder());
                    orders.setStatus(1);
                    if (oldOrders.getStatus() == 2) {
                        orders.setIsSupplement(3);
                    }
                    if (oldOrders.getStatus() == 9) {
                        orders.setIsSupplement(4);
                    }
                    orders.setCreateTime(DateUtils.format(new Date()));
                    orders.setSumMoney(orders.getPayMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
                    orders.setOldOrdersId(oldOrders.getOrdersId());
                    orders.setOldMassageMoney(oldOrders.getMassageMoney());
                    orders.setOldPayMoney(oldOrders.getPayMoney());
                    orders.setOldMassageTypeId(oldOrders.getMassageTypeId());
                    orders.setOldEntryName(oldOrders.getEntryName());
                    orders.setOldMassagePrice(oldOrders.getMassagePrice());
                    orders.setOldMassageNum(oldOrders.getMassageNum());
                    orders.setOldMassageDuration(oldOrders.getDuration());
                    orders.setCouponName(oldOrders.getCouponName());
                    orders.setCouponMoney(oldOrders.getCouponMoney());
                    orders.setOldPriceMarkup(oldOrders.getPriceMarkup());
                    orders.setOldTechnicianMoney(oldOrders.getTechnicianMoney());
                    orders.setOldVipReductionMoney(oldOrders.getVipReductionMoney());
                    //保存订单
                    baseMapper.insert(orders);

                    ordersMassageService.removeByOrdersId(orders.getOrdersId());
                    List<OrdersMassage> ordersMassageList = orders.getOrdersMassageList();
                    for (OrdersMassage ordersMassage : ordersMassageList) {
                        ordersMassage.setOrdersId(orders.getOrdersId());
                        ordersMassageService.save(ordersMassage);
                    }

//                    //删除技师占用时间表旧数据
//                    artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", oldOrders.getOrdersId()));
//                    //插入技师占用时间表新数据
//                    List<String> allTime = (ArrayList)map.get("timeList");
//                    if(allTime!=null && allTime.size()>0) {
//                        for (int x=0;x<allTime.size();x++) {
//                            String serveTime1 = allTime.get(x);
//                            String date1 = serveTime1.substring(0, 10);
//                            String time1 = serveTime1.substring(11, 16);
//                            ArtificerTime artificerTime1 = new ArtificerTime();
//                            artificerTime1.setArtificerId(orders.getArtificerId());
//                            artificerTime1.setArtificerDate(date1);
//                            artificerTime1.setArtificerTime(time1);
//                            artificerTime1.setClassify(1);
//                            artificerTime1.setOrdersId(orders.getOrdersId());
//                            artificerTime1.setCreateTime(DateUtils.format(new Date()));
//                            artificerTimeService.save(artificerTime1);
//                        }
//                    }

                    Orders ordersOld = new Orders();
                    ordersOld.setOrdersId(oldOrders.getOrdersId());
                    ordersOld.setStatus(11);
                    ordersOld.setArtificerId(orders.getArtificerId());
                    ordersOld.setArtificerRate(orders.getArtificerRate());
                    ordersOld.setTechnicianRate(artificerVipRate);
                    //计算技师出租车收益（按照技师表收益计算）
                    if ("是".equals(taxi)) {
                        //计算技师应该收取的出租车费用
                        BigDecimal artificerTaxiMoney = oldOrders.getTaxiMoney().multiply(artificer.getRate());
                        artificerTaxiMoney = artificerTaxiMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                        //计算出租车扣款
                        BigDecimal pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney);
                        //赋值技师出租收款
                        ordersOld.setArtificerTaxiMoney(artificerTaxiMoney);
                        //赋值出租车扣款
                        ordersOld.setPingTaxiMoney(pingTaxiMoney);
                    } else {
                        //平台不扣费 出租车收益全由技师收取
                        ordersOld.setArtificerTaxiMoney(oldOrders.getTaxiMoney());
                        //设置出租车扣款为0
                        ordersOld.setPingTaxiMoney(BigDecimal.ZERO);
                    }
                    //计算用户收益
                    BigDecimal oldArtificerPrice = oldOrders.getPayMoney().subtract(oldOrders.getTaxiMoney());
                    oldArtificerPrice = oldArtificerPrice.multiply(artificer.getRate());
                    oldArtificerPrice = oldArtificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                    if(oldOrders.getPayWay().equals(5)){
                        BigDecimal rate = new BigDecimal(commonInfoService.findOne(449).getValue());
                        ordersOld.setWalletRate(rate);
                        rate = rate.divide(new BigDecimal(100));
                        BigDecimal oldValueStorageDeduction = oldArtificerPrice;
                        oldArtificerPrice = oldArtificerPrice.multiply(rate);
                        oldArtificerPrice = oldArtificerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                        oldValueStorageDeduction = oldValueStorageDeduction.subtract(oldArtificerPrice);
                        ordersOld.setValueStorageDeduction(oldValueStorageDeduction);
                        ordersOld.setProjectBenefits(oldArtificerPrice);
                    }else{
                        ordersOld.setValueStorageDeduction(BigDecimal.ZERO);
                        //计算技师项目提成金额
                        ordersOld.setProjectBenefits(oldArtificerPrice);
                    }

                    UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
                    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) {
                                ordersOld.setConsortiaId(consortia.getConsortiaId());
                                ordersOld.setShopUserId(consortiaUser.getUserId());
                                ordersOld.setShopUserName(consortiaUser.getUserName());
                                shopMoney = oldArtificerPrice.multiply(consortia.getRate());
                                shopMoney = shopMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                            }
                        }
                    }
                    ordersOld.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) {
                        ordersOld.setOneUserId(oneUser.getUserId());
                        ordersOld.setOneUserName(oneUser.getUserName());
                        oneUserMoney = oldArtificerPrice.multiply(oneUser.getUserRate());
                        oneUserMoney = oneUserMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                    }
                    ordersOld.setOneUserMoney(oneUserMoney);
//                    oldArtificerPrice = oldArtificerPrice.subtract(oneArtificerMoney);
                    oldArtificerPrice = oldArtificerPrice.subtract(jjrMoney);
                    oldArtificerPrice = oldArtificerPrice.subtract(shopMoney);
                    oldArtificerPrice = oldArtificerPrice.subtract(oneUserMoney);
                    ordersOld.setArtificerMoney(oldArtificerPrice);
                    ordersOld.setSumArtificerMoney(oldArtificerPrice);

                    //平台扣款
                    BigDecimal pingMoney = oldOrders.getPayMoney();
                    pingMoney = pingMoney.subtract(oldArtificerPrice);
                    pingMoney = pingMoney.subtract(shopMoney);
//                    pingMoney = pingMoney.subtract(oneArtificerMoney);
                    pingMoney = pingMoney.subtract(jjrMoney);
                    pingMoney = pingMoney.subtract(oneUserMoney);
                    ordersOld.setPingMoney(pingMoney);
                    baseMapper.updateById(ordersOld);//原单暂变成挂单状态
                    return Result.success().put("data", orders);
                }
            }
            return Result.error("此状态单据无法修改操作！");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result cancelOrdersMoney(Long userId, Long ordersId) {
        Orders orders = baseMapper.selectById(ordersId);
        if (orders.getStatus() == 4) {
            return Result.error("订单已经取消了！");
        }else if (orders.getStatus() == 1) {
            String remarks = "取消订单将扣除：0元的手续费！";
            return Result.success().put("data",remarks);
        }else if (orders.getStatus() == 3 || orders.getStatus() == 5) {
            return Result.error("订单已经完成了，无法取消！");
        }else if (orders.getStatus() == 6) {
            if(orders.getOldOrdersId() != null && orders.getOldOrdersId() != 0){
                return Result.error("项目升级之后，无法取消！");
            }
            if(orders.getParentId() != null && orders.getParentId() != 0){
                return Result.error("项目加钟之后，无法取消！");
            }
        }else if(orders.getStatus() == 10) {
            String remarks = "取消订单将扣除：0元的手续费！";
            return Result.success().put("data",remarks);

        }else if(orders.getStatus() == 9) {
            if(orders.getRefusalContent()!=null && !orders.getRefusalContent().equals("")){
                String remarks = "取消订单将扣除：0元的手续费！";
                return Result.success().put("data",remarks);
            }
        }
        //按时间扣款，获取扣款金额
        CommonInfo commonInfo = commonInfoService.isCheckChangeOrder(DateUtils.stringToDate(orders.getServeTime(),"yyyy-MM-dd HH:mm") ,new Date());
        CommonEnum commonEnum = CommonConfigUtil.getCommonEnumByKey(commonInfo.getType());
        String[] values = CommonConfigUtil.getArrayValue(commonInfo.getValue());
        BigDecimal massageDeduction = BigDecimal.ZERO;
        BigDecimal trafficDeduction = BigDecimal.ZERO;
        BigDecimal massageRate = BigDecimal.ZERO;
        BigDecimal trafficRate = BigDecimal.ZERO;
        if(CommonEnum.V3_ORDER_FORM_CANCEL_NOT_START_01 == commonEnum){
            //距离服务开始n分钟以上免费取消,全额退服务费和车费
            massageDeduction = BigDecimal.ZERO;
            trafficDeduction = BigDecimal.ZERO;
            massageRate = BigDecimal.ZERO;
            trafficRate = BigDecimal.ZERO;
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_NOT_START_02 == commonEnum){
            //距离服务开始前取消n-n分钟内，收取n元，扣服务费，全额退车费
            massageDeduction = new BigDecimal(values[2]);
            trafficDeduction = BigDecimal.ZERO;
            massageRate = BigDecimal.ZERO;
            trafficRate = BigDecimal.ZERO;
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_NOT_START_03 == commonEnum){
            //距离服务开始前取消少于n分钟内，收取n元，扣服务费，全额退车费
            massageDeduction = new BigDecimal(values[1]);
            trafficDeduction = BigDecimal.ZERO;
            massageRate = BigDecimal.ZERO;
            trafficRate = BigDecimal.ZERO;
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_START_01 == commonEnum){
            //服务开始n分钟内取消订单，扣项目费用n%，车费全扣n%,扣服务费和车费
            massageDeduction = BigDecimal.ZERO;
            trafficDeduction = BigDecimal.ZERO;
            massageRate = new BigDecimal(values[1]).divide(new BigDecimal(100));
            trafficRate = new BigDecimal(values[2]).divide(new BigDecimal(100));
        }
        if(orders.getUserPackageDetailId() !=null){
            return cancelPackageOrdersMoney(userId,orders,trafficDeduction,trafficRate);
        }else{
            return cancelMassageOrdersMoney(userId,orders,massageDeduction,trafficDeduction,massageRate,trafficRate);
        }
    }

    private Result cancelMassageOrdersMoney(Long userId, Orders orders, BigDecimal massageDeduction, BigDecimal trafficDeduction, BigDecimal massageRate, BigDecimal trafficRate) {
        //项目扣款
        BigDecimal massageMoneyDeduction = BigDecimal.ZERO;
        if(massageRate.compareTo(BigDecimal.ZERO) == 0){
            massageMoneyDeduction = massageDeduction;
        }else{
            massageMoneyDeduction = orders.getPayMoney().subtract(orders.getTaxiMoney()).multiply(massageRate).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        if(orders.getPayMoney().subtract(orders.getTaxiMoney()).compareTo(massageDeduction) < 0){
            massageMoneyDeduction = orders.getPayMoney().subtract(orders.getTaxiMoney());
        }
        //车费扣款
        BigDecimal taxiMoneyDeduction = BigDecimal.ZERO;
        if(trafficRate.compareTo(BigDecimal.ZERO) == 0){
            taxiMoneyDeduction = trafficDeduction;
        }else{
            taxiMoneyDeduction = orders.getTaxiMoney().multiply(trafficRate).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        if(orders.getTaxiMoney().compareTo(taxiMoneyDeduction) < 0){
            taxiMoneyDeduction = orders.getTaxiMoney();
        }
        //项目总扣款数
        BigDecimal sumMoney = massageMoneyDeduction.add(taxiMoneyDeduction);//总扣费

        String remarks = "取消订单将扣除："+sumMoney+"元的手续费，其中项目费将扣除："+massageMoneyDeduction+"元，车费将扣除："+taxiMoneyDeduction+"元！";
        return Result.success().put("data",remarks);
    }

    private Result cancelPackageOrdersMoney(Long userId, Orders orders, BigDecimal trafficDeduction, BigDecimal trafficRate){
        //车费扣款
        BigDecimal taxiMoneyDeduction = BigDecimal.ZERO;
        if(trafficRate.compareTo(BigDecimal.ZERO) == 0){
            taxiMoneyDeduction = trafficDeduction;
        }else{
            taxiMoneyDeduction = orders.getTaxiMoney().multiply(trafficRate).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        if(orders.getTaxiMoney().compareTo(taxiMoneyDeduction) < 0){
            taxiMoneyDeduction = orders.getTaxiMoney();
        }
        String remarks = "取消订单将扣除："+taxiMoneyDeduction+"元的手续费，其中车费将扣除："+taxiMoneyDeduction+"元！";
        return Result.success().put("data",remarks);
    }

    @Override
    @Transactional
    public Result cancelOrders(Long userId, Long ordersId) {
        Orders orders = baseMapper.selectById(ordersId);
        //状态 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中  7技师出发 8技师到达 9用户已支付技师待接单 10待补单
        if (orders.getStatus() == 4) {
            return Result.error("订单已经取消了！");
        } else if (orders.getStatus() == 3 || orders.getStatus() == 5) {
            return Result.error("订单已经完成了，无法取消！");
        }else if (orders.getStatus() == 6) {
            if(orders.getOldOrdersId() != null && orders.getOldOrdersId() != 0){
                return Result.error("项目升级之后，无法取消！");
            }
            if(orders.getParentId() != null && orders.getParentId() != 0){
                return Result.error("项目加钟之后，无法取消！");
            }
        }else if(orders.getStatus() == 10) {
            return cancelSupplementOrders(userId,ordersId,0,2);
        }else if(orders.getStatus() == 9) {
            if(orders.getRefusalContent()!=null && !orders.getRefusalContent().equals("")){
                return cancelSupplementOrders(userId,ordersId,0,3);
            }
        }
        switch (orders.getStatus()){
            case 1:
                orders.setCancelRemark("未支付-手动");
                break;
            case 2:
                orders.setCancelRemark("待服务-手动");
                break;
            case 6:
                orders.setCancelRemark("进行中-手动");
                break;
            case 7:
                orders.setCancelRemark("已出发-手动");
                break;
            case 8:
                orders.setCancelRemark("已到达-手动");
                break;
            case 9:
                orders.setCancelRemark("待接单-手动");
                break;
            case 10:
                orders.setCancelRemark("待补单-手动");
                break;
        }
        //按时间扣款，获取扣款金额
        CommonInfo commonInfo = commonInfoService.isCheckChangeOrder(DateUtils.stringToDate(orders.getServeTime(),"yyyy-MM-dd HH:mm") ,new Date());
        CommonEnum commonEnum = CommonConfigUtil.getCommonEnumByKey(commonInfo.getType());
        String[] values = CommonConfigUtil.getArrayValue(commonInfo.getValue());
        BigDecimal massageDeduction = BigDecimal.ZERO;
        BigDecimal trafficDeduction = BigDecimal.ZERO;
        BigDecimal massageRate = BigDecimal.ZERO;
        BigDecimal trafficRate = BigDecimal.ZERO;
        if(CommonEnum.V3_ORDER_FORM_CANCEL_NOT_START_01 == commonEnum){
            //距离服务开始n分钟以上免费取消,全额退服务费和车费
            massageDeduction = BigDecimal.ZERO;
            trafficDeduction = BigDecimal.ZERO;
            massageRate = BigDecimal.ZERO;
            trafficRate = BigDecimal.ZERO;
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_NOT_START_02 == commonEnum){
            //距离服务开始前取消n-n分钟内，收取n元，扣服务费，全额退车费
            massageDeduction = new BigDecimal(values[2]);
            trafficDeduction = BigDecimal.ZERO;
            massageRate = BigDecimal.ZERO;
            trafficRate = BigDecimal.ZERO;
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_NOT_START_03 == commonEnum){
            //距离服务开始前取消少于n分钟内，收取n元，扣服务费，全额退车费
            massageDeduction = new BigDecimal(values[1]);
            trafficDeduction = BigDecimal.ZERO;
            massageRate = BigDecimal.ZERO;
            trafficRate = BigDecimal.ZERO;
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_START_01 == commonEnum){
            //服务开始n分钟内取消订单，扣项目费用n%，车费全扣n%,扣服务费和车费
            massageDeduction = BigDecimal.ZERO;
            trafficDeduction = BigDecimal.ZERO;
            massageRate = new BigDecimal(values[1]).divide(new BigDecimal(100));
            trafficRate = new BigDecimal(values[2]).divide(new BigDecimal(100));
        }
        if(CommonEnum.V3_ORDER_FORM_CANCEL_START_02 == commonEnum){
            //服务开始n分钟后不可以取消订单
            return Result.error("订单已进行"+values[0]+"分钟后，无法取消！");
        }
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
        if(orders.getUserPackageDetailId() !=null){
            return cancelPackageOrders(userId,orders,trafficDeduction,trafficRate);
        }else{
            return cancelMassageOrders(userId,orders,massageDeduction,trafficDeduction,massageRate,trafficRate);
        }
    }

    @Transactional
    public Result cancelMassageOrders(Long userId, Orders orders, BigDecimal massageDeduction, BigDecimal trafficDeduction, BigDecimal massageRate, BigDecimal trafficRate){

        String couponIds = orders.getCouponId();
        if(orders.getCouponId() != null && couponIds.length()>0){
            String[] couponArr = couponIds.trim().split(",");
            for(int i=0;i<couponArr.length;i++){
                if(couponArr[i]!=null && !couponArr[i].equals("")){
                    Long couponId = Long.valueOf(couponArr[i]);
                    CouponUser couponUser = couponUserService.getById(couponId);
                    couponUser.setStatus(0);
                    couponUserService.updateById(couponUser);
                }
            }
        }

        if (orders.getStatus() == 1) {
            orders.setStatus(4);
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            //项目扣款
            BigDecimal massageMoneyDeduction = BigDecimal.ZERO;
            if(massageRate.compareTo(BigDecimal.ZERO) == 0){
                massageMoneyDeduction = massageDeduction;
            }else{
                massageMoneyDeduction = orders.getPayMoney().subtract(orders.getTaxiMoney()).multiply(massageRate).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if(orders.getPayMoney().subtract(orders.getTaxiMoney()).compareTo(massageDeduction) < 0){
                massageMoneyDeduction = orders.getPayMoney().subtract(orders.getTaxiMoney());
            }
            //车费扣款
            BigDecimal taxiMoneyDeduction = BigDecimal.ZERO;
            if(trafficRate.compareTo(BigDecimal.ZERO) == 0){
                taxiMoneyDeduction = trafficDeduction;
            }else{
                taxiMoneyDeduction = orders.getTaxiMoney().multiply(trafficRate).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if(orders.getTaxiMoney().compareTo(taxiMoneyDeduction) < 0){
                taxiMoneyDeduction = orders.getTaxiMoney();
            }

            //项目总扣款数
            BigDecimal rate = massageMoneyDeduction;
            //退款金额
            BigDecimal userMoney = orders.getPayMoney().subtract(rate).subtract(taxiMoneyDeduction);
            if(userMoney.compareTo(BigDecimal.ZERO) < 0 ){
                userMoney = BigDecimal.ZERO;
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                if(userMoney.compareTo(BigDecimal.ZERO) > 0){
                    boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), userMoney, orders.getPayWay());
                    if (!refund) {
                        return Result.error("退款失败，请联系客服！");
                    }
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else if (orders.getPayWay() == 6) {
                if(userMoney.compareTo(BigDecimal.ZERO) > 0) {
                    String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else {
                //暂无用
//                if (orders.getUserArtificerMoney() != null && orders.getUserArtificerMoney() == 1) {
//
//                    userMoneyArtificerService.updateMoney(1, orders.getUserId(), orders.getArtificerId(), userMoney.doubleValue());
//                } else {
                if(userMoney.compareTo(BigDecimal.ZERO) > 0) {
                    userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                }
//                }
                //查询用户当前余额
                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setBlFlag(1);
            }

            userMoneyDetails.setMoney(userMoney);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已原路退款！扣除订单：" + massageMoneyDeduction + "，车费：" + taxiMoneyDeduction);
            userMoneyDetails.setTitle("订单退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetails.setArtificerId(orders.getArtificerId());
            userMoneyDetails.setBlRole(1);
            userMoneyDetailsService.save(userMoneyDetails);

            BigDecimal sumMoney = rate.add(taxiMoneyDeduction);//总扣费
            if(sumMoney.compareTo(BigDecimal.ZERO) > 0){
                //按照比例 将扣除的钱进行分佣
                BigDecimal taxiMoney = taxiMoneyDeduction;
                Artificer artificer = artificerService.getById(orders.getArtificerId());
                BigDecimal artificerTaxiMoney = taxiMoneyDeduction;//扣车费
                BigDecimal pingTaxiMoney = BigDecimal.ZERO;
                BigDecimal artificerMoney = rate.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP); //技师获得扣款提成
                orders.setProjectBenefits(artificerMoney);
                BigDecimal pingMoney = massageMoneyDeduction.subtract(artificerMoney);//平台获得项目扣款

                String taxi = commonInfoService.findOne(394).getValue();
                if ("是".equals(taxi)) {
                    artificerTaxiMoney = taxiMoney.multiply(artificer.getRate());
                    artificerTaxiMoney = artificerTaxiMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                    pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney);
                }
                orders.setArtificerTaxiMoney(artificerTaxiMoney);
                orders.setPingTaxiMoney(pingTaxiMoney);

                UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
                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 = artificerMoney.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 = artificerMoney.multiply(oneUser.getUserRate());
                    oneUserMoney = oneUserMoney.setScale(0, BigDecimal.ROUND_HALF_UP);
                }
                orders.setOneUserMoney(oneUserMoney);
//                artificerMoney = artificerMoney.subtract(oneArtificerMoney);
                artificerMoney = artificerMoney.subtract(jjrMoney);
                artificerMoney = artificerMoney.subtract(shopMoney);
                artificerMoney = artificerMoney.subtract(oneUserMoney);

                artificerMoney = artificerMoney.add(artificerTaxiMoney);
                orders.setArtificerMoney(artificerMoney);
                orders.setSumArtificerMoney(artificerMoney);

                //平台扣款
                pingMoney = pingMoney.subtract(artificerMoney);
//                pingMoney = pingMoney.subtract(oneArtificerMoney);
                pingMoney = pingMoney.subtract(jjrMoney);
                pingMoney = pingMoney.subtract(shopMoney);
                pingMoney = pingMoney.subtract(oneUserMoney);
                pingMoney = pingMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                orders.setPingMoney(pingMoney);

                //分账
                userMoneyService.updateMoney(1, artificerUser.getUserId(), orders.getSumArtificerMoney().doubleValue());
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(artificerUser.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney1.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(orders.getSumArtificerMoney());
                userMoneyDetails.setUserId(artificerUser.getUserId());
                userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单取消！");
                if (orders.getShopUserId() != null) {
                    userMoneyDetails.setContent("用户取消订单，总扣除：" + sumMoney + "，平台扣除：" + orders.getPingMoney() +
                            "，商家扣除：" + orders.getShopMoney() + "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                            "，车费：" + orders.getTaxiMoney() + "，平台扣除车费：" + orders.getPingTaxiMoney() + "，到账车费：" + orders.getArtificerTaxiMoney() +
                            "，到账总金额：" + orders.getSumArtificerMoney());
                } else {
                    userMoneyDetails.setContent("用户取消订单，总扣除：" + sumMoney + "，平台扣除：" + orders.getPingMoney() +
                            "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                            "，车费：" + orders.getTaxiMoney() + "，平台扣除车费：" + orders.getPingTaxiMoney() + "，到账车费：" + orders.getArtificerTaxiMoney() +
                            "，到账总金额：" + orders.getSumArtificerMoney());
                }
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetails.setBlRole(2);
                userMoneyDetails.setBlFlag(1);
                userMoneyDetailsService.save(userMoneyDetails);

                if (oneUser != null && oneUser.getIsAgency() != null && oneUser.getIsAgency() == 1 && orders.getOneUserMoney().compareTo(BigDecimal.ZERO) !=0) {
                    if(orders.getOneUserMoney().compareTo(BigDecimal.ZERO)>0){
                        userMoneyService.updateMoney(1, oneUser.getUserId(), orders.getOneUserMoney().doubleValue());
                        userMoneyDetails = new UserMoneyDetails();
                        //查询用户当前余额
                        UserMoney userNowMoney3 = userMoneyService.selectUserMoneyByUserId(oneUser.getUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney3.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setMoney(orders.getOneUserMoney());
                        userMoneyDetails.setUserId(oneUser.getUserId());
                        userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单取消！");
                        userMoneyDetails.setContent("分销员收益："+orders.getOneUserMoney());
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setClassify(5);
                        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                        userMoneyDetails.setBlRole(1);
                        userMoneyDetails.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails);
                    }
                }

                if (jjrUser != null && orders.getJjrMoney().compareTo(BigDecimal.ZERO)!=0) {
                    if(orders.getJjrMoney().compareTo(BigDecimal.ZERO)>0) {
                        userMoneyService.updateMoney(1, jjrUser.getUserId(), orders.getJjrMoney().doubleValue());
                        userMoneyDetails = new UserMoneyDetails();
                        //查询用户当前余额
                        UserMoney userNowMoney4 = userMoneyService.selectUserMoneyByUserId(jjrUser.getUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney4.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setMoney(orders.getJjrMoney());
                        userMoneyDetails.setUserId(jjrUser.getUserId());
                        userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单取消！");
                        userMoneyDetails.setContent("经纪人收益："+orders.getJjrMoney());
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setClassify(6);
                        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                        userMoneyDetails.setBlRole(2);
                        userMoneyDetails.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails);
                    }
                }

                if (orders.getShopUserId() != null && orders.getShopMoney().compareTo(BigDecimal.ZERO)!=0) {
                    if(orders.getShopMoney().compareTo(BigDecimal.ZERO)>0) {
                        userMoneyService.updateMoney(1, orders.getShopUserId(), orders.getShopMoney().doubleValue());
                        userMoneyDetails = new UserMoneyDetails();
                        //查询用户当前余额
                        UserMoney userNowMoney5 = userMoneyService.selectUserMoneyByUserId(orders.getShopUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney5.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setMoney(orders.getShopMoney());
                        userMoneyDetails.setUserId(orders.getShopUserId());
                        userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单取消！");
                        userMoneyDetails.setContent("商家收益："+orders.getShopMoney());
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setState(2);
                        userMoneyDetails.setClassify(7);
                        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                        userMoneyDetails.setBlRole(3);
                        userMoneyDetails.setBlFlag(1);
                        userMoneyDetailsService.save(userMoneyDetails);
                    }
                }

                List<Orders> ordersList = baseMapper.selectList(new QueryWrapper<Orders>().isNotNull("pay_way").eq("parent_id", orders.getOrdersId()));
                //加钟退款全退
                for (Orders orders1 : ordersList) {
                    userMoneyDetails = new UserMoneyDetails();
                    if (orders1.getPayWay() == 1 || orders1.getPayWay() == 2 || orders1.getPayWay() == 3 || orders1.getPayWay() == 4) {
                        boolean refund = wxService.refund(orders1.getOrdersNo(), orders1.getPayMoney(), orders1.getPayMoney(), orders1.getPayWay());
                        if (!refund) {
                            return Result.error("退款失败，请联系客服！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else if (orders1.getPayWay() == 6) {
                        String data = aliPayController.alipayRefund(orders1.getOrdersNo(), orders1.getPayMoney());
                        if (StringUtils.isNotBlank(data)) {
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else {
    //                    if (orders1.getUserArtificerMoney() != null && orders1.getUserArtificerMoney() == 1) {
    //                        userMoneyArtificerService.updateMoney(1, orders1.getUserId(), orders1.getArtificerId(), orders1.getPayMoney().doubleValue());
    //                    } else {
                        userMoneyService.updateMoney(1, orders1.getUserId(), orders1.getPayMoney().doubleValue());
    //                    }
                        //查询用户当前余额
                        UserMoney userNowMoney6 = userMoneyService.selectUserMoneyByUserId(orders1.getUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney6.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setBlFlag(1);
                    }

                    userMoneyDetails.setMoney(orders1.getPayMoney());
                    userMoneyDetails.setUserId(orders1.getUserId());
                    userMoneyDetails.setContent("订单号：" + orders1.getOrdersNo() + ",已原路退款！");
                    userMoneyDetails.setTitle("订单退款");
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setCreateTime(time);
                    userMoneyDetails.setArtificerId(orders.getArtificerId());
                    userMoneyDetails.setBlRole(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                    orders1.setStatus(4);
                    baseMapper.updateById(orders1);
                }

                Artificer artificer2 = artificerService.getById(orders.getArtificerId());
                if (userId != null && artificer2.getUserId().equals(userId)) {
                    BigDecimal newCreditScore = BigDecimal.ZERO;
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setState("8");
                    messageInfo.setUserId(String.valueOf(artificer2.getUserId()));
                    messageInfo.setTitle("取消订单：" + orders.getOrdersNo());
                    String value1 = commonInfoService.findOne(384).getValue();
                    BigDecimal creditScore = new BigDecimal(value1);
                    newCreditScore = artificer2.getCreditScore().subtract(creditScore);
                    messageInfo.setContent("扣除信誉分：" + creditScore);
                    artificer2.setCreditScore(newCreditScore);
                    String value2 = commonInfoService.findOne(385).getValue();
                    BigDecimal minScore = new BigDecimal(value2);
                    if (artificer2.getCreditScore().doubleValue() < minScore.doubleValue()) {
                        artificer2.setStatus(2);
                    }
                    artificerService.updateById(artificer2);
                    messageService.saveBody(messageInfo);
                }
            }else{
                orders.setProjectBenefits(BigDecimal.ZERO);
                orders.setArtificerTaxiMoney(BigDecimal.ZERO);
                orders.setPingTaxiMoney(BigDecimal.ZERO);
                orders.setOneArtificerMoney(BigDecimal.ZERO);
                orders.setShopMoney(BigDecimal.ZERO);
                orders.setArtificerMoney(BigDecimal.ZERO);
                orders.setSumArtificerMoney(BigDecimal.ZERO);
                orders.setOneUserMoney(BigDecimal.ZERO);
                orders.setPingMoney(BigDecimal.ZERO);
                orders.setJjrMoney(BigDecimal.ZERO);
            }

            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());

                msgList.add(content);
                msgList.add("订单已取消，金额已原路退还！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，金额已原路退还！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }
            orders.setStatus(4);
        }
        baseMapper.updateById(orders);
        //删除技师占用时间表数据
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
        if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
            Orders ordersOld = new Orders();
            ordersOld.setOrdersId(orders.getOldOrdersId());
            if(orders.getIsSupplement() != null){
                if(orders.getIsSupplement() == 2){
                    ordersOld.setStatus(6);
                }else if(orders.getIsSupplement() == 3){
                    ordersOld.setStatus(2);
                }else{
                    ordersOld.setStatus(9);//用户已支付技师待接单
                }
            }else{
                ordersOld.setStatus(9);//用户已支付技师待接单
            }
            baseMapper.updateById(ordersOld);//原单暂变成挂单状态
        }
        return Result.success();
    }

    @Transactional
    public Result cancelPackageOrders(Long userId, Orders orders, BigDecimal trafficDeduction, BigDecimal trafficRate){
        //释放
        UserPackageDetail userPackageDetail = new UserPackageDetail();
        userPackageDetail.setId(orders.getUserPackageDetailId());
        userPackageDetail.setStatus(0);
        userPackageDetailService.updateById(userPackageDetail);

        if (orders.getStatus() == 1) {
            orders.setStatus(4);
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            //车费扣款
            BigDecimal taxiMoneyDeduction = BigDecimal.ZERO;
            if(trafficRate.compareTo(BigDecimal.ZERO) == 0){
                taxiMoneyDeduction = trafficDeduction;
            }else{
                taxiMoneyDeduction = orders.getTaxiMoney().multiply(trafficRate).setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            if(orders.getTaxiMoney().compareTo(taxiMoneyDeduction) < 0){
                taxiMoneyDeduction = orders.getTaxiMoney();
            }
            //退款金额
            BigDecimal userMoney = orders.getTaxiMoney().subtract(taxiMoneyDeduction);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                if(userMoney.compareTo(BigDecimal.ZERO) > 0) {
                    boolean refund = wxService.refund(orders.getOrdersNo(), orders.getTaxiMoney(), userMoney, orders.getPayWay());
                    if (!refund) {
                        return Result.error("退款失败，请联系客服！");
                    }
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else if (orders.getPayWay() == 6) {
                if(userMoney.compareTo(BigDecimal.ZERO) > 0) {
                    String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else {
                if(userMoney.compareTo(BigDecimal.ZERO) > 0) {
                    userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                }
                //查询用户当前余额
                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setBlFlag(1);
            }
//
            userMoneyDetails.setMoney(userMoney);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已原路退款！扣除订单：" + BigDecimal.ZERO + "，车费：" + taxiMoneyDeduction);
            userMoneyDetails.setTitle("订单退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetails.setArtificerId(orders.getArtificerId());
            userMoneyDetails.setBlRole(1);
            userMoneyDetailsService.save(userMoneyDetails);

            BigDecimal sumMoney = taxiMoneyDeduction;//总扣费
            if(sumMoney.compareTo(BigDecimal.ZERO)>0){
                orders.setProjectBenefits(BigDecimal.ZERO);
                orders.setOneArtificerMoney(BigDecimal.ZERO);
                orders.setShopMoney(BigDecimal.ZERO);
                orders.setArtificerMoney(BigDecimal.ZERO);
                orders.setSumArtificerMoney(BigDecimal.ZERO);
                orders.setOneUserMoney(BigDecimal.ZERO);
                orders.setPingMoney(BigDecimal.ZERO);
                orders.setJjrMoney(BigDecimal.ZERO);

                //按照比例 将扣除的钱进行分佣
                BigDecimal taxiMoney = taxiMoneyDeduction;
                Artificer artificer = artificerService.getById(orders.getArtificerId());
                BigDecimal artificerTaxiMoney = taxiMoneyDeduction;//扣车费
                BigDecimal pingTaxiMoney = BigDecimal.ZERO;

                String taxi = commonInfoService.findOne(394).getValue();
                if ("是".equals(taxi)) {
                    artificerTaxiMoney = taxiMoney.multiply(artificer.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney);
                }
                orders.setArtificerTaxiMoney(artificerTaxiMoney);
                orders.setPingTaxiMoney(pingTaxiMoney);

                UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
                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());
                        }
                    }
                }
                orders.setShopMoney(shopMoney);
                orders.setArtificerMoney(artificerTaxiMoney);
                orders.setSumArtificerMoney(artificerTaxiMoney);

                //平台扣款
//                BigDecimal pingMoney = orders.getPayMoney();
//                pingMoney = pingMoney.subtract(artificerTaxiMoney);
//                pingMoney = pingMoney.subtract(shopMoney);
//                pingMoney = pingMoney.subtract(oneArtificerMoney);

//                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());
//                }
//                orders.setOneUserMoney(oneUserMoney);
//                pingMoney = pingMoney.subtract(oneUserMoney);
//                orders.setPingMoney(pingMoney);

                userMoneyService.updateMoney(1, artificerUser.getUserId(), orders.getSumArtificerMoney().doubleValue());
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(artificerUser.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney1.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(orders.getSumArtificerMoney());
                userMoneyDetails.setUserId(artificerUser.getUserId());
                userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单取消！");
                if (orders.getShopUserId() != null) {
                    userMoneyDetails.setContent("用户取消订单，总扣除：" + sumMoney + "，平台扣除：" + orders.getPingMoney() +
                            "，商家扣除：" + orders.getShopMoney() + "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                            "，车费：" + orders.getTaxiMoney() + "，平台扣除车费：" + orders.getPingTaxiMoney() + "，到账车费：" + orders.getArtificerTaxiMoney() +
                            "，到账总金额：" + orders.getSumArtificerMoney());
                } else {
                    userMoneyDetails.setContent("用户取消订单，总扣除：" + sumMoney + "，平台扣除：" + orders.getPingMoney() +
                            "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                            "，车费：" + orders.getTaxiMoney() + "，平台扣除车费：" + orders.getPingTaxiMoney() + "，到账车费：" + orders.getArtificerTaxiMoney() +
                            "，到账总金额：" + orders.getSumArtificerMoney());
                }
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetails.setBlRole(2);
                userMoneyDetails.setBlFlag(1);
                userMoneyDetailsService.save(userMoneyDetails);

                List<Orders> ordersList = baseMapper.selectList(new QueryWrapper<Orders>().isNotNull("pay_way").eq("parent_id", orders.getOrdersId()));
                for (Orders orders1 : ordersList) {
                    userMoneyDetails = new UserMoneyDetails();
                    if (orders1.getPayWay() == 1 || orders1.getPayWay() == 2 || orders1.getPayWay() == 3 || orders1.getPayWay() == 4) {
                        boolean refund = wxService.refund(orders1.getOrdersNo(), orders1.getPayMoney(), orders1.getPayMoney(), orders1.getPayWay());
                        if (!refund) {
                            return Result.error("退款失败，请联系客服！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else if (orders1.getPayWay() == 6) {
                        String data = aliPayController.alipayRefund(orders1.getOrdersNo(), orders1.getPayMoney());
                        if (StringUtils.isNotBlank(data)) {
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else {
                        userMoneyService.updateMoney(1, orders1.getUserId(), orders1.getPayMoney().doubleValue());
                        //查询用户当前余额
                        UserMoney userNowMoney6 = userMoneyService.selectUserMoneyByUserId(orders1.getUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney6.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setBlFlag(1);
                    }

                    userMoneyDetails.setMoney(orders1.getPayMoney());
                    userMoneyDetails.setUserId(orders1.getUserId());
                    userMoneyDetails.setContent("订单号：" + orders1.getOrdersNo() + ",已原路退款！");
                    userMoneyDetails.setTitle("订单退款");
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setCreateTime(time);
                    userMoneyDetails.setArtificerId(orders.getArtificerId());
                    userMoneyDetails.setBlRole(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                    orders1.setStatus(4);
                    baseMapper.updateById(orders1);
                }

                Artificer artificer2 = artificerService.getById(orders.getArtificerId());
                if (userId != null && artificer2.getUserId().equals(userId)) {
                    BigDecimal newCreditScore = BigDecimal.ZERO;
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setState("8");
                    messageInfo.setUserId(String.valueOf(artificer2.getUserId()));
                    messageInfo.setTitle("取消订单：" + orders.getOrdersNo());
                    String value1 = commonInfoService.findOne(384).getValue();
                    BigDecimal creditScore = new BigDecimal(value1);
                    newCreditScore = artificer2.getCreditScore().subtract(creditScore);
                    messageInfo.setContent("扣除信誉分：" + creditScore);
                    artificer2.setCreditScore(newCreditScore);
                    String value2 = commonInfoService.findOne(385).getValue();
                    BigDecimal minScore = new BigDecimal(value2);
                    if (artificer2.getCreditScore().doubleValue() < minScore.doubleValue()) {
                        artificer2.setStatus(2);
                    }
                    artificerService.updateById(artificer2);
                    messageService.saveBody(messageInfo);
                }
            }else{
                orders.setProjectBenefits(BigDecimal.ZERO);
                orders.setArtificerTaxiMoney(BigDecimal.ZERO);
                orders.setPingTaxiMoney(BigDecimal.ZERO);
                orders.setOneArtificerMoney(BigDecimal.ZERO);
                orders.setShopMoney(BigDecimal.ZERO);
                orders.setArtificerMoney(BigDecimal.ZERO);
                orders.setSumArtificerMoney(BigDecimal.ZERO);
                orders.setOneUserMoney(BigDecimal.ZERO);
                orders.setPingMoney(BigDecimal.ZERO);
                orders.setJjrMoney(BigDecimal.ZERO);
            }

            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            UserPackageDetail userPackageDetail2 = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
            MassageType massageType = massageTypeService.getById(userPackageDetail2.getMassageTypeId());

            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());

                msgList.add(content);
                msgList.add("订单已取消，金额已原路退还！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，金额已原路退还！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }
            orders.setStatus(4);
        }
        baseMapper.updateById(orders);
        //删除技师占用时间表数据
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
        if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
            Orders ordersOld = new Orders();
            ordersOld.setOrdersId(orders.getOldOrdersId());
            if(orders.getIsSupplement() != null){
                if(orders.getIsSupplement() == 1){
                    orders.setStatus(10);
                }else if(orders.getIsSupplement() == 2){
                    orders.setStatus(6);
                }else if(orders.getIsSupplement() == 3){
                    orders.setStatus(2);
                }else{
                    orders.setStatus(9);//用户已支付技师待接单
                }
            }else{
                orders.setStatus(9);//用户已支付技师待接单
            }
            ordersOld.setStatus(11);
            baseMapper.updateById(ordersOld);//原单暂变成挂单状态
        }
        return Result.success();
    }

    /***
     * 待补单处理及待补单全单退款
     * @param userId
     * @param isAuto 是否自动退款 1是 技师操作变成待补单，0否 用户点击操作变成待补单
     * @param type 是否全额退款，1车费 2项目费 3全部
     * @return
     */
    @Override
    public Result cancelSupplementOrders(Long userId, Long ordersId, Integer isAuto, Integer type) {
        Orders orders = baseMapper.selectById(ordersId);
        //状态 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中  7技师出发 8技师到达 9用户已支付技师待接单 10待补单
        if(orders.getRefusalContent()!=null && !orders.getRefusalContent().equals("")){
        }else{
            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0 && type == 1){
                return Result.error("补差价的单据无法生成待补单！");
            }
        }
        if (orders.getStatus() == 8 || orders.getStatus() == 9 || orders.getStatus() == 10 || orders.getStatus() == 11) {
            if(orders.getUserPackageDetailId() !=null){
                return cancelSupplementPackageOrders(userId,orders,isAuto,type);
            }else{
                return cancelSupplementMassageOrders(userId,orders,isAuto,type);
            }
        }else{
            return Result.error("不满足待补单条件！");
        }
    }

    private Result cancelSupplementMassageOrders(Long userId, Orders orders, Integer isAuto, Integer type) {
        if(type == 1){
            if(orders.getTaxiMoney().compareTo(BigDecimal.ZERO) != 0){
                //退车费或扣车费，成为待补单
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(new Date());
                //退款金额
                BigDecimal userMoney = BigDecimal.ZERO;
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                if(isAuto == 0){
                    //退款车费
                    userMoney = orders.getTaxiMoney();
                    if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                        boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), userMoney, orders.getPayWay());
                        if (!refund) {
                            return Result.error("退款失败，请联系客服！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else if (orders.getPayWay() == 6) {
                        String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                        if (StringUtils.isNotBlank(data)) {
                            log.error(data);
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else {
                        userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                        //查询用户当前余额
                        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setBlFlag(1);
                    }
                    userMoneyDetails.setMoney(userMoney);
                    userMoneyDetails.setUserId(orders.getUserId());
                    userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",车费已原路退款！");
                    userMoneyDetails.setTitle("订单退款");
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setCreateTime(time);
                    userMoneyDetails.setArtificerId(orders.getArtificerId());
                    userMoneyDetails.setBlRole(1);
                    userMoneyDetailsService.save(userMoneyDetails);

                    Artificer artificer2 = artificerService.getById(orders.getArtificerId());
                    if (userId != null && artificer2.getUserId().equals(userId)) {
                        BigDecimal newCreditScore = BigDecimal.ZERO;
                        MessageInfo messageInfo = new MessageInfo();
                        messageInfo.setState("8");
                        messageInfo.setUserId(String.valueOf(artificer2.getUserId()));
                        messageInfo.setTitle("转待补单订单：" + orders.getOrdersNo());
                        String value1 = commonInfoService.findOne(384).getValue();
                        BigDecimal creditScore = new BigDecimal(value1);
                        newCreditScore = artificer2.getCreditScore().subtract(creditScore);
                        messageInfo.setContent("扣除信誉分：" + creditScore);
                        artificer2.setCreditScore(newCreditScore);
                        String value2 = commonInfoService.findOne(385).getValue();
                        BigDecimal minScore = new BigDecimal(value2);
                        if (artificer2.getCreditScore().doubleValue() < minScore.doubleValue()) {
                            artificer2.setStatus(2);
                        }
                        artificerService.updateById(artificer2);
                        messageService.saveBody(messageInfo);
                    }

                    UserEntity userEntity = userService.selectUserById(orders.getUserId());
                    //超过十个字 则截取
                    String content = "订单："+orders.getOrdersNo()+"，转为待补单";
                    //消息推送
                    if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                        CommonInfo one = commonInfoService.findOne(248);
                        List<String> msgList = new ArrayList<>();
                        msgList.add(orders.getOrdersNo());
                        msgList.add(content);
                        msgList.add("车费已原路退还！");
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
                    }

                    if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                        userService.pushToSingle("订单通知", "订单已转为，车费已原路退还！", userEntity.getClientid());
                    }

                    if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                        String apkey = commonInfoService.findOne(313).getValue();
                        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                        data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                        data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                        data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                        userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
                    }
                }
                if(isAuto == 1){
                    //扣车费
                    Integer minutes = Integer.valueOf(commonInfoService.findOne(452).getValue());
                    String serveTime = orders.getServeTime();
                    Date serveTimeDate = DateUtils.stringToDate(serveTime,"yyyy-MM-dd HH:mm");
                    serveTimeDate = DateUtils.addDateMinutes(serveTimeDate,minutes);
                    Date currentDate = new Date();
                    if(currentDate.getTime()>serveTimeDate.getTime()){
                    }else{
                        return Result.error("当前单据不满足待补单条件！");
                    }
                    //按照比例 将扣除的车费钱
                    BigDecimal taxiMoney = orders.getTaxiMoney();
                    BigDecimal sumMoney = orders.getTaxiMoney();//总扣费
                    Artificer artificer = artificerService.getById(orders.getArtificerId());
                    BigDecimal artificerTaxiMoney = orders.getTaxiMoney();//扣车费
                    BigDecimal pingTaxiMoney = BigDecimal.ZERO;

                    String taxi = commonInfoService.findOne(394).getValue();
                    if ("是".equals(taxi)) {
                        artificerTaxiMoney = taxiMoney.multiply(artificer.getRate());
                        artificerTaxiMoney = artificerTaxiMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                        pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney);
                    }
                    orders.setArtificerTaxiMoney(artificerTaxiMoney);
                    orders.setPingTaxiMoney(pingTaxiMoney);

                    UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
                    orders.setArtificerMoney(artificerTaxiMoney);
                    orders.setSumArtificerMoney(artificerTaxiMoney);

                    userMoneyService.updateMoney(1, artificerUser.getUserId(), orders.getSumArtificerMoney().doubleValue());
                    userMoneyDetails = new UserMoneyDetails();
                    //查询用户当前余额
                    UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(artificerUser.getUserId());
                    //插入余额
                    userMoneyDetails.setBalance(userNowMoney1.getMoney());
                    //插入操作类型为已操作用户余额
                    userMoneyDetails.setManipulateType(2);
                    userMoneyDetails.setMoney(orders.getSumArtificerMoney());
                    userMoneyDetails.setUserId(artificerUser.getUserId());
                    userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单超时转为待补单！");
                    userMoneyDetails.setContent("用户订单超时转为待补单，总扣除：" + sumMoney + "，到账总金额：" + orders.getSumArtificerMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetails.setBlRole(2);
                    userMoneyDetails.setBlFlag(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                }
                BigDecimal payMoney = orders.getPayMoney().subtract(orders.getTaxiMoney());
                orders.setPayMoney(payMoney);
            }
            //删除技师占用时间表数据
            artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
                //此笔单子退车费，并改为取消，再将原单改成待补单
                orders.setRefusalContent("");
                orders.setTaxiMoney(BigDecimal.ZERO);
                orders.setUsualTravelMoney(BigDecimal.ZERO);
                orders.setNightTravelMoney(BigDecimal.ZERO);
                orders.setStatus(4);
                baseMapper.updateById(orders);
                cancelSupplementOrders(userId, orders.getOldOrdersId(), isAuto, 1);//退原单，原单的车费已被退/扣，所以只退项目
            }else{
                BigDecimal taxiMoney = orders.getTaxiMoney();
                BigDecimal artificerMoney = orders.getArtificerMoney().subtract(taxiMoney);
                orders.setRefusalContent("");
                orders.setTaxiMoney(BigDecimal.ZERO);
                orders.setUsualTravelMoney(BigDecimal.ZERO);
                orders.setNightTravelMoney(BigDecimal.ZERO);
                orders.setStatus(10);
                orders.setArtificerMoney(artificerMoney);
                orders.setSumArtificerMoney(artificerMoney);
                baseMapper.updateById(orders);
            }
        }
        if(type == 2){
            //退项目费
            String couponIds = orders.getCouponId();
            if(orders.getCouponId() != null && couponIds.length()>0){
                String[] couponArr = couponIds.trim().split(",");
                for(int i=0;i<couponArr.length;i++){
                    if(couponArr[i]!=null && !couponArr[i].equals("")){
                        Long couponId = Long.valueOf(couponArr[i]);
                        CouponUser couponUser = couponUserService.getById(couponId);
                        couponUser.setStatus(0);
                        couponUserService.updateById(couponUser);
                    }
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            //项目扣款
            BigDecimal rate = BigDecimal.ZERO;
            //车费扣款
            BigDecimal taxiMoneyDeduction = orders.getTaxiMoney();
            //退款金额
            BigDecimal userMoney = orders.getPayMoney().subtract(rate).subtract(taxiMoneyDeduction);

            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();

            if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), userMoney, orders.getPayWay());
                if (!refund) {
                    return Result.error("退款失败，请联系客服！");
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else if (orders.getPayWay() == 6) {
                String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                if (StringUtils.isNotBlank(data)) {
                    log.error(data);
                    JSONObject jsonObject = JSON.parseObject(data);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else {
                userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                //查询用户当前余额
                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setBlFlag(1);
            }
            userMoneyDetails.setMoney(userMoney);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",订单已原路退款！");
            userMoneyDetails.setTitle("订单退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetails.setArtificerId(orders.getArtificerId());
            userMoneyDetails.setBlRole(1);
            userMoneyDetailsService.save(userMoneyDetails);
            orders.setStatus(4);
            baseMapper.updateById(orders);

            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());
                msgList.add(content);
                msgList.add("订单已取消，订单费已原路退还！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，订单费已原路退还！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }

        }
        if(type == 3){
            //全退
            String couponIds = orders.getCouponId();
            if(orders.getCouponId() != null && couponIds.length()>0){
                String[] couponArr = couponIds.trim().split(",");
                for(int i=0;i<couponArr.length;i++){
                    if(couponArr[i]!=null && !couponArr[i].equals("")){
                        Long couponId = Long.valueOf(couponArr[i]);
                        CouponUser couponUser = couponUserService.getById(couponId);
                        couponUser.setStatus(0);
                        couponUserService.updateById(couponUser);
                    }
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            //项目扣款
            BigDecimal rate = BigDecimal.ZERO;
            //车费扣款
            BigDecimal taxiMoneyDeduction = BigDecimal.ZERO;
            //退款金额
            BigDecimal userMoney = orders.getPayMoney().subtract(rate).subtract(taxiMoneyDeduction);

            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();

            if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), userMoney, orders.getPayWay());
                if (!refund) {
                    return Result.error("退款失败，请联系客服！");
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else if (orders.getPayWay() == 6) {
                String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                if (StringUtils.isNotBlank(data)) {
                    JSONObject jsonObject = JSON.parseObject(data);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else {
                userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                //查询用户当前余额
                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setBlFlag(1);
            }
            userMoneyDetails.setMoney(userMoney);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已原路退款！");
            userMoneyDetails.setTitle("订单退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetails.setArtificerId(orders.getArtificerId());
            userMoneyDetails.setBlRole(1);
            userMoneyDetailsService.save(userMoneyDetails);
            orders.setArtificerMoney(BigDecimal.ZERO);
            orders.setArtificerTaxiMoney(BigDecimal.ZERO);
            orders.setProjectBenefits(BigDecimal.ZERO);
            orders.setStatus(4);
            baseMapper.updateById(orders);
            //删除技师占用时间表数据
            artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
            Artificer artificer2 = artificerService.getById(orders.getArtificerId());
            if (userId != null && artificer2.getUserId().equals(userId)) {
                BigDecimal newCreditScore = BigDecimal.ZERO;
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setState("8");
                messageInfo.setUserId(String.valueOf(artificer2.getUserId()));
                messageInfo.setTitle("取消订单：" + orders.getOrdersNo());
                String value1 = commonInfoService.findOne(384).getValue();
                BigDecimal creditScore = new BigDecimal(value1);
                newCreditScore = artificer2.getCreditScore().subtract(creditScore);
                messageInfo.setContent("扣除信誉分：" + creditScore);
                artificer2.setCreditScore(newCreditScore);
                String value2 = commonInfoService.findOne(385).getValue();
                BigDecimal minScore = new BigDecimal(value2);
                if (artificer2.getCreditScore().doubleValue() < minScore.doubleValue()) {
                    artificer2.setStatus(2);
                }
                artificerService.updateById(artificer2);
                messageService.saveBody(messageInfo);
            }

            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());

                msgList.add(content);
                msgList.add("订单已取消，金额已原路退还！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，金额已原路退还！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }

            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
                cancelSupplementOrders(userId, orders.getOldOrdersId(), isAuto, 2);//退原单，原单的车费已被退/扣，所以只退项目
            }
        }
        return Result.success();
    }

    private Result cancelSupplementPackageOrders(Long userId, Orders orders, Integer isAuto, Integer type) {
        if(type == 1){
            if(orders.getTaxiMoney().compareTo(BigDecimal.ZERO) != 0) {
                //退车费或扣车费，成为待补单
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(new Date());
                //退款金额
                BigDecimal userMoney = BigDecimal.ZERO;
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                if (isAuto == 0) {
                    //退款车费
                    userMoney = orders.getTaxiMoney();
                    if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                        boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), userMoney, orders.getPayWay());
                        if (!refund) {
                            return Result.error("退款失败，请联系客服！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else if (orders.getPayWay() == 6) {
                        String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                        if (StringUtils.isNotBlank(data)) {
                            log.error(data);
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                        userMoneyDetails.setManipulateType(1);
                        userMoneyDetails.setBlFlag(2);
                    } else {
                        userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                        //查询用户当前余额
                        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                        //插入余额
                        userMoneyDetails.setBalance(userNowMoney.getMoney());
                        //插入操作类型为已操作用户余额
                        userMoneyDetails.setManipulateType(2);
                        userMoneyDetails.setBlFlag(1);
                    }
                    userMoneyDetails.setMoney(userMoney);
                    userMoneyDetails.setUserId(orders.getUserId());
                    userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",车费已原路退款！");
                    userMoneyDetails.setTitle("订单退款");
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setCreateTime(time);
                    userMoneyDetails.setArtificerId(orders.getArtificerId());
                    userMoneyDetails.setBlRole(1);
                    userMoneyDetailsService.save(userMoneyDetails);

                    Artificer artificer2 = artificerService.getById(orders.getArtificerId());
                    if (userId != null && artificer2.getUserId().equals(userId)) {
                        BigDecimal newCreditScore = BigDecimal.ZERO;
                        MessageInfo messageInfo = new MessageInfo();
                        messageInfo.setState("8");
                        messageInfo.setUserId(String.valueOf(artificer2.getUserId()));
                        messageInfo.setTitle("转待补单订单：" + orders.getOrdersNo());
                        String value1 = commonInfoService.findOne(384).getValue();
                        BigDecimal creditScore = new BigDecimal(value1);
                        newCreditScore = artificer2.getCreditScore().subtract(creditScore);
                        messageInfo.setContent("扣除信誉分：" + creditScore);
                        artificer2.setCreditScore(newCreditScore);
                        String value2 = commonInfoService.findOne(385).getValue();
                        BigDecimal minScore = new BigDecimal(value2);
                        if (artificer2.getCreditScore().doubleValue() < minScore.doubleValue()) {
                            artificer2.setStatus(2);
                        }
                        artificerService.updateById(artificer2);
                        messageService.saveBody(messageInfo);
                    }

                    UserEntity userEntity = userService.selectUserById(orders.getUserId());
                    //超过十个字 则截取
                    String content = "订单：" + orders.getOrdersNo() + "，转为待补单";
                    //消息推送
                    if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                        CommonInfo one = commonInfoService.findOne(248);
                        List<String> msgList = new ArrayList<>();
                        msgList.add(orders.getOrdersNo());
                        msgList.add(content);
                        msgList.add("车费已原路退还！");
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
                    }

                    if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                        userService.pushToSingle("订单通知", "订单已转为，车费已原路退还！", userEntity.getClientid());
                    }

                    if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                        String apkey = commonInfoService.findOne(313).getValue();
                        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                        data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                        data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                        data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                        userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
                    }
                }
                if (isAuto == 1) {
                    Integer minutes = Integer.valueOf(commonInfoService.findOne(452).getValue());
                    String serveTime = orders.getServeTime();
                    Date serveTimeDate = DateUtils.stringToDate(serveTime,"yyyy-MM-dd HH:mm");
                    serveTimeDate = DateUtils.addDateMinutes(serveTimeDate,minutes);
                    Date currentDate = new Date();
                    if(currentDate.getTime()>serveTimeDate.getTime()){
                    }else{
                        return Result.error("当前单据不满足待补单条件！");
                    }
                    //按照比例 将扣除的车费钱
                    BigDecimal taxiMoney = orders.getTaxiMoney();
                    BigDecimal sumMoney = orders.getTaxiMoney();//总扣费
                    Artificer artificer = artificerService.getById(orders.getArtificerId());
                    BigDecimal artificerTaxiMoney = orders.getTaxiMoney();//扣车费
                    BigDecimal pingTaxiMoney = BigDecimal.ZERO;

                    String taxi = commonInfoService.findOne(394).getValue();
                    if ("是".equals(taxi)) {
                        artificerTaxiMoney = taxiMoney.multiply(artificer.getRate());
                        artificerTaxiMoney = artificerTaxiMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                        pingTaxiMoney = taxiMoney.subtract(artificerTaxiMoney);
                    }
                    orders.setArtificerTaxiMoney(artificerTaxiMoney);
                    orders.setPingTaxiMoney(pingTaxiMoney);

                    UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
                    orders.setArtificerMoney(artificerTaxiMoney);
                    orders.setSumArtificerMoney(artificerTaxiMoney);

                    userMoneyService.updateMoney(1, artificerUser.getUserId(), orders.getSumArtificerMoney().doubleValue());
                    userMoneyDetails = new UserMoneyDetails();
                    //查询用户当前余额
                    UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(artificerUser.getUserId());
                    //插入余额
                    userMoneyDetails.setBalance(userNowMoney1.getMoney());
                    //插入操作类型为已操作用户余额
                    userMoneyDetails.setManipulateType(2);
                    userMoneyDetails.setMoney(orders.getSumArtificerMoney());
                    userMoneyDetails.setUserId(artificerUser.getUserId());
                    userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单超时转为待补单！");
                    userMoneyDetails.setContent("用户订单超时转为待补单，总扣除：" + sumMoney + "，到账总金额：" + orders.getSumArtificerMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetails.setBlRole(2);
                    userMoneyDetails.setBlFlag(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                }
                BigDecimal payMoney = orders.getPayMoney().subtract(orders.getTaxiMoney());
                orders.setPayMoney(payMoney);
            }
            //删除技师占用时间表数据
            artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
                //此笔单子退车费，并改为取消，再将原单改成待补单
                orders.setRefusalContent("");
                orders.setTaxiMoney(BigDecimal.ZERO);
                orders.setUsualTravelMoney(BigDecimal.ZERO);
                orders.setNightTravelMoney(BigDecimal.ZERO);
                orders.setStatus(4);
                baseMapper.updateById(orders);
                cancelSupplementOrders(userId, orders.getOldOrdersId(), isAuto, 1);//退原单，原单的车费已被退/扣，所以只退项目
            }else{
                BigDecimal taxiMoney = orders.getTaxiMoney();
                BigDecimal artificerMoney = orders.getArtificerMoney().subtract(taxiMoney);
                orders.setRefusalContent("");
                orders.setTaxiMoney(BigDecimal.ZERO);
                orders.setUsualTravelMoney(BigDecimal.ZERO);
                orders.setNightTravelMoney(BigDecimal.ZERO);
                orders.setStatus(10);
                orders.setArtificerMoney(artificerMoney);
                orders.setSumArtificerMoney(artificerMoney);
                baseMapper.updateById(orders);
            }
        }
        if(type == 2){
            //退项目费
            //释放
            UserPackageDetail userPackageDetail = new UserPackageDetail();
            userPackageDetail.setId(orders.getUserPackageDetailId());
            userPackageDetail.setStatus(0);
            userPackageDetailService.updateById(userPackageDetail);

            orders.setStatus(4);
            baseMapper.updateById(orders);

            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            UserPackageDetail userPackageDetail2 = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
            MassageType massageType = massageTypeService.getById(userPackageDetail2.getMassageTypeId());

            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());
                msgList.add(content);
                msgList.add("订单已取消，订单费已原路退还！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，订单费已原路退还！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }

        }else if(type == 3){
            //全退
            //释放
            UserPackageDetail userPackageDetail = new UserPackageDetail();
            userPackageDetail.setId(orders.getUserPackageDetailId());
            userPackageDetail.setStatus(0);
            userPackageDetailService.updateById(userPackageDetail);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            //退款金额
            BigDecimal userMoney = orders.getTaxiMoney();

            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();

            if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                boolean refund = wxService.refund(orders.getOrdersNo(), orders.getTaxiMoney(), userMoney, orders.getPayWay());
                if (!refund) {
                    return Result.error("退款失败，请联系客服！");
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else if (orders.getPayWay() == 6) {
                String data = aliPayController.alipayRefund(orders.getOrdersNo(), userMoney);
                if (StringUtils.isNotBlank(data)) {
                    log.error(data);
                    JSONObject jsonObject = JSON.parseObject(data);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
                userMoneyDetails.setManipulateType(1);
                userMoneyDetails.setBlFlag(2);
            } else {
                userMoneyService.updateMoney(1, orders.getUserId(), userMoney.doubleValue());
                //查询用户当前余额
                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setBlFlag(1);
            }
            userMoneyDetails.setMoney(userMoney);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已原路退款！");
            userMoneyDetails.setTitle("订单退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetails.setArtificerId(orders.getArtificerId());
            userMoneyDetails.setBlRole(1);
            userMoneyDetailsService.save(userMoneyDetails);
            orders.setStatus(4);
            baseMapper.updateById(orders);
            //删除技师占用时间表数据
            artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));

            Artificer artificer2 = artificerService.getById(orders.getArtificerId());
            if (userId != null && artificer2.getUserId().equals(userId)) {
                BigDecimal newCreditScore = BigDecimal.ZERO;
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setState("8");
                messageInfo.setUserId(String.valueOf(artificer2.getUserId()));
                messageInfo.setTitle("取消订单：" + orders.getOrdersNo());
                String value1 = commonInfoService.findOne(384).getValue();
                BigDecimal creditScore = new BigDecimal(value1);
                newCreditScore = artificer2.getCreditScore().subtract(creditScore);
                messageInfo.setContent("扣除信誉分：" + creditScore);
                artificer2.setCreditScore(newCreditScore);
                String value2 = commonInfoService.findOne(385).getValue();
                BigDecimal minScore = new BigDecimal(value2);
                if (artificer2.getCreditScore().doubleValue() < minScore.doubleValue()) {
                    artificer2.setStatus(2);
                }
                artificerService.updateById(artificer2);
                messageService.saveBody(messageInfo);
            }

            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            UserPackageDetail userPackageDetail2 = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
            MassageType massageType = massageTypeService.getById(userPackageDetail2.getMassageTypeId());

            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());

                msgList.add(content);
                msgList.add("订单已取消，金额已原路退还！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，金额已原路退还！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }

            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
                cancelSupplementOrders(userId, orders.getOldOrdersId(), 0, 2);//退原单，原单的车费已被退/扣，所以只退项目
            }
        }
        return Result.success();
    }

    @Override
    public Result refundOrdersMoney(Long ordersId, BigDecimal refundMoney) {
        Orders orders = baseMapper.selectById(ordersId);
        //状态 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中  7技师出发 8技师到达
        if (orders.getStatus() == 4) {
            return Result.error("订单已经取消了！");
        }
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", ordersId));

        if (orders.getCouponId() != null) {
            CouponUser couponUser = couponUserService.getById(orders.getCouponId());
            if (couponUser != null && couponUser.getStatus().equals(1)) {
                couponUser.setStatus(0);
                couponUserService.updateById(couponUser);
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        BigDecimal refundMoneys = BigDecimal.ZERO;
        if (orders.getSumMoney().doubleValue() < refundMoney.doubleValue()) {
            return Result.error("退款金额不能大于支付金额！");
        }
        //判断退款金额是否大于单笔支付的金额 如果大于 则代表 有加钟项目
        if (orders.getPayMoney().doubleValue() < refundMoney.doubleValue()) {
            refundMoney = orders.getPayMoney();
            refundMoneys = refundMoney.subtract(orders.getPayMoney());
        }


        if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
            boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), refundMoney, orders.getPayWay());
            if (!refund) {
                return Result.error("退款失败，请联系客服！");
            }
        } else if (orders.getPayWay() == 6) {
            String data = aliPayController.alipayRefund(orders.getOrdersNo(), refundMoney);
            if (StringUtils.isNotBlank(data)) {
                log.error(data);
                JSONObject jsonObject = JSON.parseObject(data);
                JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                String code1 = alipay_trade_refund_response.getString("code");
                if (!"10000".equals(code1)) {
                    return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                }
            } else {
                return Result.error("退款失败！");
            }
        } else {
            if (orders.getUserArtificerMoney() != null && orders.getUserArtificerMoney() == 1) {
                userMoneyArtificerService.updateMoney(1, orders.getUserId(), orders.getArtificerId(), refundMoney.doubleValue());
            } else {
                userMoneyService.updateMoney(1, orders.getUserId(), refundMoney.doubleValue());
            }
        }
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        //查询用户当前余额
        UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
        //插入余额
        userMoneyDetails.setBalance(userNowMoney1.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setMoney(refundMoney);
        userMoneyDetails.setUserId(orders.getUserId());
        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已原路退款！");
        userMoneyDetails.setTitle("订单退款");
        userMoneyDetails.setType(1);
        userMoneyDetails.setState(2);
        userMoneyDetails.setCreateTime(time);
        userMoneyDetails.setArtificerId(orders.getArtificerId());
        userMoneyDetailsService.save(userMoneyDetails);

        if (refundMoneys.doubleValue() > 0) {
            List<Orders> ordersList = baseMapper.selectList(new QueryWrapper<Orders>().isNotNull("pay_way").eq("parent_id", orders.getOrdersId()));
            for (Orders orders1 : ordersList) {
                BigDecimal refundMoney1 = BigDecimal.ZERO;
                if (orders1.getPayMoney().doubleValue() < refundMoneys.doubleValue()) {
                    refundMoneys = refundMoneys.subtract(orders1.getPayMoney());
                    refundMoney1 = orders1.getPayMoney();
                } else {
                    refundMoney1 = refundMoneys;
                    refundMoneys = BigDecimal.ZERO;
                }

                if (orders1.getPayWay() == 1 || orders1.getPayWay() == 2 || orders1.getPayWay() == 3 || orders1.getPayWay() == 4) {
                    boolean refund = wxService.refund(orders1.getOrdersNo(), orders1.getPayMoney(), refundMoney1, orders1.getPayWay());
                    if (!refund) {
                        return Result.error("退款失败，请联系客服！");
                    }
                } else if (orders1.getPayWay() == 6) {
                    String data = aliPayController.alipayRefund(orders1.getOrdersNo(), refundMoney1);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                } else {
                    if (orders1.getUserArtificerMoney() != null && orders1.getUserArtificerMoney() == 1) {
                        userMoneyArtificerService.updateMoney(1, orders1.getUserId(), orders1.getArtificerId(), refundMoney1.doubleValue());
                    } else {
                        userMoneyService.updateMoney(1, orders1.getUserId(), refundMoney1.doubleValue());
                    }
                }
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney8 = userMoneyService.selectUserMoneyByUserId(orders1.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney8.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(refundMoney1);
                userMoneyDetails.setUserId(orders1.getUserId());
                userMoneyDetails.setContent("订单号：" + orders1.getOrdersNo() + ",已原路退款！");
                userMoneyDetails.setTitle("订单退款");
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setCreateTime(time);
                userMoneyDetails.setArtificerId(orders.getArtificerId());

                userMoneyDetailsService.save(userMoneyDetails);
                orders1.setStatus(4);
                baseMapper.updateById(orders1);
                if (refundMoneys.doubleValue() <= 0) {
                    break;
                }
            }
        }

        orders.setShopMoney(BigDecimal.ZERO);
        orders.setArtificerMoney(BigDecimal.ZERO);
        orders.setSumArtificerMoney(BigDecimal.ZERO);
        orders.setOneUserMoney(BigDecimal.ZERO);
        orders.setOneArtificerMoney(BigDecimal.ZERO);
        orders.setPingMoney(BigDecimal.ZERO);
        orders.setArtificerTaxiMoney(BigDecimal.ZERO);
        orders.setPingTaxiMoney(BigDecimal.ZERO);
        orders.setJjrMoney(BigDecimal.ZERO);
        orders.setStatus(4);
        baseMapper.updateById(orders);
        //删除技师占用时间表数据
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));

        UserEntity userEntity = userService.selectUserById(orders.getUserId());
        List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
        MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
        //超过十个字 则截取
        String content = massageType.getTitle();
        if (content.length() >= 15) {
            content = content.substring(0, 15) + "...";
        }

        //消息推送
        if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
            CommonInfo one = commonInfoService.findOne(248);
            List<String> msgList = new ArrayList<>();
            msgList.add(orders.getOrdersNo());

            msgList.add(content);
            msgList.add("订单已取消，金额已原路退款！");
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
        }

        if (StringUtils.isNotEmpty(userEntity.getClientid())) {
            userService.pushToSingle("订单通知", "订单已取消，金额已原路退款！", userEntity.getClientid());
        }

        if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
            String apkey = commonInfoService.findOne(313).getValue();
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
            data.put("thing17", new TemplateMessageItem(content, "#d71345"));
            data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
            userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
        }

        return Result.success();
    }

    /**
     * 删除订单 - 无用
     * @param ordersId
     * @return
     */
    @Override
    public Result removeOrders(Long ordersId) {
        Orders orders = baseMapper.selectById(ordersId);
        if (orders.getStatus().equals(2)) {
            return Result.error("订单正在进行中！");
        }
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", ordersId));

        if (orders.getCouponId() != null) {
            CouponUser couponUser = couponUserService.getById(orders.getCouponId());
            if (couponUser != null && couponUser.getStatus().equals(1)) {
                couponUser.setStatus(0);
                couponUserService.updateById(couponUser);
            }
        }
        baseMapper.deleteById(ordersId);
        return Result.success();
    }


    @Override
    public Result selectOrdersDetails(Long ordersId) {
        Integer minutes = Integer.valueOf(commonInfoService.findOne(452).getValue());
        Orders orders = baseMapper.selectById(ordersId);
        String serveTime = orders.getServeTime();
        Date serveTimeDate = DateUtils.stringToDate(serveTime,"yyyy-MM-dd HH:mm");
        serveTimeDate = DateUtils.addDateMinutes(serveTimeDate,minutes);
        Date currentDate = new Date();
        if(currentDate.getTime()>serveTimeDate.getTime()){
            orders.setIsCanSupplement(1);
        }else{
            orders.setIsCanSupplement(0);
        }
        List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", ordersId));
        for (OrdersMassage ordersMassage : ordersMassageList) {
            if(orders.getUserPackageDetailId() !=null){
                UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                UserPackage userPackage = userPackageService.getById(userPackageDetail.getMainId());
                orders.setPackageType(userPackage.getType());
                userPackageDetail.setMainTitle(userPackage.getTitle());
                userPackageDetail.setMainPrice(userPackage.getPrice());
                ordersMassage.setUserPackageDetail(userPackageDetail);
            }else{
                ordersMassage.setMassageType(massageTypeService.getById(ordersMassage.getMassageId()));
            }
        }
        orders.setOrdersMassageList(ordersMassageList);

        if(orders.getOldOrdersId()!=null){
            Orders oldOrders = baseMapper.selectById(orders.getOldOrdersId());
            List<OrdersMassage> oldOrdersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOldOrdersId()));
            for (OrdersMassage ordersMassage : oldOrdersMassageList) {
                if(oldOrders.getUserPackageDetailId() !=null){
                    UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                    UserPackage userPackage = userPackageService.getById(userPackageDetail.getMainId());
                    orders.setPackageType(userPackage.getType());
                    userPackageDetail.setMainTitle(userPackage.getTitle());
                    userPackageDetail.setMainPrice(userPackage.getPrice());
                    ordersMassage.setUserPackageDetail(userPackageDetail);
                }else{
                    ordersMassage.setMassageType(massageTypeService.getById(ordersMassage.getMassageId()));
                }
            }
            orders.setOldOrdersMassageList(oldOrdersMassageList);
        }
        Artificer artificer = artificerService.getById(orders.getArtificerId());
        if (artificer != null) {
            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            if (userEntity != null) {
                artificer.setPhone(userEntity.getPhone());
            }
            orders.setArtificer(artificer);
        }

        BigDecimal payMoneyTotal = BigDecimal.ZERO;
        BigDecimal artificerMoneyTotal = BigDecimal.ZERO;
        if(orders.getPayMoney()!=null){
            payMoneyTotal = payMoneyTotal.add(orders.getPayMoney());
        }
        if(orders.getArtificerMoney()!=null){
            artificerMoneyTotal = artificerMoneyTotal.add(orders.getArtificerMoney());
        }

        //获取是否有加钟订单
        if(orders.getAddNum()!=null){
            if(orders.getAddMoney()!=null){
                payMoneyTotal = payMoneyTotal.add(orders.getAddMoney());
            }
            if(orders.getAddArtificerMoney()!=null){
                artificerMoneyTotal = artificerMoneyTotal.add(orders.getAddArtificerMoney());
            }
        }

        //获取是否有改价订单
        if(orders.getOldOrdersId()!=null){
//            QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<Orders>();
//            ordersQueryWrapper.eq("orders_id",orders.getOldOrdersId());
//            ordersQueryWrapper.ne("status",4);
//            List<Orders> list = baseMapper.selectList(ordersQueryWrapper);
//            if(list!=null && list.size()>0) {
//                for(Orders vo : list){
//                    BigDecimal payMoney = vo.getPayMoney();
//                    BigDecimal artificerMoney = vo.getArtificerMoney();
//                    orders.setPayMoneyTotal(orders.getPayMoneyTotal().add(payMoney));
//                    orders.setArtificerMoneyTotal(orders.getArtificerMoneyTotal().add(artificerMoney));
//                }
//            }
            Orders oldOrders = getTotalMoney(orders);
            if(oldOrders.getPayMoney()!=null){
                payMoneyTotal = payMoneyTotal.add(oldOrders.getPayMoney());
            }
            if(oldOrders.getArtificerMoney()!=null){
                artificerMoneyTotal = artificerMoneyTotal.add(oldOrders.getArtificerMoney());
            }
        }
        orders.setPayMoneyTotal(payMoneyTotal);
        orders.setArtificerMoneyTotal(artificerMoneyTotal);
        return Result.success().put("data", orders);
    }

    private Orders getTotalMoney(Orders orders){
        Orders orders1 = new Orders();
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<Orders>();
        ordersQueryWrapper.eq("orders_id",orders.getOldOrdersId());
        ordersQueryWrapper.ne("status",4);
        List<Orders> list = baseMapper.selectList(ordersQueryWrapper);
        BigDecimal payMoneyTotal = BigDecimal.ZERO;
        BigDecimal artificerMoneyTotal = BigDecimal.ZERO;
        if(list!=null && list.size()>0) {
            for(Orders vo : list){
                if(vo.getOldOrdersId()!=null){
                    Orders oldOrders = getTotalMoney(vo);
                    if(oldOrders.getPayMoney()!=null){
                        payMoneyTotal = payMoneyTotal.add(oldOrders.getPayMoney());
                    }
                    if(oldOrders.getArtificerMoney()!=null){
                        artificerMoneyTotal = artificerMoneyTotal.add(oldOrders.getArtificerMoney());
                    }
                }
                if(vo.getPayMoney()!=null){
                    payMoneyTotal = payMoneyTotal.add(vo.getPayMoney());
                }
                if(vo.getArtificerMoney()!=null){
                    artificerMoneyTotal = artificerMoneyTotal.add(vo.getArtificerMoney());
                }
            }
        }
        orders1.setPayMoney(payMoneyTotal);
        orders1.setArtificerMoney(artificerMoneyTotal);
        return orders1;
    }

    @Override
    public Result selectOrdersList(Long userId, Integer page, Integer limit, Integer status, String city,
                                   String name, String phone, Long artificerId, Long parentId, String startTime,
                                   String endTime, Integer isAdd, String ordersNo, String artificerName,
                                   String oneUserName, String oneArtificerUserName,
                                   String startServeTime, String endServeTime, Integer overTimeOrders,
                                   Long shopId, String shopName, Integer warning, String title, String classifyId, Long userPackageId) {
        Page<Orders> pages = new Page<>(page, limit);
        IPage<Orders> ordersIPage = baseMapper.selectOrdersList(pages, userId, status,
                city, name, phone, artificerId, parentId, startTime, endTime, isAdd, ordersNo,
                artificerName, oneUserName, oneArtificerUserName, startServeTime, endServeTime, overTimeOrders, shopId, shopName, warning, title, classifyId, userPackageId);
        List<Orders> records = ordersIPage.getRecords();
        for (Orders orders : records) {
            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            for (OrdersMassage ordersMassage : ordersMassageList) {
                MassageType massageType = massageTypeService.getById(ordersMassage.getMassageId());
                ordersMassage.setMassageType(massageType);
                if (massageType != null) {
                    SysDictEntity sysDictEntity = sysDictService.getById(massageType.getClassifyId());
                    if (sysDictEntity != null) {
                        massageType.setClassifyName(sysDictEntity.getValue());
                    }
                }
            }
            orders.setOrdersMassageList(ordersMassageList);
        }
        return Result.success().put("data", new PageUtils(ordersIPage));
    }

    @Override
    public Result selectAppOrdersList(Long userId, Integer page, Integer limit, Integer status, Long userPackageId) {
        Page<Orders> pages = new Page<>(page, limit);
        IPage<Orders> ordersIPage = baseMapper.selectAppOrdersList(pages, userId, status, userPackageId);
        List<Orders> records = ordersIPage.getRecords();
        for (Orders orders : records) {
            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            for (OrdersMassage ordersMassage : ordersMassageList) {
                if(orders.getUserPackageDetailId() !=null){
                    UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                    UserPackage userPackage = userPackageService.getById(userPackageDetail.getMainId());
                    orders.setPackageType(userPackage.getType());
                    userPackageDetail.setMainTitle(userPackage.getTitle());
                    userPackageDetail.setMainPrice(userPackage.getPrice());
                    ordersMassage.setUserPackageDetail(userPackageDetail);
                }else{
                    MassageType massageType = massageTypeService.getById(ordersMassage.getMassageId());
                    ordersMassage.setMassageType(massageType);
                    if (massageType != null) {
                        SysDictEntity sysDictEntity = sysDictService.getById(massageType.getClassifyId());
                        if (sysDictEntity != null) {
                            massageType.setClassifyName(sysDictEntity.getValue());
                        }
                    }
                }
            }
            orders.setOrdersMassageList(ordersMassageList);
        }
        return Result.success().put("data", new PageUtils(ordersIPage));
    }

    @Override
    public ExcelData excelOrdersList(Long userId, Integer status, String city,
                                     String name, String phone, Long artificerId, Long parentId, String startTime,
                                     String endTime, Integer isAdd, String ordersNo, String artificerName,
                                     String oneUserName, String oneArtificerUserName,
                                     String startServeTime, String endServeTime, Integer overTimeOrders, Long shopId,
                                     String shopName, Integer warning, String title, String classifyId) {
        List<Orders> ordersList = baseMapper.excelOrdersList(userId, status, city, name, phone, artificerId,
                parentId, startTime, endTime, isAdd, ordersNo, artificerName, oneUserName, oneArtificerUserName,
                startServeTime, endServeTime, overTimeOrders, shopId, shopName, warning, title, classifyId);
        ExcelData data = new ExcelData();
        data.setName("订单列表");
        List<String> titles = new ArrayList();
        titles.add("编号");
        titles.add("下单用户");
        titles.add("技师用户");
        titles.add("订单编号");
        titles.add("商家名称");
        titles.add("项目价格");
        titles.add("优惠券名称");
        titles.add("优惠券金额");
        titles.add("技师收益");
        titles.add("支付金额");
        titles.add("打车费");
        titles.add("推广用户名称");
        titles.add("推广用户佣金");
        titles.add("推广技师名称");
        titles.add("推广技师佣金");
        titles.add("商家收益");
        titles.add("平台收益");
        titles.add("加钟价格");
        titles.add("加钟时长");
        titles.add("加钟次数");
        titles.add("加钟师傅收益");
        titles.add("技师总收益");
        titles.add("订单总金额");
        titles.add("支付方式");
        titles.add("联系电话");
        titles.add("服务地址");
        titles.add("预约时间");
        titles.add("备注");
        titles.add("开始服务时间");
        titles.add("预估结束时间");
        titles.add("订单完成时间");
        titles.add("商家电话");
        titles.add("商家地址");
        titles.add("创建时间");
        titles.add("是否超时");
        titles.add("是否加钟");
        titles.add("订单状态");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (Orders order : ordersList) {
            List<Object> row = new ArrayList();
            row.add(order.getOrdersId());
            row.add(order.getUserName());
            row.add(order.getArtificerName());
            row.add(order.getOrdersNo());
            if (StringUtils.isNotBlank(order.getShopName())) {
                row.add(order.getShopName());
            } else {
                row.add("");
            }
            row.add(order.getPrice());
            row.add(order.getCouponName());
            row.add(order.getCouponMoney());
            row.add(order.getArtificerMoney());
            row.add(order.getPayMoney());
            row.add(order.getTaxiMoney());
            row.add(order.getOneUserName());
            row.add(order.getOneUserMoney());
            row.add(order.getOneArtificerUserName());
            row.add(order.getOneArtificerMoney());
            row.add(order.getShopMoney());
            row.add(order.getPingMoney());
            row.add(order.getAddMoney());
            row.add(order.getAddTime());
            row.add(order.getAddNum());
            row.add(order.getAddArtificerMoney());
            row.add(order.getSumArtificerMoney());
            row.add(order.getSumMoney());
            if (order.getPayWay() == null) {
                row.add("待支付");
            } else if (order.getPayWay() == 1) {
                row.add("app微信");
            } else if (order.getPayWay() == 2) {
                row.add("微信公众号");
            } else if (order.getPayWay() == 3) {
                row.add("微信小程序");
            } else if (order.getPayWay() == 4) {
                row.add("支付宝");
            } else {
                row.add("零钱");
            }
            row.add(order.getPhone());
            row.add(order.getAddress());
            row.add(order.getServeTime());
            row.add(order.getRemark());
            row.add(order.getStartTime());
            row.add(order.getEndTime());
            row.add(order.getEndTimes());
            row.add(order.getShopPhone());
            row.add(order.getShopAddress());
            row.add(order.getCreateTime());
            if (order.getOverTimeOrders() != null && order.getOverTimeOrders() == 1) {
                row.add("是");
            } else {
                row.add("否");
            }
            if (order.getAddNum() != null && order.getAddNum() > 0) {
                row.add("是");
            } else {
                row.add("否");
            }
            if (order.getStatus().equals(1)) {
                row.add("待支付");
            } else if (order.getStatus().equals(2)) {
                row.add("待服务");
            } else if (order.getStatus().equals(3)) {
                row.add("待评论");
            } else if (order.getStatus().equals(4)) {
                row.add("已取消");
            } else if (order.getStatus().equals(5)) {
                row.add("已完成");
            } else if (order.getStatus().equals(6)) {
                row.add("进行中");
            } else if (order.getStatus().equals(7)) {
                row.add("技师出发");
            } else if (order.getStatus().equals(8)) {
                row.add("技师到达");
            } else {
                row.add("未知");
            }
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }


    @Override
    public Orders selectOrdersByOrderNo(String ordersNo) {
        return baseMapper.selectOne(new QueryWrapper<Orders>().eq("orders_no", ordersNo));
    }

    @Override
    public Result payOrders(Long ordersId, Integer type) {
        String msg = "";
//        reentrantReadWriteLock.writeLock().lock();
        try {
            Orders orders = baseMapper.selectById(ordersId);
            if (orders == null) {
                return Result.error("订单生成失败，请重新下单！");
            } else if (orders.getStatus() != 1) {
                return Result.error("订单状态异常，请刷新页面后重试！");
            }
            if(orders.getUserPackageDetailId() !=null ){
                //套餐订单
                return payPackageOrders(orders,type);
            }else{
                //项目订单
                return payMassageOrders(orders,type);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("钱包支付订单异常：" + e.getMessage(), e);
            msg =  e.getMessage();
        } finally {
//            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error(msg);
//        return Result.error("系统繁忙，请稍后再试！");

    }

    private Result payMassageOrders(Orders orders, Integer type) throws Exception{
//        无用，暂系统不支持储蓄金
//        UserMoneyArtificer userMoneyArtificer = userMoneyArtificerService.getOne(new QueryWrapper<UserMoneyArtificer>().eq("user_id", orders.getUserId()).eq("artificer_id", orders.getArtificerId()));
//        if (userMoneyArtificer != null && userMoneyArtificer.getMoney().doubleValue() >= orders.getPayMoney().doubleValue()) {
//            type = 2;
//        } else {
//            type = 1;
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            if (userMoney.getMoney().doubleValue() < orders.getPayMoney().doubleValue()) {
                return Result.error("钱包余额不足，请充值！");
            }
//        }

        Integer duration = 0;
        if (orders.getParentId() != null && orders.getParentId() != 0) {
            Orders orders1 = baseMapper.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("当前项目已超过最大加钟次数！");
                }
            }
            duration = massageType.getDuration();
            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 = baseMapper.selectById(orders.getOrdersId());
                        int timeDifference = orders.getDuration()-oldOrders.getDuration();
                        if(timeDifference>0){
                            ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOldOrdersId()).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.getOldOrdersId()).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 artificerTime2 = new ArtificerTime();
                                    artificerTime2.setArtificerId(orders.getArtificerId());
                                    artificerTime2.setArtificerDate(artificerTime.getArtificerDate());
                                    artificerTime2.setArtificerTime(artificerTime.getArtificerTime());
                                    artificerTime2.setClassify(1);
                                    artificerTime2.setOrdersId(orders.getOrdersId());
                                    artificerTime2.setCreateTime(DateUtils.format(new Date()));
                                    artificerTimeService.save(artificerTime2);
                                }
                            }
                        }
                    }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());
                }
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        userMoneyService.updateMoney(2, orders.getUserId(), orders.getPayMoney().doubleValue());
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        //查询用户当前余额
        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
        //插入余额
        userMoneyDetails.setBalance(userNowMoney.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setMoney(orders.getPayMoney());
        userMoneyDetails.setUserId(orders.getUserId());
        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
        userMoneyDetails.setTitle("支付订单");
        userMoneyDetails.setType(2);
        userMoneyDetails.setState(2);
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetails.setBlRole(1);
        userMoneyDetails.setBlFlag(1);
        userMoneyDetailsService.save(userMoneyDetails);

        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(5);
        orders.setPayTime(simpleDateFormat.format(new Date()));

        Artificer artificer = artificerService.getById(orders.getArtificerId());

        BigDecimal rate = new BigDecimal(commonInfoService.findOne(449).getValue());
        orders.setWalletRate(rate);
        rate = rate.divide(new BigDecimal(100));

        //钱包支付技师提成
        BigDecimal 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);
            //赋值技师收益
//            artificerPrice = orders.getPayMoney().multiply(artificer.getRate()).multiply(rate);
        } else {
            //平台不扣费 出租车收益全由技师收取
            artificerTaxiPrice = taxiMoney;
            orders.setArtificerTaxiMoney(artificerTaxiPrice);
            //设置出租车扣款为0
            orders.setPingTaxiMoney(BigDecimal.ZERO);
        }

        BigDecimal subtract = BigDecimal.ZERO;
        //用户支付减去通行费用
        if(orders.getIsSupplement()!=null && orders.getIsSupplement().equals(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;

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

        valueStorageDeduction = valueStorageDeduction.subtract(artificerPrice);
        orders.setValueStorageDeduction(valueStorageDeduction);

        orders.setProjectBenefits(artificerPrice);

        UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
        UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
        BigDecimal jjrMoney = BigDecimal.ZERO;
        if (jjrUser != null) {
            orders.setJjrUserId(jjrUser.getUserId());
            orders.setJjrUserName(jjrUser.getUserName());
            jjrMoney = artificerPrice.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(oneArtificerMoney);
        pingMoney = pingMoney.subtract(jjrMoney);
        pingMoney = pingMoney.subtract(shopMoney);
        pingMoney = pingMoney.subtract(oneUserMoney);
        orders.setPingMoney(pingMoney);

        if(orders.getIsSupplement() != null){
            if(!orders.getIsSupplement().equals(2)){
                Orders oldOrders = baseMapper.selectById(orders.getOrdersId());
                BigDecimal projectBenefits = orders.getProjectBenefits();
                projectBenefits = projectBenefits.add(oldOrders.getProjectBenefits());
                orders.setProjectBenefits(projectBenefits);
            }
        }

        baseMapper.updateById(orders);
        if (orders.getParentId() != null && orders.getParentId() != 0) {
            Orders orders1 = baseMapper.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 flag = false;
            if (StringUtils.isNotBlank(orders1.getEndTime())) {
                Calendar calendar = Calendar.getInstance();
                Date date = DateUtils.stringToDate(orders1.getEndTime(), "yyyy-MM-dd HH:mm:ss");
                calendar.setTime(date);
                calendar.add(Calendar.MINUTE, orders.getAddTime());
                orders1.setEndTime(DateUtils.format(calendar.getTime()));
                flag = true;
            }
            if (orders1.getAddMoney() != null) {
                orders1.setAddMoney(orders1.getAddMoney().add(orders.getPayMoney()));
                orders1.setAddArtificerMoney(orders1.getAddArtificerMoney().add(orders.getArtificerMoney()));
                orders1.setAddProjectBenefits(orders1.getProjectBenefits().add(orders.getProjectBenefits()));
                orders1.setAddPriceMarkup(orders1.getAddPriceMarkup().add(orders.getPriceMarkup()));
                orders1.setAddTechnicianMoney(orders1.getAddTechnicianMoney().add(orders.getTechnicianMoney()));
                orders1.setAddVipReductionMoney(orders1.getAddVipReductionMoney().add(orders.getVipReductionMoney()));
            } else {
                orders1.setAddMoney(orders.getPayMoney());
                orders1.setAddArtificerMoney(orders.getArtificerMoney());
                orders1.setAddProjectBenefits(orders.getProjectBenefits());
                orders1.setAddPriceMarkup(orders.getPriceMarkup());
                orders1.setAddTechnicianMoney(orders.getTechnicianMoney());
                orders1.setAddVipReductionMoney(orders.getVipReductionMoney());
            }
            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)) {
                String endTime = orders1.getEndTime();
                Date date = DateUtils.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
                Calendar calendar = Calendar.getInstance();
                if (date.getTime() > System.currentTimeMillis()) {
                    calendar.setTime(date);
                }
                calendar.add(Calendar.MINUTE, duration);
                orders1.setEndTime(endTime);
            }
            orders1.setAddPrice(orders.getPrice());
            orders1.setAddMassageTypeId(orders.getMassageTypeId());
            orders1.setAddEntryName(orders.getEntryName());
            orders1.setVipRate(orders.getVipRate());
            baseMapper.updateById(orders1);
            if (flag) {
                baseMapper.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());
        }
//        sendMsg(orders);

        return Result.success();
    }

    private Result payPackageOrders(Orders orders, Integer type) throws Exception{
//        无用，暂系统不支持储蓄金
//        UserMoneyArtificer userMoneyArtificer = userMoneyArtificerService.getOne(new QueryWrapper<UserMoneyArtificer>().eq("user_id", orders.getUserId()).eq("artificer_id", orders.getArtificerId()));
//        if (userMoneyArtificer != null && userMoneyArtificer.getMoney().doubleValue() >= orders.getTaxiMoney().doubleValue()) {
//            type = 2;
//        } else {
//            type = 1;
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
        if (userMoney.getMoney().doubleValue() < orders.getTaxiMoney().doubleValue()) {
            return Result.error("钱包余额不足，请充值！");
        }
//        }

        Integer duration = 0;
        if (orders.getParentId() != null && orders.getParentId() != 0) {
            Orders orders1 = baseMapper.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("当前项目已超过最大加钟次数！");
                }
            }
            duration = massageType.getDuration();
            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"),orders1.getArtificerId(),orders1.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 = baseMapper.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());
                }
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        userMoneyService.updateMoney(2, orders.getUserId(), orders.getTaxiMoney().doubleValue());
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        //查询用户当前余额
        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
        //插入余额
        userMoneyDetails.setBalance(userNowMoney.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setMoney(orders.getTaxiMoney());
        userMoneyDetails.setUserId(orders.getUserId());
        userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已经下单成功！");
        userMoneyDetails.setTitle("支付订单");
        userMoneyDetails.setType(2);
        userMoneyDetails.setState(2);
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetails.setBlRole(1);
        userMoneyDetails.setBlFlag(1);
        userMoneyDetailsService.save(userMoneyDetails);

        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(5);
        orders.setPayTime(simpleDateFormat.format(new Date()));

        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();

        BigDecimal rate = new BigDecimal(100);
        if(packagePayWay.equals(5)){
            rate = new BigDecimal(commonInfoService.findOne(449).getValue());
        }
        orders.setWalletRate(rate);
        rate = rate.divide(new BigDecimal(100));

        Artificer artificer = artificerService.getById(orders.getArtificerId());
        //钱包支付技师提成
        BigDecimal 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);
            //赋值技师收益
//            artificerPrice = orders.getPayMoney().multiply(artificer.getRate()).multiply(rate);
        } else {
            //平台不扣费 出租车收益全由技师收取
            artificerTaxiPrice = taxiMoney;
            orders.setArtificerTaxiMoney(taxiMoney);
            //设置出租车扣款为0
            orders.setPingTaxiMoney(BigDecimal.ZERO);
        }

        BigDecimal subtract = BigDecimal.ZERO;
        //用户支付减去通行费用
        if(orders.getIsSupplement()!=null && orders.getIsSupplement().equals(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;

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

        valueStorageDeduction = valueStorageDeduction.subtract(artificerPrice);
        orders.setValueStorageDeduction(valueStorageDeduction);
        orders.setProjectBenefits(artificerPrice);

        UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
        UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
        BigDecimal jjrMoney = BigDecimal.ZERO;
        if (jjrUser != null) {
            orders.setJjrUserId(jjrUser.getUserId());
            orders.setJjrUserName(jjrUser.getUserName());
            jjrMoney = artificerPrice.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);

        if(orders.getIsSupplement() != null){
            if(!orders.getIsSupplement().equals(2)){
                Orders oldOrders = baseMapper.selectById(orders.getOrdersId());
                BigDecimal projectBenefits = orders.getProjectBenefits();
                projectBenefits = projectBenefits.add(oldOrders.getProjectBenefits());
                orders.setProjectBenefits(projectBenefits);
            }
        }

        baseMapper.updateById(orders);
        if (orders.getParentId() != null && orders.getParentId() != 0) {
            Orders orders1 = baseMapper.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 flag = false;
            if (StringUtils.isNotBlank(orders1.getEndTime())) {
                Calendar calendar = Calendar.getInstance();
                Date date = DateUtils.stringToDate(orders1.getEndTime(), "yyyy-MM-dd HH:mm:ss");
                calendar.setTime(date);
                calendar.add(Calendar.MINUTE, orders.getAddTime());
                orders1.setEndTime(DateUtils.format(calendar.getTime()));
                flag = true;
            }
            if (orders1.getAddMoney() != null) {
                orders1.setAddMoney(orders1.getAddMoney().add(orders.getPayMoney()));
                orders1.setAddArtificerMoney(orders1.getAddArtificerMoney().add(orders.getArtificerMoney()));
                orders1.setAddProjectBenefits(orders1.getProjectBenefits().add(orders.getProjectBenefits()));
            } else {
                orders1.setAddMoney(orders.getPayMoney());
                orders1.setAddArtificerMoney(orders.getArtificerMoney());
                orders1.setAddProjectBenefits(orders.getProjectBenefits());
            }
            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)) {
                String endTime = orders1.getEndTime();
                Date date = DateUtils.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
                Calendar calendar = Calendar.getInstance();
                if (date.getTime() > System.currentTimeMillis()) {
                    calendar.setTime(date);
                }
                calendar.add(Calendar.MINUTE, duration);
                orders1.setEndTime(endTime);
            }
            orders1.setAddPrice(orders.getPrice());
            orders1.setAddMassageTypeId(orders.getMassageTypeId());
            orders1.setAddEntryName(orders.getEntryName());
            baseMapper.updateById(orders1);
            if (flag) {
                baseMapper.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());
        }
//        sendMsg(orders);
        return Result.success();
    }

    @Override
    public void sendMsg(Orders orders) {
        try {
            String adminPhone = commonInfoService.findOne(393).getValue();
            if (StringUtils.isNotBlank(adminPhone)) {
                singleThreadPool.submit(new Runnable() {
                    @Override
                    public void run() {
                        userService.sendMsg(adminPhone, "send");
                    }
                });
            }
            Artificer artificer = artificerService.getById(orders.getArtificerId());
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("51");
            messageInfo.setUserId(String.valueOf(artificer.getUserId()));
            messageInfo.setIsSee("0");
            messageInfo.setTitle("新订单提醒");
            messageInfo.setCreateAt(DateUtils.format(new Date()));
            messageService.save(messageInfo);
            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            //消息推送
            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }
            if (userEntity != null) {
                if (StringUtils.isNotEmpty(userEntity.getArtificerOpenId())) {
                    CommonInfo one = commonInfoService.findOne(247);
                    List<String> msgList = new ArrayList<>();
                    msgList.add(orders.getOrdersNo());
                    msgList.add(content);
                    msgList.add(orders.getCreateTime());
                    msgList.add("用户已经下单，请尽快联系！");
                    SenInfoCheckUtil.sendMsg(userEntity.getArtificerOpenId(), one.getValue(), msgList, 1);
                }
                if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                    userService.pushToSingle("订单通知", "用户已经下单，请尽快联系！", userEntity.getClientid());
                }
                /*if(StringUtils.isNotBlank(userEntity.getWxOpenId())){
                    String apkey = commonInfoService.findOne(312).getValue();
                    LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                    data.put("thing1", new TemplateMessageItem(content, "#d71345"));
                    data.put("time4", new TemplateMessageItem(orders.getServeTime(), "#d71345"));
                    data.put("thing2", new TemplateMessageItem(orders.getUserName(), "#d71345"));
                    data.put("phone_number3", new TemplateMessageItem(orders.getPhone(), "#d71345"));
                    String address=orders.getAddress();
                    if(address.length()>15){
                        address=address.substring(0,15)+"...";
                    }
                    data.put("thing5", new TemplateMessageItem(address, "#d71345"));
                    userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
                }*/

                singleThreadPool.submit(new Runnable() {
                    @Override
                    public void run() {
//                        sendAliPhone(userEntity.getPhone(), 1);
                    }
                });
            }
            CommonInfo one = commonInfoService.findOne(251);
            if ("是".equals(one.getValue())) {
                if (userEntity != null && StringUtils.isNotEmpty(userEntity.getPhone())) {
                    userService.sendMsg(userEntity.getPhone(), "send");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }


    @Override
    public Result payUserVip(Long userId, Long vipDetailsId) {
        VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", vipDetailsId));
        BigDecimal money = vipDetails.getMoney();
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        if (userMoney.getMoney().doubleValue() < money.doubleValue()) {
            return Result.error("钱包余额不足，请充值！");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        UserEntity userEntity = userService.selectUserById(userId);
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        MessageInfo messageInfo = new MessageInfo();
        userMoneyDetails.setMoney(money);
        userMoneyDetails.setUserId(userId);

        //查看用户是否是会员
        UserVip userVip = userVipDao.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
        Calendar cal = Calendar.getInstance();
        if (userVip != null) {
            Date endDate = null;
            try {
                endDate = simpleDateFormat.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(simpleDateFormat.format(new Date()));
        }

        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(simpleDateFormat.format(cal.getTime()));
        if (userVip.getVipId() != null) {
            userVipDao.updateById(userVip);
        } else {
            userVipDao.insert(userVip);
        }

        //修改我的的余额
        userMoneyService.updateMoney(2, userId, money.doubleValue());

        //查询用户当前余额
        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userId);
        //插入余额
        userMoneyDetails.setBalance(userNowMoney.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setTitle("开通会员");
        userMoneyDetails.setType(2);
        userMoneyDetails.setState(2);
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetails.setBlRole(1);
        userMoneyDetails.setBlFlag(1);
        userMoneyDetailsService.save(userMoneyDetails);
        messageInfo.setTitle("开通会员");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
        messageInfo.setIsSee("0");
        messageService.saveBody(messageInfo);
        if (StringUtil.isNotBlank(userEntity.getClientid())) {
            userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
        }

        return Result.success();
    }

    /**
     * 完成订单
     * @param ordersId
     * @param type 1PC端 2移动端
     * @param jsFwcn 服务承诺
     * @param jsPjtag 顾客评价
     * @param jsTsbz 特殊情况备注
     * @param earlyFinishReason 提前完成原因
     * @return
     */
    @Transactional
    @Override
    public Result accomplishOrders(Long ordersId, Integer type, String accomplishLongitude, String accomplishLatitude,String jsFwcn,String  jsPjtag,String jsTsbz,String earlyFinishReason) {
        try {
            Orders orders = baseMapper.selectById(ordersId);
            if (StringUtil.isEmpty(accomplishLatitude)) {
                return Result.error("技师定位异常，请检查定位！");
            }
            if (type == 1) {
                if (orders.getStatus().equals(1)) {
                    return Result.error("订单未付款！");
                } else if (orders.getStatus().equals(3) || orders.getStatus().equals(5)) {
                    return Result.error("订单已经完成了！");
                } else if (orders.getStatus().equals(4)) {
                    return Result.error("订单已经取消！");
                }
            } else {
                if (!orders.getStatus().equals(6)) {
                    return Result.error("请刷新页面后重试！");
                }
                //客户端提前完成
                if(earlyFinishReason!=null && !earlyFinishReason.equals("")){
                    orders.setEarlyFinishReason(earlyFinishReason);
                    baseMapper.updateById(orders);
                    return Result.success("订单申请提前完成成功！");
                }
                //客户端提前完成后，技师点击完成，获取提前完成原因，如果有原因，直接取完成，如果没原因判断当前时间是否大于预计结束时间
                String reasonStr = orders.getEarlyFinishReason();
                if(reasonStr!=null && !reasonStr.equals("")) {
                }else{
                    String endTimeStr = orders.getEndTime();
                    Date endTime = DateUtils.stringToDate(endTimeStr,"yyyy-MM-dd HH:mm:ss");
                    Date currentTime = new Date();
                    if(currentTime.getTime()<endTime.getTime()){
                        return Result.error("未到完成时间，该订单无法完成！");
                    }
                }
                GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(orders.getLatitude()), Double.parseDouble(orders.getLongitude()));
                GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(accomplishLatitude), Double.parseDouble(accomplishLongitude));
                Integer distances = (int) LonLatUtil.getDistanceMeter(source, target, Ellipsoid.Sphere);
                String value = commonInfoService.findOne(373).getValue();
                if (distances < Integer.parseInt(value)) {
                    return Result.error("请离开当前位置" + value + "m后点击完成！");
                }
            }
            //修改技师销量
            String accomplishAddress = CommonMapUtils.getLocationToAddress(accomplishLongitude, accomplishLatitude);//按坐标获取地理位置
            orders.setAccomplishAddress(accomplishAddress);
            Artificer artificer = artificerService.getById(orders.getArtificerId());
            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            artificer.setArtificerSales(artificer.getArtificerSales() + ordersMassageList.size());
            artificerService.updateById(artificer);

            //修改项目销量
            for (OrdersMassage ordersMassage : ordersMassageList) {
                if(orders.getUserPackageDetailId() !=null){
                    UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                    MassageType massageType = massageTypeService.getById(userPackageDetail.getMassageTypeId());
                    int num = massageType.getSales() == null ? 0 : massageType.getSales();
                    massageType.setSales(num + ordersMassage.getNum());
                    massageTypeService.updateById(massageType);
                    UserPackageDetail userPackageDetailUsed = userPackageDetailService.findMassagePackageDetailsUsed(userPackageDetail.getMainId());
                    if(userPackageDetailUsed.getServiceCount().equals(userPackageDetailUsed.getUsedQuantity())){
                        UserPackage userPackage = new UserPackage();
                        userPackage.setStatus(9);
                        userPackage.setId(userPackageDetail.getMainId());
                        userPackageService.updateById(userPackage);
                    }
                }else{
                    MassageType massageType = massageTypeService.getById(ordersMassage.getMassageId());
                    int num = massageType.getSales() == null ? 0 : massageType.getSales();
                    massageType.setSales(num + ordersMassage.getNum());
                    massageTypeService.updateById(massageType);
                }
            }
            //修改技师钱包  1是加 2是减
            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            userMoneyService.updateMoney(1, userEntity.getUserId(), orders.getSumArtificerMoney().doubleValue());

            //--------添加钱包流水日志-------------
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            //查询用户当前余额
            UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(userEntity.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney1.getMoney());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setMoney(orders.getSumArtificerMoney());
            userMoneyDetails.setUserId(userEntity.getUserId());
            userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
            if (orders.getShopUserId() != null) {
                userMoneyDetails.setContent("支付金额：" + orders.getSumMoney() + "，平台扣除：" + orders.getPingMoney() +
                        "，商家扣除：" + orders.getShopMoney() + "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                        "，打车费：" + orders.getTaxiMoney() + "，平台扣除打车费：" + orders.getPingTaxiMoney() + "，到账打车费：" + orders.getArtificerTaxiMoney() +
                        "，到账总金额：" + orders.getSumArtificerMoney());
            } else {
                userMoneyDetails.setContent("支付金额：" + orders.getSumMoney() + "，平台扣除：" + orders.getPingMoney() +
                        "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                        "，打车费：" + orders.getTaxiMoney() + "，平台扣除打车费：" + orders.getPingTaxiMoney() + "，到账打车费：" + orders.getArtificerTaxiMoney() +
                        "，到账总金额：" + orders.getSumArtificerMoney());
            }
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetails.setBlRole(2);
            userMoneyDetails.setBlFlag(1);
            userMoneyDetailsService.save(userMoneyDetails);

            //--------添加钱包流水日志-------------

            orders.setStatus(3);
            orders.setAccomplishLatitude(accomplishLatitude);
            orders.setAccomplishLongitude(accomplishLongitude);
            UserEntity user = userService.selectUserById(orders.getUserId());
            UserEntity oneUser = userService.queryByInvitationCode(user.getInviterCode());
            if (oneUser != null && oneUser.getIsAgency() != null && oneUser.getIsAgency() == 1) {
                if(orders.getOneUserMoney().compareTo(BigDecimal.ZERO)>0) {
                    userMoneyService.updateMoney(1, oneUser.getUserId(), orders.getOneUserMoney().doubleValue());
                    userMoneyDetails = new UserMoneyDetails();
                    //查询用户当前余额
                    UserMoney userNowMoney11 = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                    //插入余额
                    userMoneyDetails.setBalance(userNowMoney11.getMoney());
                    //插入操作类型为已操作用户余额
                    userMoneyDetails.setManipulateType(2);
                    userMoneyDetails.setMoney(orders.getOneUserMoney());
                    userMoneyDetails.setUserId(oneUser.getUserId());
                    userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
                    userMoneyDetails.setContent("分销员收益：" + orders.getOneUserMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setClassify(5);
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetails.setBlRole(1);
                    userMoneyDetails.setBlFlag(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                }
            }
            UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
            UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
            if (jjrUser != null) {
                if(orders.getJjrMoney().compareTo(BigDecimal.ZERO)>0) {
                    userMoneyService.updateMoney(1, jjrUser.getUserId(), orders.getJjrMoney().doubleValue());
                    userMoneyDetails = new UserMoneyDetails();
                    //查询用户当前余额
                    UserMoney userNowMoney12 = userMoneyService.selectUserMoneyByUserId(jjrUser.getUserId());
                    //插入余额
                    userMoneyDetails.setBalance(userNowMoney12.getMoney());
                    //插入操作类型为已操作用户余额
                    userMoneyDetails.setManipulateType(2);
                    userMoneyDetails.setMoney(orders.getJjrMoney());
                    userMoneyDetails.setUserId(jjrUser.getUserId());
                    userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
                    userMoneyDetails.setContent("经纪人收益："+orders.getJjrMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setClassify(6);
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetails.setBlRole(2);
                    userMoneyDetails.setBlFlag(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                }
            }

            if (orders.getShopUserId() != null) {
                if(orders.getShopMoney().compareTo(BigDecimal.ZERO)>0) {
                    userMoneyService.updateMoney(1, orders.getShopUserId(), orders.getShopMoney().doubleValue());
                    userMoneyDetails = new UserMoneyDetails();
                    //查询用户当前余额
                    UserMoney userNowMoney9 = userMoneyService.selectUserMoneyByUserId(orders.getShopUserId());
                    //插入余额
                    userMoneyDetails.setBalance(userNowMoney9.getMoney());
                    //插入操作类型为已操作用户余额
                    userMoneyDetails.setManipulateType(2);
                    userMoneyDetails.setMoney(orders.getShopMoney());
                    userMoneyDetails.setUserId(orders.getShopUserId());
                    userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
                    userMoneyDetails.setContent("商家收益："+orders.getShopMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setClassify(7);
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetails.setBlRole(3);
                    userMoneyDetails.setBlFlag(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                }
            }

            orders.setEndTimes(DateUtils.format(new Date()));
            orders.setJsFwcn(jsFwcn);
            orders.setJsPjtag(jsPjtag);
            orders.setJsTsbz(jsTsbz);
            //修改订单表类型
            baseMapper.updateById(orders);

            //删除技师占用时间表完成时间后的数据
            String afterTime = commonInfoService.findOne(458).getValue();
            int afterTimeInt = Integer.parseInt(afterTime);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, afterTimeInt);
            String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
            String date1 = format.substring(0, 10);
            String time1 = format.substring(11, 16);
            QueryWrapper<ArtificerTime> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orders_id",orders.getOrdersId());
            queryWrapper.ge("artificer_date",date1);
            queryWrapper.gt("artificer_time",time1);
            artificerTimeService.remove(queryWrapper);

            //修改订单下所有加钟的状态为待评价
            UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("parent_id", orders.getOrdersId());
            updateWrapper.notIn("status", 1,4);
            Orders orders2 = new Orders();
            orders2.setStatus(3);
            baseMapper.update(orders2,updateWrapper);
            //修改加钟销量
            if(orders.getAddMassageTypeId() != null){
                MassageType addMassageType = massageTypeService.getById(orders.getAddMassageTypeId());
                Integer addSales  = addMassageType.getSales();
                if(addSales == null){
                    addSales = 0;
                }
                addSales = addSales + 1;
                addMassageType.setSales(addSales);
                massageTypeService.updateById(addMassageType);
            }
            //消息推送
            List<String> msgList = new ArrayList<>();
            msgList.add(orders.getOrdersNo());

            MassageType massageType = null;
            if(orders.getUserPackageDetailId() !=null){
                UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassageList.get(0).getMassageId());
                massageType = massageTypeService.getById(userPackageDetail.getMassageTypeId());
            }else{
                massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
            }

            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }
            msgList.add(content);
            msgList.add(userMoneyDetails.getCreateTime());
            if (StringUtils.isNotEmpty(userEntity.getArtificerOpenId())) {
                CommonInfo one = commonInfoService.findOne(249);
                SenInfoCheckUtil.sendMsg(userEntity.getArtificerOpenId(), one.getValue(), msgList, 4);
            }
            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单完成了，请点击查看详细信息！", userEntity.getClientid());
            }
            /*if(StringUtils.isNotBlank(userEntity.getWxOpenId())){
                String apkey = commonInfoService.findOne(314).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string1", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing3", new TemplateMessageItem(content, "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }*/
            if (StringUtils.isNotEmpty(user.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(250);
                SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 3);
            }

            if (StringUtils.isNotEmpty(user.getClientid())) {
                userService.pushToSingle("订单通知", "订单完成了，请点击查看详细信息！", user.getClientid());
            }

            if (StringUtils.isNotBlank(user.getWxOpenId())) {
                String apkey = commonInfoService.findOne(314).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string1", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing3", new TemplateMessageItem(content, "#d71345"));
                userService.sendWxMessage(apkey, data, user.getWxOpenId());
            }
            //执行对应项目减去技师物料包
            materialArtificerService.accomplishOrders(orders.getMassageTypeId(),orders.getArtificerId());

            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
                Orders oldOrders = baseMapper.selectById(orders.getOldOrdersId());
                oldOrders.setArtificerId(orders.getArtificerId());
                oldOrders.setUserId(orders.getUserId());
                oldOrders.setUserName(orders.getUserName());
                oldOrders.setPhone(orders.getPhone());
                oldOrders.setAddress(orders.getAddress());
                oldOrders.setRemark(orders.getRemark());
                oldOrders.setServeTime(orders.getServeTime());
                oldOrders.setArtificerStartTime(orders.getArtificerStartTime());
                oldOrders.setArtificerEndTime(orders.getArtificerEndTime());
                oldOrders.setStartLongitude(orders.getStartLongitude());
                oldOrders.setStartLatitude(orders.getStartLatitude());
//                oldOrders.setTripWay(orders.getTripWay());
//                oldOrders.setTaxiMoney(BigDecimal.ZERO);
//                oldOrders.setKm(orders.getKm());
                oldOrders.setStartTime(orders.getStartTime());
                oldOrders.setEndTime(orders.getEndTime());
                oldOrders.setStartImg(orders.getStartImg());
                oldOrders.setStartLongitude(orders.getStartLongitude());
                oldOrders.setStartLatitude(orders.getStartLatitude());
                oldOrders.setAccomplishLongitude(orders.getAccomplishLongitude());
                oldOrders.setAccomplishLatitude(orders.getAccomplishLongitude());
                oldOrders.setStartAddress(orders.getStartAddress());
                oldOrders.setAccomplishAddress(orders.getAccomplishAddress());
                oldOrders.setArtificerRate(orders.getArtificerRate());
                accomplishOldOrders(oldOrders,type,jsFwcn,jsPjtag,jsTsbz);
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("完成订单异常：" + e.getMessage(), e);
            return Result.error("系统错误，请联系管理员");
        }
    }

    private void accomplishOldOrders(Orders orders, Integer type, String jsFwcn,String  jsPjtag,String jsTsbz) throws Exception{
        List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
        //修改套餐状态
        for (OrdersMassage ordersMassage : ordersMassageList) {
            if(orders.getUserPackageDetailId() !=null){
                UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
                UserPackageDetail userPackageDetailUsed = userPackageDetailService.findMassagePackageDetailsUsed(userPackageDetail.getMainId());
                if(userPackageDetailUsed.getServiceCount().equals(userPackageDetailUsed.getUsedQuantity())){
                    UserPackage userPackage = new UserPackage();
                    userPackage.setStatus(9);
                    userPackage.setId(userPackageDetail.getMainId());
                    userPackageService.updateById(userPackage);
                }
            }
        }

        Artificer artificer = artificerService.getById(orders.getArtificerId());
        //修改技师钱包  1是加 2是减
        UserEntity userEntity = userService.selectUserById(artificer.getUserId());
        userMoneyService.updateMoney(1, userEntity.getUserId(), orders.getSumArtificerMoney().doubleValue());

        //--------添加钱包流水日志-------------
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        //查询用户当前余额
        UserMoney userNowMoney1 = userMoneyService.selectUserMoneyByUserId(userEntity.getUserId());
        //插入余额
        userMoneyDetails.setBalance(userNowMoney1.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setMoney(orders.getSumArtificerMoney());
        userMoneyDetails.setUserId(userEntity.getUserId());
        userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
        String value = commonInfoService.findOne(394).getValue();
        if (orders.getShopUserId() != null) {
            userMoneyDetails.setContent("支付金额：" + orders.getSumMoney() + "，平台扣除：" + orders.getPingMoney() +
                    "，商家扣除：" + orders.getShopMoney() + "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                    "，打车费：" + orders.getTaxiMoney() + "，平台扣除打车费：" + orders.getPingTaxiMoney() + "，到账打车费：" + orders.getArtificerTaxiMoney() +
                    "，到账总金额：" + orders.getSumArtificerMoney());
        } else {
            userMoneyDetails.setContent("支付金额：" + orders.getSumMoney() + "，平台扣除：" + orders.getPingMoney() +
                    "，分销员扣除：" + orders.getOneUserMoney() + "，经纪人扣除：" + orders.getJjrMoney() +
                    "，打车费：" + orders.getTaxiMoney() + "，平台扣除打车费：" + orders.getPingTaxiMoney() + "，到账打车费：" + orders.getArtificerTaxiMoney() +
                    "，到账总金额：" + orders.getSumArtificerMoney());
        }
        userMoneyDetails.setType(1);
        userMoneyDetails.setState(2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetails.setBlRole(2);
        userMoneyDetails.setBlFlag(1);
        userMoneyDetailsService.save(userMoneyDetails);

        //--------添加钱包流水日志-------------
        UserEntity user = userService.selectUserById(orders.getUserId());
        UserEntity oneUser = userService.queryByInvitationCode(user.getInviterCode());
        if (oneUser != null && oneUser.getIsAgency() != null && oneUser.getIsAgency() == 1) {
            if(orders.getOneUserMoney().compareTo(BigDecimal.ZERO)>0) {
                userMoneyService.updateMoney(1, oneUser.getUserId(), orders.getOneUserMoney().doubleValue());
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney11 = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney11.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(orders.getOneUserMoney());
                userMoneyDetails.setUserId(oneUser.getUserId());
                userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
                userMoneyDetails.setContent("分销员收益："+orders.getOneUserMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setClassify(5);
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetails.setBlRole(1);
                userMoneyDetails.setBlFlag(1);
                userMoneyDetailsService.save(userMoneyDetails);
            }
        }
        UserEntity artificerUser = userService.selectUserById(artificer.getUserId());
        UserEntity jjrUser = userService.queryByInvitationCode(artificerUser.getBlJjrCode());
        if (jjrUser != null) {
            if(orders.getJjrMoney().compareTo(BigDecimal.ZERO)>0) {
                userMoneyService.updateMoney(1, jjrUser.getUserId(), orders.getJjrMoney().doubleValue());
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney12 = userMoneyService.selectUserMoneyByUserId(jjrUser.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney12.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(orders.getJjrMoney());
                userMoneyDetails.setUserId(jjrUser.getUserId());
                userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
                userMoneyDetails.setContent("经纪人收益："+orders.getJjrMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setClassify(6);
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetails.setBlRole(2);
                userMoneyDetails.setBlFlag(1);
                userMoneyDetailsService.save(userMoneyDetails);
            }
        }
        if (orders.getShopUserId() != null) {
            if(orders.getShopMoney().compareTo(BigDecimal.ZERO)>0) {
                userMoneyService.updateMoney(1, orders.getShopUserId(), orders.getShopMoney().doubleValue());
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney9 = userMoneyService.selectUserMoneyByUserId(orders.getShopUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney9.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(orders.getShopMoney());
                userMoneyDetails.setUserId(orders.getShopUserId());
                userMoneyDetails.setTitle("订单号：" + orders.getOrdersNo() + ",订单完成！");
                userMoneyDetails.setContent("商家收益："+orders.getShopMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setClassify(7);
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetails.setBlRole(3);
                userMoneyDetails.setBlFlag(1);
                userMoneyDetailsService.save(userMoneyDetails);
            }
        }
        orders.setEndTimes(DateUtils.format(new Date()));
        orders.setJsFwcn(jsFwcn);
        orders.setJsPjtag(jsPjtag);
        orders.setJsTsbz(jsTsbz);
        orders.setStatus(15);
        //修改订单表类型
        baseMapper.updateById(orders);

        //删除技师占用时间表完成时间后的数据
        String afterTime = commonInfoService.findOne(458).getValue();
        int afterTimeInt = Integer.parseInt(afterTime);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, afterTimeInt);
        String format = DateUtils.format(calendar.getTime(),"yyyy-MM-dd HH:mm");
        String date1 = format.substring(0, 10);
        String time1 = format.substring(11, 16);
        QueryWrapper<ArtificerTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orders_id",orders.getOrdersId());
        queryWrapper.ge("artificer_date",date1);
        queryWrapper.gt("artificer_time",time1);
        artificerTimeService.remove(queryWrapper);

        //修改订单下所有加钟的状态为待评价
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("parent_id", orders.getOrdersId());
        updateWrapper.notIn("status", "1,4");
        Orders orders2 = new Orders();
        orders2.setStatus(3);
        baseMapper.update(orders2,updateWrapper);
        //修改加钟销量
        if(orders.getAddMassageTypeId() != null){
            MassageType addMassageType = massageTypeService.getById(orders.getAddMassageTypeId());
            Integer addSales  = addMassageType.getSales();
            if(addSales == null){
                addSales = 0;
            }
            addSales = addSales + 1;
            addMassageType.setSales(addSales);
            massageTypeService.updateById(addMassageType);
        }
        //消息推送
        List<String> msgList = new ArrayList<>();
        msgList.add(orders.getOrdersNo());
        //超过十个字 则截取
        String content = orders.getEntryName();
        if (content.length() >= 15) {
            content = content.substring(0, 15) + "...";
        }
        msgList.add(content);
        msgList.add(userMoneyDetails.getCreateTime());
        if (StringUtils.isNotEmpty(userEntity.getArtificerOpenId())) {
            CommonInfo one = commonInfoService.findOne(249);
            SenInfoCheckUtil.sendMsg(userEntity.getArtificerOpenId(), one.getValue(), msgList, 4);
        }
        if (StringUtils.isNotEmpty(userEntity.getClientid())) {
            userService.pushToSingle("订单通知", "订单完成了，请点击查看详细信息！", userEntity.getClientid());
        }
        /*if(StringUtils.isNotBlank(userEntity.getWxOpenId())){
            String apkey = commonInfoService.findOne(314).getValue();
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string1", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
            data.put("thing3", new TemplateMessageItem(content, "#d71345"));
            userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
        }*/
        if (StringUtils.isNotEmpty(user.getOpenId())) {
            CommonInfo one = commonInfoService.findOne(250);
            SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 3);
        }

        if (StringUtils.isNotEmpty(user.getClientid())) {
            userService.pushToSingle("订单通知", "订单完成了，请点击查看详细信息！", user.getClientid());
        }

        if (StringUtils.isNotBlank(user.getWxOpenId())) {
            String apkey = commonInfoService.findOne(314).getValue();
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("character_string1", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
            data.put("thing3", new TemplateMessageItem(content, "#d71345"));
            userService.sendWxMessage(apkey, data, user.getWxOpenId());
        }

        if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0) {
            Orders oldOrders = baseMapper.selectById(orders.getOldOrdersId());
            oldOrders.setArtificerId(orders.getArtificerId());
            oldOrders.setUserId(orders.getUserId());
            oldOrders.setUserName(orders.getUserName());
            oldOrders.setPhone(orders.getPhone());
            oldOrders.setAddress(orders.getAddress());
            oldOrders.setRemark(orders.getRemark());
            oldOrders.setServeTime(orders.getServeTime());
            oldOrders.setArtificerStartTime(orders.getArtificerStartTime());
            oldOrders.setArtificerEndTime(orders.getArtificerEndTime());
            oldOrders.setStartLongitude(orders.getStartLongitude());
            oldOrders.setStartLatitude(orders.getStartLatitude());
//                oldOrders.setTripWay(orders.getTripWay());
//                oldOrders.setTaxiMoney(BigDecimal.ZERO);
//                oldOrders.setKm(orders.getKm());
            oldOrders.setStartTime(orders.getStartTime());
            oldOrders.setEndTime(orders.getEndTime());
            oldOrders.setStartImg(orders.getStartImg());
            oldOrders.setStartLongitude(orders.getStartLongitude());
            oldOrders.setStartLatitude(orders.getStartLatitude());
            oldOrders.setAccomplishLongitude(orders.getAccomplishLongitude());
            oldOrders.setAccomplishLatitude(orders.getAccomplishLongitude());
            oldOrders.setStartAddress(orders.getStartAddress());
            oldOrders.setAccomplishAddress(orders.getAccomplishAddress());
            oldOrders.setArtificerRate(orders.getArtificerRate());
            accomplishOldOrders(oldOrders, type, jsFwcn, jsPjtag, jsTsbz);
        }
    }

    @Override
    public Result startOrders(Long ordersId, String startLongitude, String startLatitude, String startImg,String startRemark) {
        Calendar calendar = Calendar.getInstance();
        Orders orders = baseMapper.selectById(ordersId);
        //判断开始服务时间 是否超过预定时间
        if (StringUtils.isNotBlank(orders.getServeTime())) {
            String value = commonInfoService.findOne(325).getValue();
            Calendar calendar1 = Calendar.getInstance();
            Date serveTime = DateUtils.stringToDate(orders.getServeTime(), "yyyy-MM-dd HH:mm");
            if (serveTime != null) {
                calendar1.setTime(serveTime);
                calendar1.add(Calendar.MINUTE, Integer.parseInt(value));
                if (System.currentTimeMillis() > calendar1.getTime().getTime()) {
                    //当前时间超过预定时间 判定为超时订单
                    orders.setOverTimeOrders(1);
                }
            }
        }

        if (orders.getOverTimeOrders() == null) {
            orders.setOverTimeOrders(2);
        }
        orders.setStartImg(startImg);
        orders.setStartRemark(startRemark);
        orders.setStartLatitude(startLatitude);
        orders.setStartLongitude(startLongitude);

        String startAddress = CommonMapUtils.getLocationToAddress(startLongitude, startLatitude);//按坐标获取地理位置

        orders.setStartAddress(startAddress);
        orders.setStartTime(DateUtils.format(calendar.getTime()));
        orders.setStatus(6);
        //开始服务 同时计算结束时间
        OrdersMassage ordersMassage = ordersMassageService.getOne(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
//        MassageType massageType = massageTypeService.getById(ordersMassage.getMassageId());
        MassageType massageType = null;
        if(orders.getUserPackageDetailId() !=null){
            UserPackageDetail userPackageDetail = userPackageDetailService.getById(ordersMassage.getMassageId());
            massageType = massageTypeService.getById(userPackageDetail.getMassageTypeId());
        }else{
            massageType = massageTypeService.getById(ordersMassage.getMassageId());
        }
        int duration = massageType.getDuration();
        if (orders.getAddTime() != null) {
            duration = duration * ordersMassage.getNum() + orders.getAddTime();
        }else{
            duration = duration * ordersMassage.getNum();
        }
        calendar.add(Calendar.MINUTE, duration);
        orders.setEndTime(DateUtils.format(calendar.getTime()));
        baseMapper.updateById(orders);
        return Result.success();
    }

    @Override
    public Result artificerStartOrEndTime(Long ordersId) {
        Orders orders = baseMapper.selectById(ordersId);
        if (orders.getStatus().equals(2)) {
            orders.setStatus(7);
            orders.setArtificerStartTime(DateUtils.format(new Date()));
        } else if (orders.getStatus().equals(7)) {
            orders.setStatus(8);
            orders.setArtificerEndTime(DateUtils.format(new Date()));
        } else {
            return Result.error("系统繁忙，请刷新后重试！");
        }
        baseMapper.updateById(orders);
        return Result.success();
    }

    /**
     * 技师数据统计
     * @param artificerId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Result selectArtificerIndex(Long artificerId, String startTime, String endTime) {
        Artificer artificer = artificerService.getById(artificerId);
        Map<String, Object> result = new HashMap<String, Object>();
        //总收益
        BigDecimal sumMoney = userMoneyDetailsService.selectArtificerMoney(artificer.getUserId(), startTime, endTime);
        //总销量 有关这个技师的订单销售数量的累计
        int countOrderNum = ordersDao.selectCountOrderNum(artificerId, startTime, endTime);
        //评价分数
        Double countTakingByUserId = orderTakingCommentDao.selectCountTakingByUserId(artificerId, startTime, endTime);
        //订单收入
        BigDecimal orderMoney = ordersDao.selectSumOrdersMoney(artificerId, startTime, endTime);
        //总订单数
        String countOrderStr = ordersDao.selectOrdersArtificerIntegral(artificerId, endTime, startTime );
        Integer countOrder = Integer.valueOf(countOrderStr);
        //退款金额
//        BigDecimal sumRefund = userMoneyDetailsService.selectSumRefund(artificer.getUserId(), startTime, endTime);
        BigDecimal sumRefund = ordersDao.selectSumRefund(artificerId, startTime, endTime);

        //访客人数
        int countByUserId = collectArtificerService.selectCountByUserId(artificerId, startTime, endTime);
        //待服务
        int countOrderIng = ordersDao.selectCountOrder(artificerId, 2, startTime, endTime);
        //待评价
        int countOrderAppraise = ordersDao.selectCountOrder(artificerId, 3, startTime, endTime);
        //已取消
        int countOrderCancel = ordersDao.selectCountOrder(artificerId, 4, startTime, endTime);
        //已完成
        int countOrderEnd = ordersDao.selectCountOrder(artificerId, 5, startTime, endTime);
        //状态 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中  7技师出发 8技师到达 9用户已支付技师待接单 10待补单 11原单挂单
        int countOrderJin = ordersDao.selectCountOrder(artificerId, 6, startTime, endTime);

        //客户评价总数
        Integer scoreCount = orderTakingCommentDao.selectCommentCount(artificerId, null, startTime, endTime);
        //好评数量  分数为4分5分
        Integer goodsScoreCount = orderTakingCommentDao.selectCommentCount(artificerId, 1, startTime, endTime);
        //差评数  分数为1，2，3分
        Integer loseScoreCount = orderTakingCommentDao.selectCommentCount(artificerId, 2, startTime, endTime);
        BigDecimal goodsRate = BigDecimal.ZERO;
        BigDecimal loseRate = BigDecimal.ZERO;
        //计算评价比例
        if (scoreCount != 0) {
            if (goodsScoreCount != null) {
                goodsRate = BigDecimal.valueOf(goodsScoreCount).divide(BigDecimal.valueOf(scoreCount), 2, BigDecimal.ROUND_HALF_UP);
            }
            if (loseScoreCount != null) {
                loseRate = BigDecimal.valueOf(loseScoreCount).divide(BigDecimal.valueOf(scoreCount), 2, BigDecimal.ROUND_HALF_UP);
            }
        }
        BigDecimal succeedRate = BigDecimal.ZERO;
        if (countOrderEnd != 0 && countOrder != 0) {
            succeedRate = BigDecimal.valueOf(countOrderEnd + countOrderAppraise).divide(new BigDecimal(countOrder), 2, BigDecimal.ROUND_HALF_UP);
        }

        result.put("sumMoney", sumMoney);
        result.put("countOrderNum", countOrderNum);
        result.put("countTakingByUserId", BigDecimal.valueOf(countTakingByUserId).setScale(2, BigDecimal.ROUND_HALF_UP));
        result.put("orderMoney", orderMoney);
        result.put("countOrder", countOrder);
        result.put("sumRefund", sumRefund);
        result.put("countByUserId", countByUserId);
        result.put("countOrderIng", countOrderIng);
        result.put("countOrderAppraise", countOrderAppraise);
        result.put("countOrderCancel", countOrderCancel);
        result.put("countOrderEnd", countOrderEnd + countOrderAppraise);
        result.put("countOrderJin", countOrderJin);
        result.put("succeedRate", succeedRate);
        result.put("sumCount", countOrderEnd + countOrderAppraise);
        result.put("goodsRate", goodsRate);
        result.put("loseRate", loseRate);
        return Result.success().put("data", result);
    }

    @Override
    public Result selectTodayOrder(Long artificerId, Integer page, Integer limit, Integer type, String startTime, String endTime) {
        Integer minutes = Integer.valueOf(commonInfoService.findOne(452).getValue());
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        Page<Orders> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(ordersDao.selectTodayOrder(pages, artificerId, type, startTime, endTime,minutes));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectArtificerOrder(Long userId, Integer status, Integer page, Integer limit) {
        Page<Orders> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(ordersDao.selectArtificerOrder(pages, userId, status));
        return Result.success().put("data", pageUtils);
    }


    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 Result refundOrders(Long ordersId) {
        Orders orders = baseMapper.selectById(ordersId);
        if (orders.getCouponId() != null) {
            CouponUser couponUser = couponUserService.getById(orders.getCouponId());
            if (couponUser != null && couponUser.getStatus().equals(1)) {
                couponUser.setStatus(0);
                couponUserService.updateById(couponUser);
            }
        }
        artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", ordersId));
        if (orders.getStatus() != 1 && orders.getStatus() != 4) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            List<Orders> ordersList = baseMapper.selectList(new QueryWrapper<Orders>().isNotNull("pay_way").eq("parent_id", orders.getOrdersId()));
            if (orders.getPayWay() == 1 || orders.getPayWay() == 2 || orders.getPayWay() == 3 || orders.getPayWay() == 4) {
                boolean refund = wxService.refund(orders.getOrdersNo(), orders.getPayMoney(), orders.getPayMoney(), orders.getPayWay());
                if (!refund) {
                    return Result.error("退款失败，请联系客服！");
                }
            } else if (orders.getPayWay() == 6) {
                String data = aliPayController.alipayRefund(orders.getOrdersNo(), orders.getPayMoney());
                if (StringUtils.isNotBlank(data)) {
                    log.error(data);
                    JSONObject jsonObject = JSON.parseObject(data);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
            } else {
                if (orders.getUserArtificerMoney() != null && orders.getUserArtificerMoney() == 1) {
                    userMoneyArtificerService.updateMoney(1, orders.getUserId(), orders.getArtificerId(), orders.getPayMoney().doubleValue());
                } else {
                    userMoneyService.updateMoney(1, orders.getUserId(), orders.getPayMoney().doubleValue());
                }

            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getMoney());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setMoney(orders.getPayMoney());
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("订单号：" + orders.getOrdersNo() + ",已原路退款！");
            userMoneyDetails.setTitle("订单退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetails.setArtificerId(orders.getArtificerId());
            userMoneyDetails.setBlRole(1);
            userMoneyDetails.setBlFlag(1);
            userMoneyDetailsService.save(userMoneyDetails);
            for (Orders orders1 : ordersList) {
                if (orders1.getPayWay() == 1 || orders1.getPayWay() == 2 || orders1.getPayWay() == 3 || orders1.getPayWay() == 4) {
                    boolean refund = wxService.refund(orders1.getOrdersNo(), orders1.getPayMoney(), orders1.getPayMoney(), orders1.getPayWay());
                    if (!refund) {
                        return Result.error("退款失败，请联系客服！");
                    }
                } else if (orders1.getPayWay() == 6) {
                    String data = aliPayController.alipayRefund(orders1.getOrdersNo(), orders1.getPayMoney());
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                } else {
                    if (orders1.getUserArtificerMoney() != null && orders1.getUserArtificerMoney() == 1) {
                        userMoneyArtificerService.updateMoney(1, orders1.getUserId(), orders1.getArtificerId(), orders1.getPayMoney().doubleValue());
                    } else {
                        userMoneyService.updateMoney(1, orders1.getUserId(), orders1.getPayMoney().doubleValue());
                    }
                }
                userMoneyDetails = new UserMoneyDetails();
                //查询用户当前余额
                UserMoney userNowMoney12 = userMoneyService.selectUserMoneyByUserId(orders1.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney12.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setMoney(orders1.getPayMoney());
                userMoneyDetails.setUserId(orders1.getUserId());
                userMoneyDetails.setContent("订单号：" + orders1.getOrdersNo() + ",已原路退款！");
                userMoneyDetails.setTitle("加钟订单退款");
                userMoneyDetails.setType(1);
                userMoneyDetails.setState(2);
                userMoneyDetails.setCreateTime(time);
                userMoneyDetails.setArtificerId(orders.getArtificerId());
                userMoneyDetails.setBlRole(1);
                userMoneyDetails.setBlFlag(1);
                userMoneyDetailsService.save(userMoneyDetails);
                orders1.setStatus(4);
                baseMapper.updateById(orders1);
            }
            orders.setStatus(4);
            baseMapper.updateById(orders);
            UserEntity userEntity = userService.selectUserById(orders.getUserId());

            List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
            MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
            //超过十个字 则截取
            String content = massageType.getTitle();
            if (content.length() >= 15) {
                content = content.substring(0, 15) + "...";
            }

            //消息推送
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(248);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());

                msgList.add(content);
                msgList.add("订单已取消，金额已原路退款！");
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
            }

            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("订单通知", "订单已取消，金额已原路退款！", userEntity.getClientid());
            }

            if (StringUtils.isNotBlank(userEntity.getWxOpenId())) {
                String apkey = commonInfoService.findOne(313).getValue();
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("character_string12", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                data.put("thing17", new TemplateMessageItem(content, "#d71345"));
                data.put("time14", new TemplateMessageItem(DateUtils.format(new Date()), "#d71345"));
                userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
            }
        }
        return Result.success();
    }

    @Override
    public Result updateArtificerCreditScore(Integer type, BigDecimal creditScore, Long artificerId) {
        Artificer artificer = artificerService.getById(artificerId);
        BigDecimal newCreditScore = BigDecimal.ZERO;
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState("8");
        messageInfo.setUserId(String.valueOf(artificer.getUserId()));
        messageInfo.setTitle("系统修改信誉分");
        if (type == 1) {
            newCreditScore = artificer.getCreditScore().add(creditScore);
            messageInfo.setContent("增加信誉分：" + creditScore);
        } else {
            newCreditScore = artificer.getCreditScore().subtract(creditScore);
            messageInfo.setContent("扣除信誉分：" + creditScore);
        }
        artificer.setCreditScore(newCreditScore);
        String value = commonInfoService.findOne(385).getValue();
        BigDecimal minScore = new BigDecimal(value);
        if (artificer.getCreditScore().doubleValue() < minScore.doubleValue()) {
            artificer.setStatus(2);
        }
        artificerService.updateById(artificer);
        messageService.saveBody(messageInfo);
        return Result.success();
    }

    @Override
    public void endOrders() {
        String value = commonInfoService.findOne(316).getValue();
        List<Orders> ordersList = baseMapper.selectOrdersByEndTime(value);
        for (Orders orders : ordersList) {
            Artificer artificer = artificerService.getById(orders.getArtificerId());
            orders.setIsSend(1);
            updateById(orders);
            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            singleThreadPool.submit(new Runnable() {
                @Override
                public void run() {
//                    sendAliPhone(userEntity.getPhone(), 2);
                }
            });


            if (userEntity != null) {

                if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                    userService.pushToSingle("订单通知", "订单即将结束，请与客户进行确认", userEntity.getClientid());
                }
                CommonInfo sms = commonInfoService.findOne(396);
                if ("是".equals(sms.getValue())) {
                    if (StringUtils.isNotEmpty(userEntity.getPhone())) {
                        userService.sendMsg(userEntity.getPhone(), "end");
                    }
                }


                List<OrdersMassage> ordersMassageList = ordersMassageService.list(new QueryWrapper<OrdersMassage>().eq("orders_id", orders.getOrdersId()));
                MassageType massageType = massageTypeService.getById(ordersMassageList.get(0).getMassageId());
                //超过十个字 则截取
                String content = massageType.getTitle();
                if (content.length() >= 15) {
                    content = content.substring(0, 15) + "...";
                }

                if (StringUtils.isNotEmpty(userEntity.getArtificerOpenId())) {
                    CommonInfo one = commonInfoService.findOne(309);
                    List<String> msgList = new ArrayList<>();
                    msgList.add(orders.getOrdersNo());

                    msgList.add(content);
                    msgList.add("订单即将结束，请与客户进行确认");
                    msgList.add(orders.getEndTime());
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 5);
                }
                /*if(StringUtils.isNotBlank(userEntity.getWxOpenId())){
                    String apkey = commonInfoService.findOne(315).getValue();
                    LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                    data.put("character_string1", new TemplateMessageItem(orders.getOrdersNo(), "#d71345"));
                    data.put("thing2", new TemplateMessageItem(content, "#d71345"));
                    data.put("time7", new TemplateMessageItem(orders.getEndTime(), "#d71345"));
                    userService.sendWxMessage(apkey, data, userEntity.getWxOpenId());
                }*/
            }


        }
    }


    public void sendAliPhone(String phone, Integer classify) {
        String value1 = commonInfoService.findOne(311).getValue();
        if ("是".equals(value1)) {
            String accessKeyId = commonInfoService.findOne(288).getValue();
            String accessKeySecret = commonInfoService.findOne(289).getValue();
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(accessKeyId)
                    // 您的AccessKey Secret
                    .setAccessKeySecret(accessKeySecret);
            // 访问的域名
            config.endpoint = "dyvmsapi.aliyuncs.com";

            String value2 = commonInfoService.findOne(317).getValue();
            if ("1".equals(value2)) {

                try {
                    Client client = new Client(config);
                    //使用公共模式发起语音通知时，CalledShowNumber参数必须为空。
                    //使用专属号码发起语音通知时，CalledShowNumber参数必须为已购买的手机号码。
                    SingleCallByTtsRequest singleCallByTtsRequest = new SingleCallByTtsRequest();
                    String value = commonInfoService.findOne(290).getValue();
                    if ("2".equals(value)) {
                        singleCallByTtsRequest.setCalledShowNumber(commonInfoService.findOne(291).getValue());
                    }
                    singleCallByTtsRequest.setCalledNumber(phone);
                    if (classify == 1) {
                        singleCallByTtsRequest.setTtsCode(commonInfoService.findOne(310).getValue());
                    } else {
                        singleCallByTtsRequest.setTtsCode(commonInfoService.findOne(292).getValue());
                    }

                    // 复制代码运行请自行打印API的返回值
                    SingleCallByTtsResponse singleCallByTtsResponse = client.singleCallByTts(singleCallByTtsRequest);
                    SingleCallByTtsResponseBody body = singleCallByTtsResponse.getBody();
                    log.error("阿里云语音通知返回值：" + body.getMessage() + ",状态值：" + body.getCode());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("阿里云语音通知异常：" + e.getMessage(), e);
                }

            } else {
                try {
                    Client client = new Client(config);
                    //使用公共模式发起语音通知时，CalledShowNumber参数必须为空。
                    //使用专属号码发起语音通知时，CalledShowNumber参数必须为已购买的手机号码。
                    SingleCallByVoiceRequest singleCallByVoiceRequest = new SingleCallByVoiceRequest();
                    String value = commonInfoService.findOne(290).getValue();
                    if ("2".equals(value)) {
                        singleCallByVoiceRequest.setCalledShowNumber(commonInfoService.findOne(291).getValue());
                    }
                    singleCallByVoiceRequest.setCalledNumber(phone);
                    if (classify == 1) {
                        singleCallByVoiceRequest.setVoiceCode(commonInfoService.findOne(310).getValue());
                    } else {
                        singleCallByVoiceRequest.setVoiceCode(commonInfoService.findOne(292).getValue());
                    }

                    // 复制代码运行请自行打印API的返回值
                    SingleCallByVoiceResponse singleCallByVoiceResponse = client.singleCallByVoice(singleCallByVoiceRequest);
                    SingleCallByVoiceResponseBody body = singleCallByVoiceResponse.getBody();
                    log.error("阿里云语音通知返回值：" + body.getMessage() + ",状态值：" + body.getCode());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("阿里云语音通知异常：" + e.getMessage(), e);
                }
            }


        }
    }

    @Override
    public Result selectTeamOrdersList(Integer page, Integer limit, Long userId, Integer type, Integer status) {
        return Result.success().put("data", new PageUtils(baseMapper.selectTeamOrdersList(new Page<>(page, limit), userId, type, status)));
    }

    @Override
    public Result selectTeamUserList(Integer page, Integer limit, String invitationCode, Integer type, Long userId) {
        return Result.success().put("data", new PageUtils(baseMapper.selectTeamUserList(new Page<>(page, limit), invitationCode, type, userId)));
    }

    @Override
    public Double selectOrdersMoneyCountByUserId(Long userId, Integer type, String time) {
        return baseMapper.selectOrdersMoneyCountByUserId(userId, type, time);
    }

    @Override
    public Integer selectUserCountByInvitationCode(String invitationCode, Integer type) {
        return baseMapper.selectUserCountByInvitationCode(invitationCode, type);
    }

    @Override
    public Integer selectOrdersCountStatisticsByYear(Integer flag, String time, Integer status) {
        return baseMapper.selectOrdersCountStatisticsByYear(flag, time, status);
    }

    @Override
    public Result selectArtificerOrdersList(Integer page, Integer limit, String artificerName, String artificerPhone,
                                            String userName, String phone, Integer warning, Integer overTimeOrders) {
        return Result.success().put("data",
                new PageUtils(baseMapper.selectArtificerOrdersList(new Page<>(page, limit), artificerName, artificerPhone, userName, phone, warning, overTimeOrders)));
    }

//    @Scheduled(cron = "0 */1 * * * ?")
    @Scheduled(cron = "0 1/5 * * * ?")
    public void updateOrdersWarning() {
        String value = commonInfoService.findOne(376).getValue();
        baseMapper.updateOrdersWarning(value);
        String value1 = commonInfoService.findOne(388).getValue();
        List<Orders> ordersList = baseMapper.selectOrdersStatusByTime(value1);
        for (Orders orders : ordersList) {
            orders.setStatus(4);
            orders.setCancelRemark("未支付-系统");
            baseMapper.updateById(orders);
            artificerTimeService.remove(new QueryWrapper<ArtificerTime>().eq("orders_id", orders.getOrdersId()));
            if (orders.getCouponId() != null && orders.getOldOrdersId()==null) {
                CouponUser couponUser = couponUserService.getById(orders.getCouponId());
                if (couponUser != null && couponUser.getStatus().equals(1)) {
                    couponUser.setStatus(0);
                    couponUserService.updateById(couponUser);
                }
            }
            if(orders.getOldOrdersId()!=null && orders.getOldOrdersId() !=0){
                Orders ordersOld = new Orders();
                ordersOld.setOrdersId(orders.getOldOrdersId());
                if(orders.getIsSupplement() != null){
                    if(orders.getIsSupplement() == 1){
                        ordersOld.setStatus(10);
                    }else if(orders.getIsSupplement() == 2){
                        ordersOld.setStatus(6);
                    }else if(orders.getIsSupplement() == 3){
                        ordersOld.setStatus(2);
                    }else{
                        ordersOld.setStatus(9);//用户已支付技师待接单
                    }
                }else{
                    ordersOld.setStatus(9);//用户已支付技师待接单
                }
                baseMapper.updateById(ordersOld);//原单暂变成挂单状态
            }
        }
    }

    @Override
    public Result selectShopMoney(Integer page, Integer limit, String userName, String phone, String flag, String time) {
        return Result.success().put("data", baseMapper.selectShopMoney(new Page<>(page, limit), userName, phone, flag, time));
    }

    @Override
    public Result selectOneUserMoney(Integer page, Integer limit, String userName, String phone, String flag, String time) {
        return Result.success().put("data", baseMapper.selectOneUserMoney(new Page<>(page, limit), userName, phone, flag, time));
    }

    @Override
    public Result selectOneArtificerMoney(Integer page, Integer limit, String userName, String phone, String flag, String time) {
        return Result.success().put("data", baseMapper.selectOneArtificerMoney(new Page<>(page, limit), userName, phone, flag, time));
    }

    @Override
    public Result selectArtificerMoney(Integer page, Integer limit, String userName, String phone, String flag, String time) {
        return Result.success().put("data", baseMapper.selectArtificerMoney(new Page<>(page, limit), userName, phone, flag, time));
    }

    @Override
    public Result selectNewUserOrdersCount(Integer page, Integer limit, String userName, String phone) {
        return Result.success().put("data", baseMapper.selectNewUserOrdersCount(new Page<>(page, limit), userName, phone));
    }

    @Override
    public Result selectNewUserOrdersRate() {
        return Result.success().put("data", baseMapper.selectNewUserOrdersRate());
    }

    @Override
    public Result selectDividedIntoDetail(Period period) {
        if(StringUtil.isNotEmpty(period.getArtificerId())) {
            Result.error("系统异常，请联系管理员");
        }
        //插入开始结束时间
        UserMoneyArtificerDetails userMoneyArtificerDetails = new UserMoneyArtificerDetails();
        userMoneyArtificerDetails.setStartFundData(period.getStartFundData());
        userMoneyArtificerDetails.setEndFundData(period.getEndFundData());

        Long artificerId = Long.valueOf(period.getArtificerId());
        String startDate = DateUtils.format(period.getStartFundData());
        String endDate = DateUtils.format(period.getEndFundData());
        //总顶顶那收益
        BigDecimal sy = ordersDao.selectOrdersArtificerIntegralEarnings(artificerId,endDate,startDate);
        userMoneyArtificerDetails.setTotalRevenue(sy);

        BigDecimal xmsy = ordersDao.selectOrdersArtificerIntegralProjectEarnings(artificerId,endDate,startDate);
        userMoneyArtificerDetails.setProjectBenefits(xmsy);

        BigDecimal cfsy = sy.subtract(xmsy);
        userMoneyArtificerDetails.setVehicleFareAmount(cfsy);

        //资金明细添加到返回对象中
        return Result.success().put("data", userMoneyArtificerDetails);
    }
    @Override
    public Result selectDividedIntoDetails(Integer page, Integer limit, Period period) {
        Page<Orders> page1 = new Page(page, limit);
        String startFundData = DateUtils.format(period.getStartFundData());
        String endFundData = DateUtils.format(period.getEndFundData());
        return Result.success().put("data", baseMapper.selectDividedIntoDetails(page1,Long.valueOf(period.getArtificerId()),startFundData,endFundData,null));

    }

    @Override
    public Result splitDetails(Period period) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper();
        //查询对应技师id以及
        queryWrapper.eq("orders_id", period.getOrderId()).or().eq("parent_id", period.getOrderId());
        //只查询已完成和待评价的订单
        queryWrapper.in("status", Arrays.asList(5, 3));
        List<Orders> ordersList =  baseMapper.selectList(queryWrapper);
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("ordersId");
        treeNodeConfig.setParentIdKey("parentId");
        List<Tree<Long>> trees = TreeUtil.build(ordersList, 0L, treeNodeConfig, ((object, treeNode) -> {
            treeNode.setId(object.getOrdersId());//id
            treeNode.setParentId(object.getParentId());//父id
            treeNode.putExtra("entryName", object.getEntryName());//项目名称
            treeNode.putExtra("serveTime", object.getServeTime());//服务时间
            treeNode.putExtra("payTime", object.getPayTime());//下单时间
            treeNode.putExtra("ordersNo", object.getOrdersNo());//订单号
            treeNode.putExtra("couponMoney", object.getCouponMoney());//优惠券金额
            treeNode.putExtra("price", object.getPrice());//服务金额
            treeNode.putExtra("artificerRate", object.getArtificerRate());//提成比例
            treeNode.putExtra("projectBenefits", object.getProjectBenefits());//项目收益
            treeNode.putExtra("channelDeduction", object.getChannelDeduction());//渠道扣费
            treeNode.putExtra("valueStorageDeduction",object.getValueStorageDeduction());//储值扣费
            treeNode.putExtra("totalDeduction", object.getChannelDeduction().add(object.getValueStorageDeduction()));//合计扣费
            treeNode.putExtra("artificerTaxiMoney", object.getArtificerTaxiMoney());//车费金额
//            treeNode.putExtra("revenueAmount",object.getArtificerTaxiMoney().add(object.getProjectBenefits()).subtract(object.getChannelDeduction().add(object.getValueStorageDeduction())));//收益金额
        }));
        //项目金额
        BigDecimal Price = BigDecimal.valueOf(ordersList.stream().map(Orders->new BigDecimal(String.valueOf(Orders.getPrice()))).collect(Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        BigDecimal couponMoney = new BigDecimal(trees.get(0).get("couponMoney").toString());
        //实际项目金额
        trees.get(0).put("allPrice",Price.subtract(couponMoney));
        //项目收益
        BigDecimal projectBenefits = BigDecimal.valueOf(ordersList.stream().map(Orders->new BigDecimal(String.valueOf(Orders.getProjectBenefits()))).collect(Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        //实际项目收益
        trees.get(0).put("actualProjectBenefits",projectBenefits);
        BigDecimal artificerTaxiMoney = new BigDecimal(trees.get(0).get("artificerTaxiMoney").toString());
        //实际总收益
        trees.get(0).put("totalRevenue",artificerTaxiMoney.add(projectBenefits));
        //分成明细添加到返回对象中
        return Result.success().put("data", trees);
    }

    /**
     * 技师确认接单
     * @param ordersId 订单id
     * @return
     */
    @Override
    public Result jishiQueren(Long ordersId) {
        //获取项目是否包含物料包
        Orders orders = ordersDao.selectById(ordersId);
        Long messageTypeId = orders.getMassageTypeId();

        CommonInfo commonInfo = commonInfoDao.findOne(448);//查询技师接单是否需要物料的配置
        if(StringUtils.equals("否", commonInfo.getValue())){
            orders = new Orders();
            orders.setOrdersId(ordersId);
            orders.setStatus(2);//确认接单
            ordersDao.updateById(orders);
            Map<String,Object> map = new HashMap<>();
            map.put("code",200);
            map.put("msg","已确认接单");
            return Result.success(map);
        }

        QueryWrapper<MaterialMassage> materialMassageQueryWrapper = new QueryWrapper<>();
        materialMassageQueryWrapper.eq("massage_type_id",messageTypeId);
        //查询服务是否消耗指定的物料信息
        List<MaterialMassage> wllist =materialMassageMapper.selectList(materialMassageQueryWrapper);
        if(wllist.size()>0){
            int code = 200;
            String msg = "已确认接单";
            for(MaterialMassage par: wllist){
                QueryWrapper<MaterialArtificer> materialArtificerQueryWrapper = new QueryWrapper<MaterialArtificer>();
                materialArtificerQueryWrapper.eq("material_id",par.getMaterialId());
                materialArtificerQueryWrapper.eq("artificer_id",orders.getArtificerId());
                materialArtificerQueryWrapper.orderByDesc("residue");
                materialArtificerQueryWrapper.last("limit 1");
                //获取技师是否有对应的物料
                MaterialArtificer materialArtificer = materialArtificerMapper.selectOne(materialArtificerQueryWrapper);

                if(materialArtificer == null){
                    //获取缺少的物料
                    Material material = materialMapper.getById(par.getMaterialId());
                    code = 500;
                    msg = "此服务需要【"+material.getMaterialName()+"】物料，您还没有此物料信息";
                    break;
                }
                BigDecimal consume = par.getConsume();//每次服务需要消耗的数量
                BigDecimal residue = materialArtificer.getResidue();//技师剩余物料库存

                if(residue.compareTo(consume) < 0){//库存不足
                    //获取缺少的物料
                    Material material = materialMapper.getById(par.getMaterialId());
                    code = 500;
                    msg = "【"+material.getMaterialName()+"】库存不足，剩余数量：【"+residue+"】，消耗数量：【"+consume+"】";
                    break;
                }
            }

            orders = new Orders();
            orders.setOrdersId(ordersId);
            if(code == 200){
                Map<String,Object> map = new HashMap<>();
                map.put("code",code);
                map.put("msg",msg);
                orders.setStatus(2);//确认接单
                ordersDao.updateById(orders);
                return Result.success(map);
            }else{
                return Result.error(msg);
            }

        }else{
            orders = new Orders();
            orders.setOrdersId(ordersId);
            orders.setStatus(2);//确认接单
            ordersDao.updateById(orders);
            Map<String,Object> map = new HashMap<>();
            map.put("code",200);
            map.put("msg","已确认接单");
            return Result.success(map);
        }
    }

    @Override
    @Transactional
    public Result jszd(Long orderId, Long artificerId) {
        Orders orders = ordersDao.selectById(orderId);

        Long parentId = orders.getParentId();
        Long oldOrdersId = orders.getOldOrdersId();
        if(parentId != null && parentId != 0){
            Orders parentorders = ordersDao.selectById(parentId);
            parentorders.setArtificerId(artificerId);
            ordersDao.updateById(parentorders);

        }
        if(oldOrdersId!=null){
            Orders oldorders = ordersDao.selectById(oldOrdersId);
            oldorders.setArtificerId(artificerId);
            ordersDao.updateById(oldorders);
        }
        orders.setArtificerId(artificerId);
        ordersDao.updateById(orders);
        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","转单成功");
        return Result.success(map);
    }

}