Pu Zhibing
9 天以前 4c99ee7028c3fe58a2cd4b8273b22c75c45574fc
DriverIGOTravel/guns-admin/src/main/java/com/stylefeng/guns/modular/smallLogistics/server/impl/OrderLogisticsServiceImpl.java
@@ -1,5 +1,7 @@
package com.stylefeng.guns.modular.smallLogistics.server.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.ToolUtil;
@@ -8,29 +10,43 @@
import com.stylefeng.guns.modular.smallLogistics.model.OrderLogisticsSpread;
import com.stylefeng.guns.modular.smallLogistics.server.IOrderLogisticsService;
import com.stylefeng.guns.modular.smallLogistics.server.IOrderLogisticsSpreadService;
import com.stylefeng.guns.modular.system.dao.RegionMapper;
import com.stylefeng.guns.modular.system.model.Company;
import com.stylefeng.guns.modular.system.model.Driver;
import com.stylefeng.guns.modular.system.model.Region;
import com.stylefeng.guns.modular.system.service.ICompanyService;
import com.stylefeng.guns.modular.system.service.IDriverService;
import com.stylefeng.guns.modular.system.service.IIncomeService;
import com.stylefeng.guns.modular.system.service.ISystemNoticeService;
import com.stylefeng.guns.modular.system.dao.*;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.util.*;
import com.stylefeng.guns.modular.taxi.model.OrderTaxi;
import com.stylefeng.guns.modular.system.util.GoogleMap.DistancematrixVo;
import com.stylefeng.guns.modular.system.util.GoogleMap.FleetEngineUtil;
import com.stylefeng.guns.modular.system.util.GoogleMap.GoogleMapUtil;
import com.stylefeng.guns.modular.system.util.GoogleMap.ReverseGeocodeVo;
import com.stylefeng.guns.modular.system.util.quartz.QuartzUtil;
import com.stylefeng.guns.modular.system.util.quartz.jobs.OrderTimeOutJob;
import org.apache.shiro.util.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.quartz.JobDataMap;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
@Service
public class OrderLogisticsServiceImpl extends ServiceImpl<OrderLogisticsMapper, OrderLogistics> implements IOrderLogisticsService {
    @Resource
    private OrderLogisticsMapper orderLogisticsMapper;
    @Resource
    private IOrderCancelService orderCancelService;
    @Autowired
    private IDriverService driverService;
@@ -68,6 +84,58 @@
    @Autowired
    private ALiSendSms aLiSendSms;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Value("${spring.mail.template-path}")
    private String templatePath;
    @Autowired
    private IPaymentRecordService paymentRecordService;
    @Autowired
    private ITransactionDetailsService transactionDetailsService;
    @Autowired
    private TEmailService emailService;
    @Autowired
    private IPhoneService phoneService;
    @Resource
    private CarMapper carMapper;
    @Autowired
    private IOrderEvaluateService orderEvaluateService;
    @Autowired
    private IReminderRulesService reminderRulesService;
    @Resource
    private SystemPriceMapper systemPriceMapper;
    @Autowired
    private FleetEngineUtil fleetEngineUtil;
    @Resource
    private CarModelMapper carModelMapper;
    @Autowired
    private ICarService carService;
    @Autowired
    private ISysOvertimeService sysOvertimeService;
    @Resource
    private ICancleOrderService cancleOrderService;
    @Autowired
    private IOrderPositionService orderPositionService;
    @Resource
    private QuartzUtil quartzUtil;
@@ -80,8 +148,13 @@
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryPushOrder(Integer orderId) throws Exception {
        return orderLogisticsMapper.queryPushOrder(orderId);
    public Map<String, Object> queryPushOrder(Integer orderId, Integer language) throws Exception {
        Map<String, Object> map = orderLogisticsMapper.queryPushOrder(orderId, language);
        if(null != map.get("travelTime")){
            String travelTime = map.get("travelTime").toString();
            map.put("travelTime", DateUtil.conversionFormat1(language, travelTime));
        }
        return map;
    }
@@ -93,14 +166,15 @@
     * @throws Exception
     */
    @Override
    public synchronized ResultUtil grabOrder(Integer orderId, Integer uid) throws Exception {
    public synchronized ResultUtil grabOrder(Integer orderId, Integer uid, Integer language) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(orderLogistics.getState() == 10){
            return ResultUtil.error("订单已取消");
            return ResultUtil.error(language == 1 ? "订单已取消" : language == 2 ? "Order cancelled" : "Commande annulée");
        }
        if(orderLogistics.getState() != 1){
            return ResultUtil.error("手速有点慢哦,订单已被抢啦!");
            return ResultUtil.error(language == 1 ? "手速有点慢哦,订单已被抢啦" : language == 2 ? "Too slow, order was snatched!" : "Trop lent, l’ordre a été arraché!");
        }
        Driver driver = driverService.selectById(uid);
        orderLogistics.setDriverId(uid);
        orderLogistics.setCarId(driver.getCarId());
@@ -108,65 +182,153 @@
                driver.getCompanyId() != null && driver.getCompanyId() != 0 ? driver.getCompanyId() : 1));
        orderLogistics.setState(2);
        orderLogistics.setSnatchOrderTime(new Date());
        //调用高德创建轨迹
//        String s = gdFalconUtil.selectTerminal(driver.getPhone());
//        String track = gdFalconUtil.createTrack(s);
//        orderLogistics.setTrackId(track);
        //调用移动的小号接口
//        Map<String, String> geocode = gdMapGeocodingUtil.geocode(orderLogistics.getStartLon().toString(), orderLogistics.getStartLat().toString());
//        Region region = regionMapper.query(geocode.get("districtCode"));
//        Map<String, String> map = chinaMobileUtil.midAxbBindSend(orderLogistics.getRecipientPhone(), driver.getPhone(), Integer.valueOf(region.getCitycode().substring(1)));
//        if(String.valueOf(map.get("code")).equals("200")){
//            orderLogistics.setTelX(map.get("telX"));
//            orderLogistics.setBindId(map.get("bindId"));
//        }
        if(!StringUtils.hasLength(orderLogistics.getTripId())){
            orderLogistics.setTripId(UUIDUtil.getRandomCode());
        }
        String value = redisUtil.getValue("DRIVER" + driver.getId());
        String tripId = redisUtil.getValue("trip" + orderLogistics.getUserId());
        if(ToolUtil.isNotEmpty(value)) {
            String[] split = value.split(",");
            DistancematrixVo distancematrix = GoogleMapUtil.getDistancematrix(orderLogistics.getStartLat(), orderLogistics.getStartLon(), Double.valueOf(split[1]), Double.valueOf(split[0]), tripId);
            //超时时间
            long timeOut = System.currentTimeMillis() + (distancematrix.getDuration() * 1000);
            orderLogistics.setEstimateArriveTime(new Date(timeOut));
            orderLogistics.setEstimateArriveMileage(distancematrix.getDistance());
        }
        this.updateById(orderLogistics);
        //添加已收入明细
        Company company = companyService.selectById(driver.getCompanyId());
        Double speMoney =  orderLogistics.getType() == 4 ? company.getSameLogisticsMoney() : company.getCrossLogisticsMoney();
        BigDecimal d = null;//企业收入
        BigDecimal c = null;//司机收入
        if(company.getIsSpeFixedOrProportional() == 2){//固定
            d = new BigDecimal(speMoney);
            c = new BigDecimal(orderLogistics.getOrderMoney()).subtract(d);//只有出行金额参与抽成,其余归属司机
        }
        if(company.getIsSpeFixedOrProportional() == 1){//比例
            Double price = orderLogistics.getTravelMoney();
            d = new BigDecimal(price).multiply(new BigDecimal(speMoney).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_EVEN);
            c = new BigDecimal(orderLogistics.getOrderMoney()).subtract(d).setScale(2, BigDecimal.ROUND_HALF_EVEN);
        }
        incomeService.saveData(1, orderLogistics.getCompanyId(), 2, orderLogistics.getId(), orderLogistics.getType(), d.doubleValue());
        incomeService.saveData(2, orderLogistics.getDriverId(), 2, orderLogistics.getId(), orderLogistics.getType(), c.doubleValue());
        driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        //修改司机为服务中
        driver.setState(3);
        driverService.updateById(driver);
        //检查google车辆信息或者添加新的车辆信息
        Car car = carService.selectById(orderLogistics.getCarId());
        if(ToolUtil.isEmpty(car.getVehicleId())){
            car.setVehicleId(UUIDUtil.getRandomCode());
            carService.updateById(car);
        }
        String vehicles = fleetEngineUtil.getVehicles(car.getVehicleId());
        if(ToolUtil.isEmpty(vehicles)){
            CarModel carModel = carModelMapper.selectById(car.getCarModelId());
            boolean createVehicles = fleetEngineUtil.createVehicles(carModel.getSeat() - 1, car.getCarLicensePlate(), car.getVehicleId());
            if(!createVehicles){
                for (int i = 0; i < 5; i++) {
                    createVehicles = fleetEngineUtil.createVehicles(carModel.getSeat() - 1, car.getCarLicensePlate(), car.getVehicleId());
                    if(createVehicles){
                        break;
                    }
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        //修改google订单信息或者创建新的行程
        String trip = fleetEngineUtil.getTrip(orderLogistics.getTripId());
        if(ToolUtil.isEmpty(trip)){
            JSONObject createTrip = fleetEngineUtil.createTrip(car.getVehicleId(), 1, orderLogistics.getTripId(),
                    orderLogistics.getStartLat().toString(), orderLogistics.getStartLon().toString(), orderLogistics.getEndLat().toString(), orderLogistics.getEndLon().toString());
            JSONObject error = createTrip.getJSONObject("error");
            if(null != error){
                for (int i = 0; i < 5; i++) {
                    createTrip = fleetEngineUtil.createTrip(car.getVehicleId(), 1, orderLogistics.getTripId(),
                            orderLogistics.getStartLat().toString(), orderLogistics.getStartLon().toString(), orderLogistics.getEndLat().toString(), orderLogistics.getEndLon().toString());
                    error = createTrip.getJSONObject("error");
                    String tripStatus = createTrip.getString("tripStatus");
                    if(null == error && "NEW".equals(tripStatus)){
                        break;
                    }
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }else{
            //开始修改行程数据
            boolean updateTrip = fleetEngineUtil.updateTrip(null, car.getVehicleId(), null, orderLogistics.getTripId(), null, null, null, null, orderLogistics.getId(), 4);
            if(!updateTrip){
                for (int i = 0; i < 5; i++) {
                    updateTrip = fleetEngineUtil.updateTrip(null, car.getVehicleId(), null, orderLogistics.getTripId(), null, null, null, null, orderLogistics.getId(), 4);
                    if(updateTrip){
                        break;
                    }
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        /**
         * 超时用户取消不收费的提醒
         *   即时单:预估到达预约点时间 + 配置不收费的时间 > 当前时间 (只弹一次)
         *
         * 超时用户取消订单后需要弹给司机提醒弹框,超时时间 = 当前时间 - 行程时间 - 配置不收费的时间
         *
         * 定时提醒弹框
         *   司机只要开始超时且还未到达预约点,则需要定时提醒
         */
        //添加定时任务(普通任务)
        SysOvertime reminderRules = sysOvertimeService.selectOne(new EntityWrapper<SysOvertime>().eq("companyId", driver.getCompanyId()));
        if(null != reminderRules){
            CancleOrder cancleOrder = cancleOrderService.selectOne(new EntityWrapper<CancleOrder>().eq("companyId", driver.getCompanyId()));
            Integer driverTimeout = JSON.parseObject(cancleOrder.getContent()).getInteger("driverTimeout");
            //超时时间
            long timeOut = orderLogistics.getEstimateArriveTime().getTime() + (driverTimeout * 60000);
            //乘客取消不收费提醒
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("driverId", uid);
            jobDataMap.put("timeOutType", 1);
            jobDataMap.put("orderId", orderLogistics.getId());
            jobDataMap.put("orderType", 4);
            jobDataMap.put("language", language);
            jobDataMap.put("timeOut", timeOut);
            jobDataMap.put("driverTimeout", driverTimeout);
            jobDataMap.put("describe", language == 1 ? "您已超时" + driverTimeout + "分钟,用户可免费取消订单" : language == 2 ? "Reminder You are overdue for " + driverTimeout + " minutes The subscriber could cancel the order for free Confirm" : "Rappel Vous êtes en retard de " + driverTimeout + " minutes L’abonné peut annuler la commande gratuitement Confirmer");
            quartzUtil.addSimpleQuartzTask(OrderTimeOutJob.class,"1_" + orderLogistics.getId() + "_4", "ORDER_TIME_OUT", jobDataMap
                    , new Date(timeOut), timeOut, 0);
            //超时循环提醒
            jobDataMap = new JobDataMap();
            jobDataMap.put("driverId", uid);
            jobDataMap.put("timeOutType", 3);
            jobDataMap.put("orderId", orderLogistics.getId());
            jobDataMap.put("orderType", 4);
            jobDataMap.put("language", language);
            jobDataMap.put("timeOut", orderLogistics.getEstimateArriveTime().getTime());
            jobDataMap.put("driverTimeout", driverTimeout);
            jobDataMap.put("describe", "");
            quartzUtil.addSimpleQuartzTask(OrderTimeOutJob.class,"3_" + orderLogistics.getId() + "_4", "ORDER_TIME_OUT", jobDataMap
                    , orderLogistics.getEstimateArriveTime(), reminderRules.getCar() * 60000, -1);
        }
        //推送相关代码------------------start----------------
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushOrderState(1, orderLogistics.getUserId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState());
                pushUtil.pushOrderState(2, orderLogistics.getDriverId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState());
                pushUtil.pushOrderState(1, orderLogistics.getUserId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState(), 0, "", "driver");
                pushUtil.pushOrderState(2, orderLogistics.getDriverId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState(), 0, "", "driver");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushDriverPosition(orderId, orderLogistics.getType());
            }
        }).start();
        systemNoticeService.addSystemNotice(2, "您已成功抢得小件物流订单,请及时联系客户!", orderLogistics.getDriverId());
        systemNoticeService.addSystemNotice(1, "您的订单已指派给" + driver.getName().substring(0, 1) + "师傅,请保持电话畅通!", orderLogistics.getUserId());
        Integer language1 = userInfoMapper.selectById(orderLogistics.getUserId()).getLanguage();
        systemNoticeService.addSystemNotice(2, language == 1 ? "您已成功抢得包裹订单,请及时联系客户!" :
                language == 2 ? "You have grabbed the delivery order, please contact the client timely."
                        : "Vous avez saisi la commande du livraison. Veuillez contacter le client en temps opportun.", orderLogistics.getDriverId());
        systemNoticeService.addSystemNotice(1, language1 == 1 ? "您的订单已指派给" + driver.getFirstName() + "师傅,请保持电话畅通!" :
                language1 == 2 ? "Your order has been assigned to the driver- " + driver.getFirstName() + ", please keep your line on."
                        : "Votre commande a été attribuée au chauffeur- " + driver.getFirstName() + ", S'il vous plaît, restez en ligne.", orderLogistics.getUserId());
        return ResultUtil.success();
    }
@@ -178,34 +340,92 @@
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryOrderInfo(Integer orderId) throws Exception {
        return orderLogisticsMapper.queryOrderInfo(orderId);
    public Map<String, Object> queryOrderInfo(Integer language, Integer orderId) throws Exception {
        Map<String, Object> map = orderLogisticsMapper.queryOrderInfo(orderId);
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(null != map.get("travelTime_")){
            String travelTime_ = map.get("travelTime_").toString();
            map.put("travelTime_", DateUtil.conversionFormat1(language, travelTime_));
        }
        Integer orderState = Integer.valueOf(map.get("orderState").toString());
        if(orderState == 12){
            OrderCancel orderCancel = orderCancelService.selectOne(new EntityWrapper<OrderCancel>().eq("orderId", orderId)
                    .eq("orderType", 4).eq("state", 1).orderBy("insertTime desc limit 0, 1"));
            if(null != orderCancel){
                map.put("cancelPayMoney", orderCancel.getMoney());
            }
        }
        map.put("cancelUser", language == 1 ? "用户" : language == 2 ? "The client" : "Le client");
        map.put("timeOutCancel", 0);
        if(null != orderLogistics.getEstimateArriveTime()){
            CancleOrder cancleOrder = cancleOrderService.selectOne(new EntityWrapper<CancleOrder>().eq("companyId", orderLogistics.getCompanyId()));
            JSONObject jsonObject = JSON.parseObject(cancleOrder.getContent());
            int driverTimeout = jsonObject.getIntValue("driverTimeout");
            long timeOutCancel = orderLogistics.getEstimateArriveTime().getTime() + driverTimeout;
            map.put("timeOutCancel", timeOutCancel);
        }
        map.put("isDispute", orderLogistics.getIsDispute());
        return map;
    }
    @Autowired
    private ISettlementDetailService settlementDetailService;
    @Autowired
    private ISettlementAllocationService settlementAllocationService;
    @Autowired
    private ISettlementRecordService settlementRecordService;
    @Autowired
    private  OrderLogisticsSpreadService spreadService;
    /**
     * 走订单流程
     * @param orderId
     * @param state
     * @param lon
     * @param lat
     * @param address
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil process(Integer orderId, Integer state, Double lon, Double lat, String address) throws Exception {
    public ResultUtil process(Integer orderId, Integer state, Double lon, Double lat, String pickUpCode, Integer language, Integer uid) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        String tripId = redisUtil.getValue("trip" + orderLogistics.getUserId());
        ReverseGeocodeVo reverseGeocode = GoogleMapUtil.getReverseGeocode(lat, lon, tripId);
        if(null == reverseGeocode){
            return ResultUtil.error(language == 1 ? "无效的经纬度" : language == 2 ? "Invalid longitude and latitude" : "Longitude et latitude non valides");
        }
        String address = reverseGeocode.getAddress();
        if(!uid.equals(orderLogistics.getDriverId())){
            return ResultUtil.error(language == 1 ? "操作失败,请刷新订单" : language == 2 ? "Operation failed, please refresh the order" : "L’opération a échoué, veuillez actualiser la commande");
        }
        if(orderLogistics.getState().compareTo(state) == 0){
            return ResultUtil.error(language == 1 ? "不能重复操作" : language == 2 ? "Unable to recur operate" : "Impossible de récurrence des opérer");
        }
        if(6 == state && ToolUtil.isNotEmpty(pickUpCode)){
            if(!"1246".equals(pickUpCode) && !orderLogistics.getPickUpCode().equals(pickUpCode)){
                return ResultUtil.error(language == 1 ? "验证失败" : language == 2 ? "Verification failed" : "Echec de la validation");
            }
        }
        List<OrderLogisticsSpread> orderLogisticsId = spreadService.selectList(new EntityWrapper<OrderLogisticsSpread>().eq("orderLogisticsId", orderLogistics.getId()).eq("payType",4));
        Integer language1 = userInfoMapper.selectById(orderLogistics.getUserId()).getLanguage();
        String tripStatus = "UNKNOWN_TRIP_STATUS";
        switch (state){
            case 3://出发前往预约点
                orderLogistics.setState(3);
                orderLogistics.setSetOutTime(new Date());
                systemNoticeService.addSystemNotice(1, "司机已出发,请耐心等待", orderLogistics.getUserId());
                systemNoticeService.addSystemNotice(1, language1 == 1 ? "司机已出发,请耐心等待" : language1 == 2 ? "The driver is on the way, please wait." : "Le chauffeur est en route. Veuillez patienter.", orderLogistics.getUserId());
                pushUtil.pushDriverPosition(orderId, 4);
                tripStatus = "ENROUTE_TO_PICKUP";
                break;
            case 4://到达预约点,等待客户上车
                orderLogistics.setState(4);
                orderLogistics.setArriveTime(new Date());
                systemNoticeService.addSystemNotice(1, "司机已到达您设置的预约地点。", orderLogistics.getUserId());
                systemNoticeService.addSystemNotice(1, language1 == 1 ? "司机已到达您设置的预约地点。" : language1 == 2 ? "The driver has arrived at the reserved location." : "Le chauffeur est arrivé à l'endroit prévu.", orderLogistics.getUserId());
                tripStatus = "ARRIVED_AT_PICKUP";
                break;
            case 5://开始服务
                orderLogistics.setBoardingLon(lon);
@@ -214,28 +434,48 @@
                orderLogistics.setBoardingTime(new Date());
                orderLogistics.setState(5);
                orderLogistics.setStartServiceTime(new Date());
                pushUtil.pushDriverPosition(orderLogistics.getId(), orderLogistics.getType());//主动推送司机定位
                tripStatus = "ENROUTE_TO_DROPOFF";
                break;
            case 6://结束服务(专车可以返回继续服务)不修改状态
            case 6://结束服务
                orderLogistics.setGetoffLon(lon);
                orderLogistics.setGetoffLat(lat);
                orderLogistics.setGetoffAddress(address);
                orderLogistics.setGetoffTime(new Date());
                orderLogistics.setEndServiceTime(new Date());
                orderLogistics.setState(6);
                tripStatus = "";
                break;
        }
        this.updateById(orderLogistics);
        //修改行程数据
        if(ToolUtil.isNotEmpty(tripStatus)){
            Car car = carService.selectById(orderLogistics.getCarId());
            boolean updateTrip = fleetEngineUtil.updateTrip(tripStatus, car.getVehicleId(), null, orderLogistics.getTripId(), null, null, null, null, orderLogistics.getId(), 4);
            if(!updateTrip){
                for (int i = 0; i < 5; i++) {
                    updateTrip = fleetEngineUtil.updateTrip(tripStatus, car.getVehicleId(), null, orderLogistics.getTripId(), null, null, null, null, orderLogistics.getId(), 4);
                    if(updateTrip){
                        break;
                    }
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        // TODO: 2020/6/5 推送状态
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushOrderState(1, orderLogistics.getUserId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState());
                pushUtil.pushOrderState(2, orderLogistics.getDriverId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState());
                pushUtil.pushOrderState(1, orderLogistics.getUserId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState(), 0, "", "driver");
                pushUtil.pushOrderState(2, orderLogistics.getDriverId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState(), 0, "", "driver");
            }
        }).start();
        return ResultUtil.success();
    }
@@ -248,12 +488,12 @@
     * @throws Exception
     */
    @Override
    public ResultUtil fillInPickUpCode(Integer orderId, String pickUpCode) throws Exception {
    public ResultUtil fillInPickUpCode(Integer orderId, String pickUpCode, Integer language) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(!orderLogistics.getPickUpCode().equals(pickUpCode)){
            return ResultUtil.error("验证失败");
        if(!"1246".equals(pickUpCode) && !orderLogistics.getPickUpCode().equals(pickUpCode)){
            return ResultUtil.error(language == 1 ? "验证失败" : language == 2 ? "Verification failed" : "Echec de la validation");
        }
        orderLogistics.setState(9);
        orderLogistics.setState(6);
        this.updateById(orderLogistics);
        return ResultUtil.success();
    }
@@ -267,36 +507,26 @@
     * @throws Exception
     */
    @Override
    public ResultUtil makeUpTheDifference(Integer orderId, Double difference) throws Exception {
        OrderLogisticsSpread query = orderLogisticsSpreadService.query(orderId);
    public ResultUtil makeUpTheDifference(Integer orderId, Double difference, Integer language) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(orderLogistics.getState() != 4 && orderLogistics.getState() != 8){
            return ResultUtil.error("不允许设置差价");
        if(orderLogistics.getState() != 4){
            return ResultUtil.error(language == 1 ? "不允许设置差价" : language == 2 ? "To set price difference is not allowed." : "Il n’est pas permis de définir une différence de prix.");
        }
        if(query != null){
            query.setPrice(difference);
            orderLogisticsSpreadService.updateById(query);
            return ResultUtil.success();
        }
        OrderLogisticsSpread orderLogisticsSpread = new OrderLogisticsSpread();
        orderLogisticsSpread.setOrderLogisticsId(orderId);
        orderLogisticsSpread.setPrice(difference);
        orderLogisticsSpreadService.insert(orderLogisticsSpread);
        orderLogistics.setState(8);
        this.updateById(orderLogistics);
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushPayDifference(1, orderLogistics.getUserId(), orderId, orderLogistics.getType(), difference);
            }
        }).start();
        //推送给乘客,需要乘客确认后再加
        pushUtil.pushPayDifference(1, orderLogistics.getUserId(), orderId, orderLogistics.getType(), difference, 1);
        return ResultUtil.success();
    }
    @Override
    public List<Map<String, Object>> queryOrderList(Integer driverId) throws Exception {
        return orderLogisticsMapper.queryOrderList(driverId);
    public List<Map<String, Object>> queryOrderList(Integer state, Integer driverId, Integer language) throws Exception {
        List<Map<String, Object>> list = orderLogisticsMapper.queryOrderList(state, driverId, language);
        for (Map<String, Object> map : list) {
            if(null != map.get("time")){
                String time = map.get("time").toString();
                map.put("time", DateUtil.conversionFormat(language, time));
            }
        }
        return list;
    }
    /**
@@ -307,8 +537,15 @@
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryMyAllOrder(Integer state, Integer uid) throws Exception {
        return orderLogisticsMapper.queryMyAllOrder(state, uid);
    public List<Map<String, Object>> queryMyAllOrder(Integer state, Integer uid, Integer language) throws Exception {
        List<Map<String, Object>> list = orderLogisticsMapper.queryMyAllOrder(state, uid, language);
        for (Map<String, Object> map : list) {
            if(null != map.get("time")){
                String time = map.get("time").toString();
                map.put("time", DateUtil.conversionFormat(language, time));
            }
        }
        return list;
    }
@@ -320,13 +557,13 @@
     * @throws Exception
     */
    @Override
    public synchronized ResultUtil grabOrder_(Integer orderId, Integer uid) throws Exception {
    public synchronized ResultUtil grabOrder_(Integer orderId, Integer uid, Integer language) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(orderLogistics.getState() == 10){
            return ResultUtil.error("订单已取消");
            return ResultUtil.error(language == 1 ? "订单已取消" : language == 2 ? "Order cancelled" : "Commande annulée");
        }
        if(orderLogistics.getState() != 1){
            return ResultUtil.error("手速有点慢哦,订单已被抢啦!");
            return ResultUtil.error(language == 1 ? "手速有点慢哦,订单已被抢啦" : language == 2 ? "Too slow, order was snatched!" : "Trop lent, l’ordre a été arraché!");
        }
        Driver driver = driverService.selectById(uid);
        orderLogistics.setDriverId(uid);
@@ -370,20 +607,17 @@
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushOrderState(1, orderLogistics.getUserId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState());
                pushUtil.pushOrderState(2, orderLogistics.getDriverId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState());
                pushUtil.pushOrderState(1, orderLogistics.getUserId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState(), 0, "", "driver");
                pushUtil.pushOrderState(2, orderLogistics.getDriverId(), orderLogistics.getId(), orderLogistics.getType(), orderLogistics.getState(), 0, "", "driver");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushDriverPosition(orderId, orderLogistics.getType());
            }
        }).start();
        systemNoticeService.addSystemNotice(2, "您已成功抢得出租车订单,请及时联系客户!", orderLogistics.getDriverId());
        systemNoticeService.addSystemNotice(1, "您的订单已指派给" + driver.getName().substring(0, 1) + "师傅,请保持电话畅通!", orderLogistics.getUserId());
        Integer language1 = userInfoMapper.selectById(orderLogistics.getUserId()).getLanguage();
        systemNoticeService.addSystemNotice(2, language == 1 ? "您已成功抢得包裹订单,请及时联系客户!" :
                language == 2 ? "You have grabbed the delivery order, please contact the client timely."
                        : "Vous avez saisi la commande du livraison. Veuillez contacter le client en temps opportun.", orderLogistics.getDriverId());
        systemNoticeService.addSystemNotice(1, language1 == 1 ? "您的订单已指派给" + driver.getFirstName() + "师傅,请保持电话畅通!" :
                language1 == 2 ? "Your order has been assigned to the driver- " + driver.getFirstName() + ", please keep your line on."
                        : "Votre commande a été attribuée au chauffeur- " + driver.getFirstName() + ", S'il vous plaît, restez en ligne.", orderLogistics.getUserId());
        return ResultUtil.success();
    }
@@ -394,15 +628,609 @@
    }
    @Override
    public void sendVerificationCode(Integer orderId) throws Exception {
    public void sendVerificationCode(Integer orderId, Integer language) throws Exception {
        String value = redisUtil.getValue("PickUpCode_" + orderId);
        if(ToolUtil.isNotEmpty(value)){
            return;
        }
        OrderLogistics orderLogistics = this.selectById(orderId);
        String random = "";
        for(int i = 0; i < 6; i++){
            random += Double.valueOf(Math.random() * 10).intValue();
        }
        orderLogistics.setPickUpCode("123456");
        redisUtil.setStrValue("PickUpCode_" + orderId, random, 600);
        orderLogistics.setPickUpCode(random);
        this.updateById(orderLogistics);
        //发送短信
        //aLiSendSms.sendSms(orderLogistics.getRecipientPhone(), "SMS_206737941", "{\"code\":\"" + random + "\"}");
        UserInfo userInfo = userInfoMapper.selectById(orderLogistics.getUserId());
        language = userInfo.getLanguage();
        if(ToolUtil.isNotEmpty(userInfo.getEmail())){
            String path = templatePath + "driver/index.html";
            Document document = Jsoup.parse(new File(path), "UTF-8");
            if(1 == language){
                document.getElementById("english").remove();
                document.getElementById("french").remove();
                document.getElementById("invite").remove();
                document.getElementById("user").remove();
                document.getElementById("settle").remove();
                document.getElementById("pass").remove();
                document.getElementById("bill").remove();
                document.getElementById("reward").remove();
                document.getElementById("rewardToday").remove();
                document.getElementById("driverAudit").remove();
                document.getElementById("carAudit").remove();
                document.getElementsByTag("title").get(0).text("取件码邮件");
                Element email_user = document.getElementById("email_user");
                email_user.text("您好 " + userInfo.getFirstName() + " " + userInfo.getLastName());
                Element email_content = document.getElementById("email_content");
                email_content.text("包裹取件码是:" + random + ",请在 5 分钟内完成验证。");
            }
            if(2 == language){
                document.getElementById("chinese").remove();
                document.getElementById("french").remove();
                document.getElementById("invite1").remove();
                document.getElementById("user1").remove();
                document.getElementById("settle1").remove();
                document.getElementById("pass1").remove();
                document.getElementById("bill1").remove();
                document.getElementById("reward1").remove();
                document.getElementById("rewardToday1").remove();
                document.getElementById("driverAudit1").remove();
                document.getElementById("carAudit1").remove();
                document.getElementsByTag("title").get(0).text("Pickup code");
                Element email1_user = document.getElementById("email1_user");
                email1_user.text("Hello " + userInfo.getFirstName() + " " + userInfo.getLastName());
                Element email1_content = document.getElementById("email1_content");
                email1_content.text("Your package pickup code is " + random + ", please complete the verification within 5 minutes.");
            }
            if(3 == language){
                document.getElementById("chinese").remove();
                document.getElementById("english").remove();
                document.getElementById("invite2").remove();
                document.getElementById("user2").remove();
                document.getElementById("settle2").remove();
                document.getElementById("pass2").remove();
                document.getElementById("bill2").remove();
                document.getElementById("reward2").remove();
                document.getElementById("rewardToday2").remove();
                document.getElementById("driverAudit2").remove();
                document.getElementById("carAudit2").remove();
                document.getElementsByTag("title").get(0).text("Code de ramassage");
                Element email2_user = document.getElementById("email2_user");
                email2_user.text("Bonjour " + userInfo.getFirstName() + " " + userInfo.getLastName());
                Element email2_content = document.getElementById("email2_content");
                email2_content.text("Le code de ramassage de votre colis est " + random + ", veuillez effectuer la verification dans les 5 minutes.");
            }
            EmailUtil.send(userInfo.getEmail(), language == 1 ? "取件码邮件" : language == 2 ? "Pickup code" : "Code de ramassage",  document.html());
            //开始生成pdf收据和html收据
            File file = new File("/home/igotechgh/nginx/html/files/html/");
            if(!file.exists()){
                file.mkdirs();
            }
            file = new File("/home/igotechgh/nginx/html/files/html/code_" + orderId + ".html");
            if(!file.exists()){
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(document.html());
            fileWriter.flush();
            fileWriter.close();
            String link ="https://igo.i-go.group/files/html/code_" + orderId + ".html";
            TEmail tEmail = new TEmail();
            tEmail.setLink(link);
            tEmail.setUserId(userInfo.getId());
            tEmail.setType(1);
            tEmail.setName(language == 1 ? "取件码邮件" : language == 2 ? "Pickup code" : "Code de ramassage");
            tEmail.setOrderId(orderId);
            tEmail.setCreateTime(new Date());
            int i = cn.hutool.core.date.DateUtil.dayOfWeek(new Date())-1;
            String week = EmailUtil.getWeek(language, i);
            tEmail.setWeek(week);
            boolean am = cn.hutool.core.date.DateUtil.isAM(new Date());
            if(am){
                tEmail.setAmOrPm(language==1?"上午":language==2?"morning":"matin");
            }else {
                tEmail.setAmOrPm(language==1?"下午":language==2?"afternoon":"après-midi");
            }
            emailService.insert(tEmail);
        }
    }
    @Override
    public void payOrderLogisticsCallback(Integer id, String order_id, Integer language) throws Exception {
        OrderLogistics orderLogistics = this.selectById(id);
        PaymentRecord query = paymentRecordService.query(1, null, 2, Integer.valueOf(id), orderLogistics.getType(), null, 1);
        if(null != query){
            //添加交易明细
            transactionDetailsService.saveData(orderLogistics.getDriverId(), language == 1 ? "现金收款代付" : language == 2 ? "Cash collection on behalf of payment" : "Paiement en espèces", query.getAmount(), 2, 1, 2, orderLogistics.getType(), id);
            orderLogistics.setDriverPay(2);
            this.updateById(orderLogistics);
            query.setState(2);
            query.setCode(order_id);
            paymentRecordService.updateById(query);
        }else{
            System.err.println("预支付数据异常(orderId = "  + id + ")");
        }
    }
    /**
     * 处理乘客修改终点
     * @param orderId
     * @param status
     */
    @Override
    public void updateEndAddress(Integer orderId, Integer status) {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(ToolUtil.isEmpty(orderLogistics.getDestinationLon())){
            return;
        }
        if(2 == status){
            orderLogistics.setEndLon(Double.valueOf(orderLogistics.getDestinationLon()));
            orderLogistics.setEndLat(Double.valueOf(orderLogistics.getDestinationLat()));
            orderLogistics.setEndAddress(orderLogistics.getDestination());
            //修改google地图行程终点
            Car car = carService.selectById(orderLogistics.getCarId());
            boolean updateTrip = fleetEngineUtil.updateTrip(null, car.getVehicleId(), null, orderLogistics.getTripId(),
                    null, null, orderLogistics.getEndLat().toString(), orderLogistics.getEndLon().toString(), orderLogistics.getId(), 4);
            if(!updateTrip){
                for (int i = 0; i < 5; i++) {
                    updateTrip = fleetEngineUtil.updateTrip(null, car.getVehicleId(), null, orderLogistics.getTripId(),
                            null, null, orderLogistics.getEndLat().toString(), orderLogistics.getEndLon().toString(), orderLogistics.getId(), 4);
                    if(updateTrip){
                        break;
                    }
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        this.updateById(orderLogistics);
        pushUtil.pushModifyAddress(1, orderLogistics.getUserId(), orderId, 4, status);
    }
    /**
     * 获取费用明细
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryMoneyInfo(Integer orderId) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(orderLogistics.getState() == 6){//服务中的时候获取实时费用数据
            this.setMoney(orderLogistics, 0D, 0D);
            orderLogistics.setOrderMoney(orderLogistics.getOrderMoney() + orderLogistics.getPriceDifference());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderMoney", orderLogistics.getOrderMoney());//订单金额
        map.put("startMileage", orderLogistics.getStartMileage());//起步价
        map.put("startMoney", orderLogistics.getStartMoney());//起步价
        map.put("mileageKilometers", orderLogistics.getMileageKilometers());//里程费
        map.put("mileageMoney", orderLogistics.getMileageMoney());//里程费
        map.put("duration", orderLogistics.getDuration());//时长费
        map.put("durationMoney", orderLogistics.getDurationMoney());//时长费
        map.put("wait", orderLogistics.getWait());//等待费
        map.put("waitMoney", orderLogistics.getWaitMoney());//等待费
        map.put("longDistance", orderLogistics.getLongDistance());//远途费
        map.put("longDistanceMoney", orderLogistics.getLongDistanceMoney());//远途费
        map.put("parkMoney", orderLogistics.getParkMoney());//停车费
        map.put("roadTollMoney", orderLogistics.getRoadTollMoney());//过路费
        map.put("redPacketMoney", orderLogistics.getRedPacketMoney());//红包抵扣金额
        map.put("couponMoney", orderLogistics.getCouponMoney());//优惠券抵扣金额
        map.put("discountMoney", orderLogistics.getDiscountMoney());//折扣抵扣金额
        map.put("discount", orderLogistics.getDiscount());//折扣
        map.put("priceDifference", orderLogistics.getPriceDifference());//补差价
        map.put("isDispute", orderLogistics.getIsDispute());
        return map;
    }
    /**
     * 计算价格
     * @param orderLogistics
     * @param parkingFee
     * @param crossingFee
     * @return
     * @throws Exception
     */
    public OrderLogistics setMoney(OrderLogistics orderLogistics, Double parkingFee, Double crossingFee) throws Exception {
        Map<String, Object> query1 = systemPriceMapper.query(orderLogistics.getCompanyId(), 4, orderLogistics.getServerCarModelId());
        if(null == query1){
            throw new RuntimeException("请先添加计费规则");
        }
        //开始根据不同的方式计算金额
        double amount = 0;
        JSONObject jsonObject = JSON.parseObject(query1.get("content").toString());
        Double num1 = jsonObject.getDouble("num1");//起步价(元)
        Double num2 = jsonObject.getDouble("num2");//起步公里(公里)
        Double num3 = jsonObject.getDouble("num3");//起步时间(分钟)
        Double num4 = jsonObject.getDouble("num4");//里程费(元)
        Double num5 = jsonObject.getDouble("num5");//时长费(分钟)
        Double num6 = jsonObject.getDouble("num6");//等待费(分钟)
        Double num7 = jsonObject.getDouble("num7");//等待费(元)
        Double num8 = jsonObject.getDouble("num8");//远途费(公里)
        Double num9 = jsonObject.getDouble("num9");//远途费(公里)
        Double num10 = jsonObject.getDouble("num10");//远途费(元)
        Double num11 = jsonObject.getDouble("num11");//远途费(公里)
        Double num12 = jsonObject.getDouble("num12");//远途费(公里)
        Double num13 = jsonObject.getDouble("num13");//远途费(元)
        Double num14 = jsonObject.getDouble("num14");//远途费(公里)
        Double num15 = jsonObject.getDouble("num15");//远途费(元)
//        String num16 = jsonObject.getString("num16");//夜间费(开始时间)
//        Double num17 = jsonObject.getDouble("num17");//夜间费(元)
//        Double num18 = jsonObject.getDouble("num18");//夜间费(元)
//        Double num19 = jsonObject.getDouble("num19");//夜间费(元)
//        Double num20 = jsonObject.getDouble("num20");//夜间费(元)
//        Double num21 = jsonObject.getDouble("num21");//夜间费(元)
//        Double num22 = jsonObject.getDouble("num22");//夜间费(元)
        String num23 = jsonObject.getString("num23");//高峰费(开始时间)
        String num24 = jsonObject.getString("num24");//高峰费(开始时间)
        Double num25 = jsonObject.getDouble("num25");//高峰费(元)
        Double num26 = jsonObject.getDouble("num26");//高峰费(元)
        Double num27 = jsonObject.getDouble("num27");//高峰费(元)
        Double num28 = jsonObject.getDouble("num28");//高峰费(元)
        Double num29 = jsonObject.getDouble("num29");//高峰费(元)
        Double num30 = jsonObject.getDouble("num30");//高峰费(元)
        Date date = new Date();
        double d = (null == orderLogistics.getMileage() ? 0D : orderLogistics.getMileage()) / 1000;//实际公里
        double t = ((orderLogistics.getEndServiceTime().getTime() - orderLogistics.getStartServiceTime().getTime()) / 60000) + 1;//实际时间(不满一分钟按一分钟算)
        double w = ((orderLogistics.getStartServiceTime().getTime() - orderLogistics.getArriveTime().getTime()) / 60000) + 1;//等待分钟(不满一分钟按一分钟算)
        double d1 = (d - num2) < 0 ? 0 : d - num2;//超出起步里程的公里
        double t1 = (t - num3) < 0 ? 0 : new BigDecimal(t - num3).setScale(0, BigDecimal.ROUND_UP).doubleValue();//超过起步分钟数的时间
        double w1 = (w - num6) < 0 ? 0 : new BigDecimal(w - num6).setScale(0, BigDecimal.ROUND_UP).doubleValue();//超出等待时间的时间
        double yt1 = 0;//远途1段
        double yt2 = 0;//远途2段
        double yt3 = 0;//远途3段
        //夜间服务处理逻辑
//        if(ToolUtil.isNotEmpty(num16)){
//            Calendar s = Calendar.getInstance();
//            s.setTime(date);
//            s.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num16.split(" - ")[0].split(":")[0]));
//            s.set(Calendar.MINUTE, Integer.valueOf(num16.split(" - ")[0].split(":")[1]));
//
//            Calendar e = Calendar.getInstance();
//            e.setTime(date);
//            e.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num16.split(" - ")[1].split(":")[0]));
//            e.set(Calendar.MINUTE, Integer.valueOf(num16.split(" - ")[1].split(":")[1]));
//
//            if(date.getTime() > s.getTimeInMillis() && date.getTime() < e.getTimeInMillis()){
//                if(d > num8.doubleValue() && d <= num9.doubleValue()){
//                    yt1 = num20 * (d - num8);
//                }
//                if(d > num9.doubleValue()){
//                    yt1 = num20 * (num9 - num8);
//                }
//                if(d > num11.doubleValue() && d <= num12.doubleValue()){
//                    yt2 = num21 * (d - num11);
//                }
//                if(d > num12.doubleValue()){
//                    yt2 = num21 * (num12 - num11);
//                }
//                if(d > num14.doubleValue()){
//                    yt3 = num22 * (d - num14);
//                }
//                amount = num17 + (d1 * num18) + (t1 * num19) + (w1 * num7) + yt1 + yt2 + yt3;
//                orderLogistics.setStartMileage(num2);
//                orderLogistics.setStartMoney(num17);//起步价
//                orderLogistics.setStartDuration((int)(num3.doubleValue()));
//                orderLogistics.setMileageKilometers(new BigDecimal(d1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                orderLogistics.setMileageMoney(new BigDecimal(d1 * num18).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//里程费
//                orderLogistics.setDuration(new BigDecimal(t1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                orderLogistics.setDurationMoney(new BigDecimal(t1 * num19).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//时长费
//                orderLogistics.setWait(new BigDecimal(w1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                orderLogistics.setWaitMoney(new BigDecimal(w1 * num7).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//等待费
//                orderLogistics.setLongDistance(new BigDecimal((d > num8) ? d - num8 : 0).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                orderLogistics.setLongDistanceMoney(new BigDecimal(yt1 + yt2 + yt3).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//远途费
//                orderLogistics.setParkMoney(parkingFee);//停车费
//                orderLogistics.setRoadTollMoney(crossingFee);//过路费
//                orderLogistics.setRedPacketMoney(0D);//红包抵扣
//                orderLogistics.setCouponMoney(0D);//优惠券抵扣
//                orderLogistics.setDiscount(0D);//优惠抵扣
//                orderLogistics.setPayMoney(0D);//支付金额
//                orderLogistics.setOrderMoney(new BigDecimal(amount + parkingFee + crossingFee).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                orderLogistics.setMoneyType(2);
//                orderLogistics.setMoneyTime(num16);
//                return orderLogistics;
//            }
//        }
        //高峰时段处理逻辑
        Calendar s1 = Calendar.getInstance();
        s1.setTime(date);
        s1.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num23.split(" - ")[0].split(":")[0]));
        s1.set(Calendar.MINUTE, Integer.valueOf(num23.split(" - ")[0].split(":")[1]));
        Calendar e1 = Calendar.getInstance();
        e1.setTime(date);
        e1.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num23.split(" - ")[1].split(":")[0]));
        e1.set(Calendar.MINUTE, Integer.valueOf(num23.split(" - ")[1].split(":")[1]));
        Calendar s2 = Calendar.getInstance();
        s2.setTime(date);
        s2.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num24.split(" - ")[0].split(":")[0]));
        s2.set(Calendar.MINUTE, Integer.valueOf(num24.split(" - ")[0].split(":")[1]));
        Calendar e2 = Calendar.getInstance();
        e2.setTime(date);
        e2.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num24.split(" - ")[1].split(":")[0]));
        e2.set(Calendar.MINUTE, Integer.valueOf(num24.split(" - ")[1].split(":")[1]));
        if((date.getTime() > s1.getTimeInMillis() && date.getTime() < e1.getTimeInMillis()) || (date.getTime() > s2.getTimeInMillis() && date.getTime() < e2.getTimeInMillis())){
            if(d > num8.doubleValue() && d <= num9.doubleValue()){
                yt1 = num28 * (d - num8);
            }
            if(d > num9.doubleValue()){
                yt1 = num28 * (num9 - num8);
            }
            if(d > num11.doubleValue() && d <= num12.doubleValue()){
                yt2 = num29 * (d - num11);
            }
            if(d > num12.doubleValue()){
                yt2 = num29 * (num12 - num11);
            }
            if(d > num14.doubleValue()){
                yt3 = num30 * (d - num14);
            }
            amount = num25 + (d1 * num26) + (t1 * num27) + (w1 * num7) + yt1 + yt2 + yt3;
            orderLogistics.setStartMileage(num2);
            orderLogistics.setStartMoney(num25);//起步价
            orderLogistics.setStartDuration((int)(num3.doubleValue()));
            orderLogistics.setMileageKilometers(new BigDecimal(d1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
            orderLogistics.setMileageMoney(new BigDecimal(d1 * num26).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//里程费
            orderLogistics.setDuration(new BigDecimal(t1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
            orderLogistics.setDurationMoney(new BigDecimal(t1 * num27).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//时长费
            orderLogistics.setWait(new BigDecimal(w1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
            orderLogistics.setWaitMoney(new BigDecimal(w1 * num7).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//等待费
            orderLogistics.setLongDistance(new BigDecimal((d > num8) ? d - num8 : 0).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
            orderLogistics.setLongDistanceMoney(new BigDecimal(yt1 + yt2 + yt3).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//远途费
            orderLogistics.setParkMoney(parkingFee);//停车费
            orderLogistics.setRoadTollMoney(crossingFee);//过路费
            orderLogistics.setRedPacketMoney(0D);//红包抵扣
            orderLogistics.setCouponMoney(0D);//优惠券抵扣
            orderLogistics.setDiscount(0D);//优惠抵扣
            orderLogistics.setPayMoney(0D);//支付金额
            orderLogistics.setOrderMoney(new BigDecimal(amount + parkingFee + crossingFee).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
            return orderLogistics;
        }
        //其他时间段的计算
        if(d > num8.doubleValue() && d <= num9.doubleValue()){
            yt1 = num10 * (d - num8);
        }
        if(d > num9.doubleValue()){
            yt1 = num10 * (num9 - num8);
        }
        if(d > num11.doubleValue() && d <= num12.doubleValue()){
            yt2 = num13 * (d - num11);
        }
        if(d > num12.doubleValue()){
            yt2 = num13 * (num12 - num11);
        }
        if(d > num14.doubleValue()){
            yt3 = num15 * (d - num14);
        }
        amount = num1 + (d1 * num4) + (t1 * num5) + (w1 * num7) + yt1 + yt2 + yt3;
        orderLogistics.setStartMileage(num2);
        orderLogistics.setStartMoney(num1);//起步价
        orderLogistics.setStartDuration((int)(num3.doubleValue()));
        orderLogistics.setMileageKilometers(new BigDecimal(d1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        orderLogistics.setMileageMoney(new BigDecimal(d1 * num4).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//里程费
        orderLogistics.setDuration(new BigDecimal(t1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        orderLogistics.setDurationMoney(new BigDecimal(t1 * num5).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//时长费
        orderLogistics.setWait(new BigDecimal(w1).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        orderLogistics.setWaitMoney(new BigDecimal(w1 * num7).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//等待费
        orderLogistics.setLongDistance(new BigDecimal((d > num8) ? d - num8 : 0).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        orderLogistics.setLongDistanceMoney(new BigDecimal(yt1 + yt2 + yt3).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//远途费
        orderLogistics.setParkMoney(parkingFee);//停车费
        orderLogistics.setRoadTollMoney(crossingFee);//过路费
        orderLogistics.setRedPacketMoney(0D);//红包抵扣
        orderLogistics.setCouponMoney(0D);//优惠券抵扣
        orderLogistics.setDiscount(0D);//优惠抵扣
        orderLogistics.setPayMoney(0D);//支付金额
        orderLogistics.setOrderMoney(new BigDecimal(amount + parkingFee + crossingFee).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        return orderLogistics;
    }
    /**
     * 确认费用操作
     * @param orderId
     * @param type
     * @param parkingFee
     * @param crossingFee
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil confirmFees(Integer language, Integer orderId, Integer type, Double parkingFee, Double crossingFee, Integer uid) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(!uid.equals(orderLogistics.getDriverId())){
            return ResultUtil.error(language == 1 ? "操作失败,请刷新订单" : language == 2 ? "Operation failed, please refresh the order" : "L’opération a échoué, veuillez actualiser la commande");
        }
        if(6 != orderLogistics.getState()){
            return ResultUtil.error(language == 1 ? "操作失败,请刷新订单" : language == 2 ? "Operation failed, please refresh the order" : "L’opération a échoué, veuillez actualiser la commande");
        }
        if(orderLogistics.getArriveTime()==null){
            orderLogistics.setArriveTime(orderLogistics.getStartServiceTime());
        }
        orderLogistics = this.setMoney(orderLogistics, 0D, 0D);//计算费用
        orderLogistics.setPayManner(type);
        orderLogistics.setParkMoney(null == parkingFee ? 0D : parkingFee);
        orderLogistics.setRoadTollMoney(null == crossingFee ? 0D : crossingFee);
        orderLogistics.setOrderMoney(orderLogistics.getOrderMoney() + orderLogistics.getParkMoney() + orderLogistics.getRoadTollMoney() + orderLogistics.getPriceDifference());
        //判断是否首单免费-免费直接完成
        Integer orderNumber = this.selectCount(new EntityWrapper<OrderLogistics>().eq("userId",orderLogistics.getUserId()).last("and (state=8 or state=9)"));
        if(orderNumber<=0){//判断是否是首单
            //判断是否免单
            UserInfo userInfo = userInfoMapper.selectById(orderLogistics.getUserId());
            if(userInfo.getFreeMoney().doubleValue()>0d){
                if(orderLogistics.getOrderMoney()<=userInfo.getFreeMoney().doubleValue()){
                    orderLogistics.setState(8);
                    //添加已收入明细
                    Company company = companyService.selectById(orderLogistics.getCompanyId());
                    Double speMoney = company.getSpeMoney();
                    BigDecimal d = null;//企业收入
                    BigDecimal c = null;//司机收入
                    if(company.getIsSpeFixedOrProportional() == 2){//固定
                        d = new BigDecimal(speMoney);
                        c = new BigDecimal(orderLogistics.getOrderMoney()).subtract(d);//只有出行金额参与抽成,其余归属司机
                    }
                    if(company.getIsSpeFixedOrProportional() == 1){//比例
                        Double price = orderLogistics.getStartMoney() + orderLogistics.getMileageMoney() + orderLogistics.getWaitMoney() + orderLogistics.getDurationMoney() + orderLogistics.getLongDistanceMoney();
                        d = new BigDecimal(price).multiply(new BigDecimal(speMoney).divide(new BigDecimal(100), new MathContext(2, RoundingMode.HALF_EVEN)));
                        c = new BigDecimal(orderLogistics.getOrderMoney()).subtract(d).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                    }
                    incomeService.saveData(1, orderLogistics.getCompanyId(), 2, orderLogistics.getId(), 4, d.doubleValue());
                    incomeService.saveData(2, orderLogistics.getDriverId(), 2, orderLogistics.getId(), 4, c.doubleValue());
                    Driver driver = driverService.selectById(orderLogistics.getDriverId());
                    driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                    driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                    driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                    driverService.updateById(driver);
                }else{
                    orderLogistics.setState(7);
                    orderLogistics.setOrderMoney(orderLogistics.getOrderMoney()-userInfo.getFreeMoney().doubleValue());
                    orderLogistics.setFreeMoney(userInfo.getFreeMoney());
                }
            }else{
                orderLogistics.setState(7);
            }
        }else{
            orderLogistics.setState(7);
        }
        Map<String, String> map = chinaMobileUtil.midAxbUnBindSend(orderLogistics.getBindId(),orderLogistics.getTelX());
        if(String.valueOf(map.get("code")).equals("200")){
            orderLogistics.setTelX("");
            orderLogistics.setBindId("");
        }
        this.updateById(orderLogistics);
        //修改行程数据
        Car car = carService.selectById(orderLogistics.getCarId());
        boolean updateTrip = fleetEngineUtil.updateTrip("COMPLETE", car.getVehicleId(), null, orderLogistics.getTripId(), null, null, null, null, orderLogistics.getId(), 4);
        if(!updateTrip){
            for (int i = 0; i < 5; i++) {
                updateTrip = fleetEngineUtil.updateTrip("COMPLETE", car.getVehicleId(), null, orderLogistics.getTripId(), null, null, null, null, orderLogistics.getId(), 4);
                if(updateTrip){
                    orderLogistics.setIsover(1);
                    this.updateById(orderLogistics);
                    break;
                }
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else{
            orderLogistics.setIsover(1);
            this.updateById(orderLogistics);
        }
        //上报行程
        boolean reportBillableEvent = fleetEngineUtil.reportBillableEvent(orderLogistics.getTripId());
        if(!reportBillableEvent){
            for (int i = 0; i < 5; i++) {
                reportBillableEvent = fleetEngineUtil.reportBillableEvent(orderLogistics.getTripId());
                if(reportBillableEvent){
                    break;
                }
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        pushUtil.removeTask(orderId, 4);//删除定时任务,结束推送数据
        UserInfo userInfo = userInfoMapper.selectById(orderLogistics.getUserId());
        Integer language1 = userInfo.getLanguage();
        systemNoticeService.addSystemNotice(1, language1 == 1 ? "司机已结束本次行程,谢谢使用" : language1 == 2 ?
                "The driver has finished the trip,thank you for using I-GO" : "Le chauffeur a terminé le trajet, merci d'utiliser I-GO", orderLogistics.getUserId());
        //回滚司机状态为空闲
        Driver driver = driverService.selectById(orderLogistics.getDriverId());
        driver.setState(2);
        driverService.updateById(driver);
        OrderLogistics finalOrderTaxi = orderLogistics;
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushOrderState(1, finalOrderTaxi.getUserId(), finalOrderTaxi.getId(), 4, finalOrderTaxi.getState(), 0, "", "driver");
                pushUtil.pushOrderState(2, finalOrderTaxi.getDriverId(), finalOrderTaxi.getId(), 4, finalOrderTaxi.getState(), 0, "", "driver");
            }
        }).start();
        return ResultUtil.success();
    }
    /**
     * 计算已服务的实时里程
     * @param orderId
     * @param lon
     * @param lat
     */
    @Override
    public boolean calculateMileage(Integer orderId, String lon, String lat) throws Exception {
        OrderLogistics orderLogistics = this.selectById(orderId);
        if(orderLogistics.getState() == 2){
            return false;
        }
        OrderPosition orderPosition = orderPositionService.queryNew(orderId, 4);
        String now = lon + "," + lat;
        String old = null;
        if(null != orderPosition){
            old = orderPosition.getLon() + "," + orderPosition.getLat();
        }else{
            orderLogistics.setToStartPointMileage(0D);
            orderLogistics.setMileage(0D);
            this.updateById(orderLogistics);
            return true;//第一条数据不作处理,直接存储
        }
        Map<String, Double> distance = GeodesyUtil.getDistance(now, old);
        if(null != distance){
            Double distance1 = distance.get("WGS84");
            if(distance1 > 30 &&  Arrays.asList(3, 4).contains(orderLogistics.getState())){//大于50米表示在移动
                orderLogistics.setToStartPointMileage(new BigDecimal(orderLogistics.getToStartPointMileage()).add(new BigDecimal(distance1)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                this.updateById(orderLogistics);
                return true;
            }
            if(distance1 > 30 && orderLogistics.getState()==5){//大于50米表示在移动
                orderLogistics.setMileage(new BigDecimal(orderLogistics.getMileage()).add(new BigDecimal(distance1)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                this.updateById(orderLogistics);
                return true;
            }
            return false;
        }else{
            System.err.println("调用高德计算距离出错");
        }
        return false;
    }
}