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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.service.UserVipService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.creditRecord.service.CreditRecordService;
import com.sqx.modules.driver.entity.Driver;
import com.sqx.modules.driver.entity.DriverRoute;
import com.sqx.modules.driver.service.DriverRouteService;
import com.sqx.modules.driver.service.DriverService;
import com.sqx.modules.fixedStroke.entity.FixedStroke;
import com.sqx.modules.fixedStroke.service.FixedStrokeService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.orders.service.PriceRuleService;
import com.sqx.modules.orders.utils.LocationUtils;
import com.sqx.modules.orders.vo.CalculatePrice;
import com.sqx.modules.orders.vo.TxDirection;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.utils.BaiduUtils;
import com.sqx.modules.utils.SenInfoCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

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

    @Autowired
    private PriceRuleService priceRuleService;
    @Autowired
    private TbCouponUserService couponUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverRouteService driverRouteService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private WxService wxService;
    @Autowired
    private PayDetailsService payDetailsService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private CreditRecordService creditRecordService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private BaiduUtils baiduUtils;
    @Autowired
    private FixedStrokeService fixedStrokeService;
    private ExecutorService newCachedThreadPool = new ThreadPoolExecutor(30, 100, 0L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());
    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);


    @Override
    public Result insertOrders(Orders orders){
        TbCouponUser tbCouponUser = null;
        if(orders.getCouponId()!=null){
            tbCouponUser = couponUserService.getById(orders.getCouponId());
            if(tbCouponUser==null || tbCouponUser.getStatus()!=0){
                return Result.error("优惠券失效");
            }
        }
        CalculatePrice ordersPrice = priceRuleService.getOrdersPrice(orders);
        if(tbCouponUser!=null){
            if(ordersPrice.getSumMoney().doubleValue()<tbCouponUser.getMinMoney().doubleValue()){
                return Result.error("优惠券不满足最低使用金额");
            }
            tbCouponUser.setStatus(1);
            couponUserService.updateById(tbCouponUser);
            orders.setCouponName(tbCouponUser.getCouponName());
        }
        orders.setPayMoney(ordersPrice.getPayMoney());
        orders.setSumMoney(ordersPrice.getSumMoney());
        orders.setDriveMoney(ordersPrice.getDriveMoney());

        orders.setCouponMoney(ordersPrice.getCouponMoney());
        orders.setDistance(ordersPrice.getDistance());
        orders.setKmDistance(ordersPrice.getKmDistance());

        orders.setOrdersNo(getGeneralOrder());
        String isPrice = commonInfoService.findOne(633).getValue();
        if("是".equals(isPrice)){
            orders.setStatus(1);
        }else{
            orders.setStatus(2);
            orders.setPayWay(6);
            newCachedThreadPool.submit(() -> {
                sendOrdersMessage(orders);
            });
        }
        orders.setCreateTime(DateUtils.format(new Date()));
        baseMapper.insert(orders);
        return Result.success().put("data",orders);
    }

    @Override
    public Result insertOrdersFixedStroke(Orders orders){
        TbCouponUser tbCouponUser = null;
        if(orders.getCouponId()!=null){
            tbCouponUser = couponUserService.getById(orders.getCouponId());
            if(tbCouponUser==null || tbCouponUser.getStatus()!=0){
                return Result.error("优惠券失效");
            }
        }

        FixedStroke fixedStroke = fixedStrokeService.getById(orders.getFixedStrokeId());
        orders.setUserId(orders.getUserId());
        orders.setShipProvince(fixedStroke.getShipProvince());
        orders.setShipCity(fixedStroke.getShipCity());
        orders.setShipDistrict(fixedStroke.getShipDistrict());
        orders.setShipAddress(fixedStroke.getShipAddress());
        orders.setShipAddressLatitude(fixedStroke.getShipAddressLatitude());
        orders.setShipAddressLongitude(fixedStroke.getShipAddressLongitude());
        orders.setDeliveryProvince(fixedStroke.getDeliveryProvince());
        orders.setDeliveryCity(fixedStroke.getDeliveryCity());
        orders.setDeliveryDistrict(fixedStroke.getDeliveryDistrict());
        orders.setDeliveryAddress(fixedStroke.getDeliveryAddress());
        orders.setDeliveryAddressLatitude(fixedStroke.getDeliveryAddressLatitude());
        orders.setDeliveryAddressLongitude(fixedStroke.getDeliveryAddressLongitude());

        BigDecimal payMoney = fixedStroke.getPayMoney().multiply(BigDecimal.valueOf(orders.getAppointmentNum()));

        if(tbCouponUser!=null){
            if(payMoney.doubleValue()<tbCouponUser.getMinMoney().doubleValue()){
                return Result.error("优惠券不满足最低使用金额");
            }
            tbCouponUser.setStatus(1);
            couponUserService.updateById(tbCouponUser);
            orders.setCouponName(tbCouponUser.getCouponName());
            orders.setCouponMoney(tbCouponUser.getMoney());
            payMoney=payMoney.subtract(orders.getCouponMoney());
        }
        orders.setPayMoney(payMoney);
        orders.setSumMoney(payMoney);
        orders.setDriveMoney(payMoney);
        orders.setIsFixedStroke(1);
        TxDirection txDirection = priceRuleService.getDistance(orders.getShipAddressLatitude(), orders.getShipAddressLongitude(),
                orders.getDeliveryAddressLatitude(), orders.getDeliveryAddressLongitude());
        BigDecimal distance = txDirection.getDistance().divide(new BigDecimal("1000"), 2, RoundingMode.FLOOR);
        orders.setDistance(txDirection.getDistance());
        orders.setKmDistance(distance);

        orders.setOrdersNo(getGeneralOrder());
        String isPrice = commonInfoService.findOne(633).getValue();
        if("是".equals(isPrice)){
            orders.setStatus(1);
        }else{
            orders.setStatus(2);
            orders.setPayWay(6);
            newCachedThreadPool.submit(() -> {
                sendOrdersMessage(orders);
            });
        }
        orders.setCreateTime(DateUtils.format(new Date()));
        baseMapper.insert(orders);
        return Result.success().put("data",orders);
    }


    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 payOrders(Long ordersId){
        Orders orders = baseMapper.selectById(ordersId);
        if(orders.getStatus()!=1){
            return Result.error("订单状态异常，刷新后重试！");
        }
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
        if(userMoney.getMoney().doubleValue()<orders.getPayMoney().doubleValue()){
            return Result.error("账户余额不足！");
        }
        userMoneyService.updateMoney(2,orders.getUserId(),orders.getPayMoney().doubleValue());
        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        userMoneyDetails.setTitle("支付订单："+orders.getOrdersNo());
        userMoneyDetails.setContent("余额支付："+orders.getPayMoney());
        userMoneyDetails.setUserType(1);
        userMoneyDetails.setUserId(orders.getUserId());
        userMoneyDetails.setMoney(orders.getPayMoney());
        userMoneyDetails.setType(2);
        userMoneyDetails.setClassify(7);
        userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);
        orders.setStatus(2);
        orders.setPayWay(5);
        orders.setPayTime(DateUtils.format(new Date()));
        baseMapper.updateById(orders);
        newCachedThreadPool.submit(() -> {
            sendOrdersMessage(orders);
        });

        return Result.success();
    }

    @Override
    public void sendOrdersMessage(Orders orders){
        try {
            String isPrice = commonInfoService.findOne(633).getValue();
            BigDecimal driverMoneys=BigDecimal.ZERO;

            String rate = commonInfoService.findOne(129).getValue();
            BigDecimal driverRate = new BigDecimal(rate);

            if("是".equals(isPrice)){
                driverMoneys=orders.getSumMoney().multiply(driverRate).setScale(2,BigDecimal.ROUND_DOWN);
            }else{
                driverMoneys=orders.getPayMoney();
            }

            String manPer = commonInfoService.findOne(815).getValue();
            String girlPer = commonInfoService.findOne(816).getValue();


            UserEntity userEntity = userService.selectUserById(orders.getUserId());
            if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                String templateId = commonInfoService.findOne(427).getValue();
                List<String> msgList=new ArrayList<>();
                msgList.add(0,orders.getOrdersNo());
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                msgList.add(1,title);
                msgList.add(2,"待接单");
                msgList.add(3,DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,msgList,1);
            }
            if(StringUtils.isNotEmpty(userEntity.getAccountOpenId())){
                String templateId = commonInfoService.findOne(437).getValue();
                List<String> msgList=new ArrayList<>();
                msgList.add(0,orders.getOrdersNo());
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                msgList.add(1,title);
                msgList.add(2,String.valueOf(orders.getPayMoney()));
                msgList.add(3,DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsgGZH(userEntity.getAccountOpenId(),templateId,msgList,2);
            }
            if(StringUtils.isNotEmpty(userEntity.getClientid())){
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                userService.pushToSingle(title,"订单金额："+orders.getPayMoney(),userEntity.getClientid());
            }
            String girlContent=null;
            String manContent=null;
            List<Driver> driverList = driverService.list(new QueryWrapper<Driver>().eq("status", 2)
                    .eq("is_listening_orders", 1).eq("city",orders.getShipCity()));
            for (Driver driver:driverList){
                //先判断是同城还是非同城
                boolean flag=false;
                if(driver.getIsCityOrders()!=null && driver.getIsCityOrders()==1){
                    if(driver.getCity().equals(orders.getShipCity()) && driver.getCity().equals(orders.getDeliveryCity())){
                        flag=true;
                    }
                }
                if(!flag && driver.getIsProvinceOrders()!=null && driver.getIsProvinceOrders()==1){
                    if(!orders.getShipCity().equals(orders.getDeliveryCity())){
                        flag=true;
                    }
                }
                if(flag){
                    //判断提供座位数 和订单座位数相匹配
                    if(driver.getSeatNum()>=orders.getAppointmentNum()){
                        //听单类型 1不限 2拼座 3独享
                        if(driver.getOrdersType()==1 || (driver.getOrdersType()==2 && orders.getAppointmentType()==2)
                                || (driver.getOrdersType()==3 && orders.getAppointmentType()==1)){
                            flag=false;
                            String appointmentStartTime = orders.getAppointmentStartTime();
                            String appointmentEndTime = orders.getAppointmentEndTime();
                            Calendar calendar=Calendar.getInstance();
                            int year = calendar.get(Calendar.YEAR);
                            String specifiedTime1 = year+"年"+appointmentStartTime;
                            String currentTime1 = DateUtils.format(new Date());
                            String s = convertTime(specifiedTime1, currentTime1);

                            String specifiedTime2 = year+"年"+appointmentEndTime;
                            String s1 = convertTime(specifiedTime2, currentTime1);

                            Date date1 = DateUtils.stringToDate(s,DateUtils.DATE_TIME_PATTERN);
                            Date date2 = new Date();
                            Date date3 = DateUtils.stringToDate(s1,DateUtils.DATE_TIME_PATTERN);

                            long differenceInMillis1 = Math.abs(date2.getTime() - date1.getTime());
                            long differenceInMillis2 = Math.abs(date2.getTime() - date3.getTime());
                            long startNum=differenceInMillis1 / (1000 * 60);
                            long endNum=differenceInMillis2 / (1000 * 60);

                            if(driver.getOrdersStartTime().contains("15")){
                                if(startNum<=15 || endNum<=15){
                                    flag=true;
                                }
                            }else if(driver.getOrdersStartTime().contains("30")){
                                if(startNum<=30 || endNum<=30){
                                    flag=true;
                                }
                            }else if(driver.getOrdersStartTime().contains("60")){
                                if(startNum<=60 || endNum<=60){
                                    flag=true;
                                }
                            }else{
                                flag=true;
                            }
                            if(flag){
                                flag=false;
                                //距离
                                //判断当前用户是否有行程
                                List<DriverRoute> driverRouteList = driverRouteService.list(new QueryWrapper<DriverRoute>().eq("driver_id", driver.getDriverId()));
                                if(!driverRouteList.isEmpty()){
                                    for(DriverRoute driverRoute:driverRouteList){

                                        double[] start1 = {Double.parseDouble(driverRoute.getShipAddressLatitude()), Double.parseDouble(driverRoute.getShipAddressLongitude())};
                                        double[] start2 = {Double.parseDouble(orders.getShipAddressLatitude()), Double.parseDouble(orders.getShipAddressLongitude())};
                                        Double startDistance = LocationUtils.calculateDistanceUsingHaversine(start1, start2);

                                        if(driver.getOrdersKm().doubleValue()>=startDistance.doubleValue()){
                                            flag=true;
                                            break;
                                        }
                                    }
                                }else{
                                    double[] start1 = {Double.parseDouble(driver.getLatitude()), Double.parseDouble(driver.getLongitude())};
                                    double[] start2 = {Double.parseDouble(orders.getShipAddressLatitude()), Double.parseDouble(orders.getShipAddressLongitude())};
                                    Double startDistance = LocationUtils.calculateDistanceUsingHaversine(start1, start2);

                                    if(driver.getOrdersKm().doubleValue()>=startDistance){
                                        flag=true;
                                    }
                                }
                                if(flag){
                                    //播报语音

                                    MessageInfo messageInfo=new MessageInfo();
                                    if(driver.getMusicType()==null || driver.getMusicType()==2){
                                        if(StringUtils.isEmpty(girlContent)){
                                            girlContent=baiduUtils.exportMusic("新订单,"+orders.getAppointmentStartTime()+"出发，从"+orders.getShipCity()+orders.getShipAddress()+
                                                    "到"+orders.getDeliveryCity()+orders.getDeliveryAddress()+"，全程："+orders.getKmDistance()+"公里，预估"+driverMoneys+"元",girlPer);
                                        }
                                        messageInfo.setContent(girlContent);
                                    }else{
                                        if(StringUtils.isEmpty(manContent)){
                                            manContent=baiduUtils.exportMusic("新订单,"+orders.getAppointmentStartTime()+"出发，从"+orders.getShipCity()+orders.getShipAddress()+
                                                    "到"+orders.getDeliveryCity()+orders.getDeliveryAddress()+"，全程："+orders.getKmDistance()+"公里，预估"+driverMoneys+"元",manPer);
                                        }
                                        messageInfo.setContent(manContent);
                                    }

                                    messageInfo.setIsSee("0");
                                    messageInfo.setState("13");
                                    messageInfo.setUserId(String.valueOf(driver.getUserId()));
                                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                                    messageService.save(messageInfo);
                                }
                            }
                        }
                    }
                }
            }


            //获取出发地一样的师傅
            List<DriverRoute> driverRouteList = driverRouteService.list(new QueryWrapper<DriverRoute>().eq("ship_city", orders.getShipCity()));
            for (DriverRoute driverRoute:driverRouteList){
                UserEntity driverEntity = userService.selectUserById(driverRoute.getUserId());
                if(StringUtils.isNotEmpty(driverEntity.getRiderOpenId())){
                    String templateId = commonInfoService.findOne(428).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    BigDecimal driverMoney = orders.getSumMoney().multiply(new BigDecimal(driverEntity.getRate())).setScale(2, BigDecimal.ROUND_DOWN);
                    msgList.add(2,String.valueOf(driverMoney));
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendRiderMsg(driverEntity.getRiderOpenId(),templateId,msgList,3);
                }
                if(StringUtils.isNotEmpty(driverEntity.getRiderAccountOpenId())){
                    String templateId = commonInfoService.findOne(432).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    BigDecimal driverMoney = orders.getSumMoney().multiply(new BigDecimal(driverEntity.getRate())).setScale(2, BigDecimal.ROUND_DOWN);
                    msgList.add(2,String.valueOf(driverMoney));
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendRiderMsgGZH(driverEntity.getRiderAccountOpenId(),templateId,msgList,1);
                }
                if(StringUtils.isNotEmpty(driverEntity.getClientRiderId())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    BigDecimal driverMoney = orders.getSumMoney().multiply(new BigDecimal(driverEntity.getRate())).setScale(2, BigDecimal.ROUND_DOWN);
                    userService.pushToSingleQiShou(title,"订单金额："+driverMoney,driverEntity.getClientRiderId());
                }
                MessageInfo messageInfo=new MessageInfo();
                messageInfo.setTitle("新订单通知");
                messageInfo.setState("7");
                messageInfo.setIsSee("0");
                messageInfo.setUserId(String.valueOf(driverEntity.getUserId()));
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageService.save(messageInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("语音出错："+e.getMessage(),e);
        }

    }

    public static void main(String[] args) {
        String appointmentStartTime = "11月25日16:30";
        String appointmentEndTime = "11月25日17:30";
        Calendar calendar=Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String specifiedTime1 = year+"年"+appointmentStartTime;
        String currentTime1 = DateUtils.format(new Date());
        String s = convertTime(specifiedTime1, currentTime1);

        String specifiedTime2 = year+"年"+appointmentEndTime;
        String s1 = convertTime(specifiedTime2, currentTime1);

        Date date1 = DateUtils.stringToDate(s,DateUtils.DATE_TIME_PATTERN);
        Date date2 = new Date();
        Date date3 = DateUtils.stringToDate(s1,DateUtils.DATE_TIME_PATTERN);

        long differenceInMillis1 = Math.abs(date2.getTime() - date1.getTime());
        long differenceInMillis2 = Math.abs(date2.getTime() - date3.getTime());
        long startNum=differenceInMillis1 / (1000 * 60);
        long endNum=differenceInMillis2 / (1000 * 60);
        boolean flag=false;
        if(startNum<=15 || endNum<=15){
            flag=true;
        }
        /*if("15".contains(driver.getOrdersStartTime())){
            if(startNum<=15 || endNum<=15){
                flag=true;
            }
        }else if("30".contains(driver.getOrdersStartTime())){
            if(startNum<=30 || endNum<=30){
                flag=true;
            }
        }else if("60".contains(driver.getOrdersStartTime())){
            if(startNum<=60 || endNum<=60){
                flag=true;
            }
        }else{
            flag=true;
        }*/
        System.out.println(flag);
    }


    public static String convertTime(String specifiedTime, String currentTime) {
        try {
            // 先将输入的指定时间格式化为可解析的格式
            SimpleDateFormat inputSdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
            Date specifiedDate = inputSdf.parse(specifiedTime);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currentDate = sdf.parse(currentTime);

            // 判断指定时间是否在当前时间之后，如果是，则年份需要加1
            if (!specifiedDate.after(currentDate)) {
                // 使用Calendar类来处理时间的调整
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(specifiedDate);
                calendar.add(Calendar.YEAR, 1);
                Date newDate = calendar.getTime();

                SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return outputSdf.format(newDate);
            } else {
                SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return outputSdf.format(specifiedDate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public Result selectOrdersDetails(Long ordersId,Long driverUserId,Long driverRouteId){
        Orders orders = baseMapper.selectById(ordersId);
        if(orders==null){
            return Result.error("订单已取消！");
        }
        if(orders.getDriverId()!=null){
            Driver driver = driverService.getById(orders.getDriverId());
            if(driver!=null){
                UserEntity userEntity = userService.selectUserById(driver.getUserId());
                if(userEntity!=null){
                    driver.setPhone(userEntity.getPhone());
                }
                orders.setOrdersCount(baseMapper.selectCount(new QueryWrapper<Orders>().eq("driver_id",driver.getDriverId()).eq("status",5)));
            }
            orders.setDriver(driver);
        }
        String isPrice = commonInfoService.findOne(633).getValue();
        if(driverUserId!=null){
            UserEntity userEntity = userService.selectUserById(driverUserId);
            if("是".equals(isPrice)){
                orders.setDriveMoney(orders.getSumMoney().multiply(new BigDecimal(userEntity.getRate())).setScale(2,BigDecimal.ROUND_DOWN));
            }else{
                orders.setDriveMoney(orders.getPayMoney());
            }
            int count = messageService.count(new QueryWrapper<MessageInfo>().eq("state", 10)
                    .eq("user_id", driverRouteId).eq("platform", ordersId));
            if(count==0){
                MessageInfo messageInfo=new MessageInfo();
                messageInfo.setState("11");
                messageInfo.setPlatform(String.valueOf(ordersId));
                messageInfo.setUserId(String.valueOf(driverUserId));
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageService.save(messageInfo);
            }
        }
        if(driverRouteId!=null){
            DriverRoute driverRoute = driverRouteService.getById(driverRouteId);
            double[] start1 = {Double.parseDouble(driverRoute.getShipAddressLatitude()), Double.parseDouble(driverRoute.getShipAddressLongitude())};
            double[] end1 = {Double.parseDouble(driverRoute.getDeliveryAddressLatitude()), Double.parseDouble(driverRoute.getDeliveryAddressLongitude())};
            double[] start2 = {Double.parseDouble(orders.getShipAddressLatitude()), Double.parseDouble(orders.getShipAddressLongitude())};
            double[] end2 = {Double.parseDouble(orders.getDeliveryAddressLatitude()), Double.parseDouble(orders.getDeliveryAddressLongitude())};
            BigDecimal similarity = LocationUtils.calculateRouteSimilarity(start1, end1, start2, end2);
            orders.setSimilarity(similarity.setScale(0,BigDecimal.ROUND_DOWN));

            Double startDistance = LocationUtils.calculateDistanceUsingHaversine(start1, start2);
            Double endDistance = LocationUtils.calculateDistanceUsingHaversine(end1, end2);

            orders.setStartDistance(BigDecimal.valueOf(startDistance).setScale(2,BigDecimal.ROUND_DOWN));
            orders.setEndDistance(BigDecimal.valueOf(endDistance).setScale(2,BigDecimal.ROUND_DOWN));
        }
        if(orders.getDriverRouteId()!=null){
            DriverRoute driverRoute = driverRouteService.getById(orders.getDriverRouteId());
            orders.setDriverRoute(driverRoute);
        }
        return Result.success().put("data",orders);
    }

    @Override
    public Result selectOrdersList(Integer page,Integer limit,Integer appointmentType,Integer appointmentNum,Integer status,String shipProvince,
                                   String shipCity,String shipDistrict,String shipAddress,String deliveryProvince,String deliveryCity,
                                   String deliveryDistrict,String deliveryAddress,String userName,String phone,String shipUserName,String shipUserPhone,
                                   String driverName,String driverPhone,Integer sort,Long driverRouteId,String longitude,String latitude,
                                   Long driverId,String ordersNo,Integer orderType,Long driverUserId,Long driverRouteIds,Integer isFixedStroke){
        IPage<Orders> ordersIPage = baseMapper.selectOrdersList(new Page<>(page, limit), appointmentType, appointmentNum,
                status, shipProvince, shipCity, shipDistrict, shipAddress, deliveryProvince, deliveryCity, deliveryDistrict, deliveryAddress,
                userName, phone, shipUserName, shipUserPhone, driverName, driverPhone, sort,longitude,latitude,driverId,ordersNo,orderType,
                driverUserId,driverRouteIds,isFixedStroke);
        String isPrice = commonInfoService.findOne(633).getValue();
        DriverRoute driverRoute = null;
        if(driverRouteId!=null) {
            driverRoute = driverRouteService.getById(driverRouteId);
        }
        UserEntity driverUserEntity = null;
        if(driverUserId!=null){
            driverUserEntity = userService.selectUserById(driverUserId);
        }
        for(Orders orders:ordersIPage.getRecords()){
            if(driverRoute!=null){
                double[] start1 = {Double.parseDouble(driverRoute.getShipAddressLatitude()), Double.parseDouble(driverRoute.getShipAddressLongitude())};
                double[] end1 = {Double.parseDouble(driverRoute.getDeliveryAddressLatitude()), Double.parseDouble(driverRoute.getDeliveryAddressLongitude())};
                double[] start2 = {Double.parseDouble(orders.getShipAddressLatitude()), Double.parseDouble(orders.getShipAddressLongitude())};
                double[] end2 = {Double.parseDouble(orders.getDeliveryAddressLatitude()), Double.parseDouble(orders.getDeliveryAddressLongitude())};
                BigDecimal similarity = LocationUtils.calculateRouteSimilarity(start1, end1, start2, end2);
                orders.setSimilarity(similarity.setScale(0,BigDecimal.ROUND_DOWN));
                Double startDistance = LocationUtils.calculateDistanceUsingHaversine(start1, start2);
                Double endDistance = LocationUtils.calculateDistanceUsingHaversine(end1, end2);
                orders.setStartDistance(BigDecimal.valueOf(startDistance).setScale(2,BigDecimal.ROUND_DOWN));
                orders.setEndDistance(BigDecimal.valueOf(endDistance).setScale(2,BigDecimal.ROUND_DOWN));
            }
            if(driverUserEntity!=null){
                if("是".equals(isPrice)){
                    orders.setDriveMoney(orders.getSumMoney().multiply(new BigDecimal(driverUserEntity.getRate())).setScale(2,BigDecimal.ROUND_DOWN));
                }else{
                    orders.setDriveMoney(orders.getPayMoney());
                }
            }
        }
        return Result.success().put("data",new PageUtils(ordersIPage));
    }

    @Override
    public Result takingOrders(Long ordersId,Long userId,Integer admin,Long driverRouteId){
        reentrantReadWriteLock.writeLock().lock();
        try {
            String isVip = commonInfoService.findOne(632).getValue();
            if("是".equals(isVip)){
                UserVip userVip = userVipService.selectUserVipByUserId(userId);
                if(userVip==null || userVip.getIsVip()==2){
                    return Result.error("请开通会员后接单！");
                }
            }

            Orders orders = baseMapper.selectById(ordersId);
            if(admin==null && orders.getStatus()!=2){
                return Result.error("状态异常，请刷新后重试！");
            }
            orders.setDriverRouteId(driverRouteId);

            UserEntity driverUser = userService.selectUserById(userId);
            String isCashDeposit = commonInfoService.findOne(634).getValue();
            if("是".equals(isCashDeposit)){
                if(driverUser.getCashDeposit()==null || driverUser.getCashDeposit().doubleValue()<=0){
                    return Result.error("请缴纳保证金后接单！");
                }
            }

            int minScore = Integer.parseInt(commonInfoService.findOne(365).getValue());
            if (driverUser.getCreditScore() < minScore) {
                return Result.error("信用分不足无法下单,请联系平台客服");
            }
            Driver driver = driverService.selectDriverByUserId(userId);
            orders.setDriverUserId(driver.getUserId());
            orders.setStatus(3);
            orders.setDriverId(driver.getDriverId());
            orders.setTakingTime(DateUtils.format(new Date()));

            BigDecimal driverMoney = orders.getSumMoney().multiply(new BigDecimal(driverUser.getRate())).setScale(2,BigDecimal.ROUND_DOWN);
            orders.setDriveMoney(driverMoney);
            BigDecimal pingMoney=orders.getPayMoney().subtract(orders.getDriveMoney());

            BigDecimal oneUserMoney = BigDecimal.ZERO;
            BigDecimal twoUserMoney = BigDecimal.ZERO;
            if(pingMoney.doubleValue()>0){
                //计算一级收益
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                UserEntity oneUser = userService.queryByInvitationCode(userEntity.getInviterCode());
                if(oneUser!=null){
                    if (StringUtils.isNotEmpty(oneUser.getDivideScale())) {
                        oneUserMoney = pingMoney.multiply(new BigDecimal(oneUser.getDivideScale()));
                    }
                    orders.setOneUserId(oneUser.getUserId());
                    orders.setOneUserMoney(oneUserMoney);

                    //计算二级收益
                    UserEntity twoUser = userService.queryByInvitationCode(oneUser.getInviterCode());
                    if(twoUser!=null){
                        if (StringUtils.isNotEmpty(twoUser.getDivideTwoScale())) {
                            twoUserMoney = pingMoney.multiply(new BigDecimal(twoUser.getDivideTwoScale()));
                        }
                        orders.setTwoUserId(twoUser.getUserId());
                        orders.setTwoUserMoney(twoUserMoney);
                    }
                }
            }


            BigDecimal oneMoney = BigDecimal.ZERO;
            BigDecimal twoMoney = BigDecimal.ZERO;

            if(pingMoney.doubleValue()>0){
                //计算一级收益
                UserEntity userEntity = userService.selectUserById(driver.getUserId());
                UserEntity oneUser = userService.queryByInvitationCode(userEntity.getInviterCode());
                if(oneUser!=null){
                    if (StringUtils.isNotEmpty(oneUser.getDivideScale())) {
                        oneMoney = pingMoney.multiply(new BigDecimal(oneUser.getDivideScale()));
                    }
                    orders.setOneDriverUserId(oneUser.getUserId());
                    orders.setOneDriverUserMoney(oneMoney);

                    //计算二级收益
                    UserEntity twoUser = userService.queryByInvitationCode(oneUser.getInviterCode());
                    if(twoUser!=null){
                        if (StringUtils.isNotEmpty(twoUser.getDivideTwoScale())) {
                            twoMoney = pingMoney.multiply(new BigDecimal(twoUser.getDivideTwoScale()));
                        }
                        orders.setTwoDriverUserId(twoUser.getUserId());
                        orders.setTwoDriverUserMoney(twoMoney);
                    }
                }
            }


            pingMoney=pingMoney.subtract(oneUserMoney);
            pingMoney=pingMoney.subtract(twoUserMoney);

            pingMoney=pingMoney.subtract(oneMoney);
            pingMoney=pingMoney.subtract(twoMoney);

            orders.setPingMoney(pingMoney);
            baseMapper.updateById(orders);

            newCachedThreadPool.submit(() -> {
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                    String templateId = commonInfoService.findOne(427).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,"已接单");
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,msgList,1);
                }
                if(StringUtils.isNotEmpty(userEntity.getAccountOpenId())){
                    String templateId = commonInfoService.findOne(438).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsgGZH(userEntity.getAccountOpenId(),templateId,msgList,3);
                }
                if(StringUtils.isNotEmpty(userEntity.getClientid())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    userService.pushToSingle(title,"已接单",userEntity.getClientid());
                }


                UserEntity driverEntity = userService.selectUserById(driver.getUserId());
                if(StringUtils.isNotEmpty(driverEntity.getRiderOpenId())){
                    String templateId = commonInfoService.findOne(428).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,"已接单");
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendRiderMsg(driverEntity.getRiderOpenId(),templateId,msgList,2);
                }

                if(StringUtils.isNotEmpty(driverEntity.getRiderAccountOpenId())){
                    String templateId = commonInfoService.findOne(433).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendRiderMsgGZH(driverEntity.getRiderAccountOpenId(),templateId,msgList,3);
                }
                if(StringUtils.isNotEmpty(driverEntity.getClientRiderId())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    userService.pushToSingleQiShou(title,"已接单",driverEntity.getClientRiderId());
                }

            });

            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("接单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Result proceedOrders(Long ordersId,String code){
        Orders orders = baseMapper.selectById(ordersId);
        if(orders.getStatus()!=3){
            return Result.error("状态异常，刷新后重试！");
        }
        String phone = orders.getShipUserPhone().substring(7);
        if(!phone.equals(code)){
            return Result.error("验证码错误！");
        }
        orders.setStatus(4);
        orders.setStartTime(DateUtils.format(new Date()));
        baseMapper.updateById(orders);

        newCachedThreadPool.submit(() -> {
            UserEntity userEntity = userService.selectUserById(orders.getUserId());
            if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                String templateId = commonInfoService.findOne(427).getValue();
                List<String> msgList=new ArrayList<>();
                msgList.add(0,orders.getOrdersNo());
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                msgList.add(1,title);
                msgList.add(2,"进行中");
                msgList.add(3,DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,msgList,1);
            }

            if(StringUtils.isNotEmpty(userEntity.getAccountOpenId())){
                String templateId = commonInfoService.findOne(439).getValue();
                List<String> msgList=new ArrayList<>();
                msgList.add(0,orders.getOrdersNo());
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                msgList.add(1,title);
                msgList.add(2,DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsgGZH(userEntity.getAccountOpenId(),templateId,msgList,4);
            }
            if(StringUtils.isNotEmpty(userEntity.getClientid())){
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                userService.pushToSingle(title,"进行中",userEntity.getClientid());
            }

            Driver driver = driverService.getById(orders.getDriverId());
            UserEntity driverEntity = userService.selectUserById(driver.getUserId());
            if(StringUtils.isNotEmpty(driverEntity.getRiderOpenId())){
                String templateId = commonInfoService.findOne(428).getValue();
                List<String> msgList=new ArrayList<>();
                msgList.add(0,orders.getOrdersNo());
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                msgList.add(1,title);
                msgList.add(2,"进行中");
                msgList.add(3,DateUtils.format(new Date()));
                SenInfoCheckUtil.sendRiderMsg(driverEntity.getRiderOpenId(),templateId,msgList,2);
            }

            if(StringUtils.isNotEmpty(driverEntity.getRiderAccountOpenId())){
                String templateId = commonInfoService.findOne(434).getValue();
                List<String> msgList=new ArrayList<>();
                msgList.add(0,orders.getOrdersNo());
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                msgList.add(1,title);
                msgList.add(2,DateUtils.format(new Date()));
                SenInfoCheckUtil.sendRiderMsgGZH(driverEntity.getRiderAccountOpenId(),templateId,msgList,4);
            }
            if(StringUtils.isNotEmpty(driverEntity.getClientRiderId())){
                String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                if(title.length()>20){
                    title=title.substring(0,15)+"...";
                }
                userService.pushToSingleQiShou(title,"进行中",driverEntity.getClientRiderId());
            }

        });

        return Result.success();
    }

    @Override
    public Result completeOrders(Long ordersId){
        reentrantReadWriteLock.writeLock().lock();
        try {
            Orders orders = baseMapper.selectById(ordersId);
            if(orders.getStatus()!=4){
                return Result.error("状态异常，刷新后重试！");
            }
            orders.setStatus(5);
            orders.setEndTime(DateUtils.format(new Date()));
            baseMapper.updateById(orders);
            //给司机到账收益
            Driver driver = driverService.getById(orders.getDriverId());

            String isPrice = commonInfoService.findOne(633).getValue();
            if("是".equals(isPrice)){
                userMoneyService.updateBalance(1,driver.getUserId(),orders.getDriveMoney().doubleValue());
            }


            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            userMoneyDetails.setTitle("完成订单：");
            userMoneyDetails.setContent("到账收益："+orders.getDriveMoney()+" 订单号："+orders.getOrdersNo());
            userMoneyDetails.setUserType(2);
            userMoneyDetails.setUserId(driver.getUserId());
            userMoneyDetails.setMoney(orders.getDriveMoney());
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            //给用户一级二级收益
            if(orders.getOneUserId()!=null && orders.getOneUserMoney().doubleValue()>0){
                if("是".equals(isPrice)){
                    userMoneyService.updateInviteMoney(1,orders.getOneUserId(),orders.getOneUserMoney().doubleValue());
                }

                userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("一级用户完成订单："+orders.getOrdersNo());
                userMoneyDetails.setContent("到账收益："+orders.getOneUserMoney());
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(orders.getOneUserId());
                userMoneyDetails.setMoney(orders.getOneUserMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(2);
                userMoneyDetails.setUserLevel(1);
                userMoneyDetails.setRelationId(orders.getUserId());
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
            if(orders.getTwoUserId()!=null && orders.getTwoUserMoney().doubleValue()>0){
                if("是".equals(isPrice)){
                    userMoneyService.updateInviteMoney(1,orders.getTwoUserId(),orders.getTwoUserMoney().doubleValue());
                }
                userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("二级用户完成订单："+orders.getOrdersNo());
                userMoneyDetails.setContent("到账收益："+orders.getTwoUserMoney());
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(orders.getTwoUserId());
                userMoneyDetails.setMoney(orders.getTwoUserMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(2);
                userMoneyDetails.setUserLevel(2);
                userMoneyDetails.setRelationId(orders.getUserId());
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
            //给师傅一二级
            if(orders.getOneDriverUserId()!=null && orders.getOneDriverUserMoney().doubleValue()>0){
                if("是".equals(isPrice)){
                    userMoneyService.updateInviteMoney(1,orders.getOneDriverUserId(),orders.getOneDriverUserMoney().doubleValue());
                }

                userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("一级师傅完成订单："+orders.getOrdersNo());
                userMoneyDetails.setContent("到账收益："+orders.getOneDriverUserMoney());
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(orders.getOneDriverUserId());
                userMoneyDetails.setMoney(orders.getOneDriverUserMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(2);
                userMoneyDetails.setUserLevel(1);
                userMoneyDetails.setRelationId(orders.getUserId());
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
            if(orders.getTwoDriverUserId()!=null && orders.getTwoDriverUserMoney().doubleValue()>0){
                if("是".equals(isPrice)){
                    userMoneyService.updateInviteMoney(1,orders.getTwoDriverUserId(),orders.getTwoDriverUserMoney().doubleValue());
                }

                userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("二级师傅完成订单："+orders.getOrdersNo());
                userMoneyDetails.setContent("到账收益："+orders.getTwoDriverUserMoney());
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(orders.getTwoDriverUserId());
                userMoneyDetails.setMoney(orders.getTwoDriverUserMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(2);
                userMoneyDetails.setUserLevel(2);
                userMoneyDetails.setRelationId(orders.getUserId());
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
            newCachedThreadPool.submit(() -> {
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                    String templateId = commonInfoService.findOne(427).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,"已完成");
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,msgList,1);
                }

                if(StringUtils.isNotEmpty(userEntity.getAccountOpenId())){
                    String templateId = commonInfoService.findOne(440).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsgGZH(userEntity.getAccountOpenId(),templateId,msgList,5);
                }
                if(StringUtils.isNotEmpty(userEntity.getClientid())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    userService.pushToSingle(title,"已完成",userEntity.getClientid());
                }

                UserEntity driverEntity = userService.selectUserById(driver.getUserId());
                if(StringUtils.isNotEmpty(driverEntity.getRiderOpenId())){
                    String templateId = commonInfoService.findOne(428).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,"已完成");
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendRiderMsg(driverEntity.getRiderOpenId(),templateId,msgList,2);
                }

                if(StringUtils.isNotEmpty(driverEntity.getRiderAccountOpenId())){
                    String templateId = commonInfoService.findOne(435).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendRiderMsgGZH(driverEntity.getRiderAccountOpenId(),templateId,msgList,5);
                }
                if(StringUtils.isNotEmpty(driverEntity.getClientRiderId())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    userService.pushToSingleQiShou(title,"已完成",driverEntity.getClientRiderId());
                }

            });

            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("完成订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Result cancelOrders(Long ordersId,Integer isDriver){
        reentrantReadWriteLock.writeLock().lock();
        try {
            Orders orders = baseMapper.selectById(ordersId);
            if(orders.getStatus()==1){
                orders.setStatus(6);
                orders.setIsRefund(1);
                baseMapper.updateById(orders);
                if(orders.getCouponId()!=null){
                    TbCouponUser couponUser = couponUserService.getById(orders.getCouponId());
                    couponUser.setStatus(0);
                    couponUserService.updateById(couponUser);
                }
                return Result.success();
            }
            //状态 1待支付 2待接单 3已接单 4进行中 5已抵达 6已取消
            if(orders.getStatus()==4){
                return Result.error("进行中的订单不允许取消，请联系客服！");
            }else if(orders.getStatus()==5){
                return Result.error("订单已完成无法退款！");
            }else if(orders.getStatus()==3){
                Driver driver = driverService.getById(orders.getDriverId());
                UserEntity userEntity = userService.selectUserById(driver.getUserId());
                String score = commonInfoService.findOne(364).getValue();
                if (isDriver == 0){
                    creditRecordService.updateUserCreditRecord(userEntity, 2, Integer.parseInt(score), "取消订单扣除信用分",orders.getOrdersNo(),isDriver);
                } else if (isDriver == 1){
                    creditRecordService.updateUserCreditRecord(userEntity, 2, Integer.parseInt(score), "取消订单扣除信用分",orders.getOrdersNo(),isDriver);
                }
                //清空师傅的信息和师傅的上级  订单改为待接单
                baseMapper.update(null, Wrappers.<Orders>lambdaUpdate()
                        .set(Orders::getStatus,2)
                        .set(Orders::getDriverId,null)
                        .set(Orders::getOneDriverUserId,null)
                        .set(Orders::getOneDriverUserMoney,null)
                        .set(Orders::getTwoDriverUserId,null)
                        .set(Orders::getTwoDriverUserMoney,null)
                        .set(Orders::getIsRefund,1)
                        .eq(Orders::getOrdersId,orders.getOrdersId()));
                return Result.success();
            }
            if(orders.getCouponId()!=null){
                TbCouponUser couponUser = couponUserService.getById(orders.getCouponId());
                couponUser.setStatus(0);
                couponUserService.updateById(couponUser);
            }
            orders.setIsRefund(1);
            orders.setStatus(6);
            baseMapper.updateById(orders);
            if(orders.getPayWay()==1 || orders.getPayWay()==2 || orders.getPayWay()==3){
                PayDetails payDetails = payDetailsService.getOne(new QueryWrapper<PayDetails>().eq("classify", orders.getPayWay())
                        .eq("state", 2).eq("type", 2).eq("parent_id", ordersId));
                Result result = wxService.wxRefund(payDetails);
                String code = String.valueOf(result.get("code"));
                if("500".equals(code)){
                    return result;
                }
            }else if(orders.getPayWay()==4){
                PayDetails payDetails = payDetailsService.getOne(new QueryWrapper<PayDetails>().eq("classify", orders.getPayWay())
                        .eq("state", 2).eq("type", 2).eq("parent_id", ordersId));
                boolean b = aliPayController.aliRefund(payDetails);
                if(!b){
                    return Result.error("退款失败，请联系客服！");
                }
            }else if(orders.getPayWay()==5){
                userMoneyService.updateMoney(1,orders.getUserId(),orders.getPayMoney().doubleValue());
            }
            if(orders.getPayWay()!=6){
                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("退款订单："+orders.getOrdersNo());
                userMoneyDetails.setContent("原路退款："+orders.getPayMoney());
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(orders.getUserId());
                userMoneyDetails.setMoney(orders.getPayMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(9);
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }

            newCachedThreadPool.submit(() -> {
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                    String templateId = commonInfoService.findOne(427).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,"已退款");
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,msgList,1);
                }
                if(StringUtils.isNotEmpty(userEntity.getAccountOpenId())){
                    String templateId = commonInfoService.findOne(441).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsgGZH(userEntity.getAccountOpenId(),templateId,msgList,6);
                }
                if(StringUtils.isNotEmpty(userEntity.getClientid())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    userService.pushToSingle(title,"已退款",userEntity.getClientid());
                }


                if(orders.getDriverId()!=null){
                    Driver driver = driverService.getById(orders.getDriverId());
                    UserEntity driverEntity = userService.selectUserById(driver.getUserId());
                    if(StringUtils.isNotEmpty(driverEntity.getRiderOpenId())){
                        String templateId = commonInfoService.findOne(428).getValue();
                        List<String> msgList=new ArrayList<>();
                        msgList.add(0,orders.getOrdersNo());
                        String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                        if(title.length()>20){
                            title=title.substring(0,15)+"...";
                        }
                        msgList.add(1,title);
                        msgList.add(2,"已退款");
                        msgList.add(3,DateUtils.format(new Date()));
                        SenInfoCheckUtil.sendRiderMsg(driverEntity.getRiderOpenId(),templateId,msgList,2);
                    }

                    if(StringUtils.isNotEmpty(driverEntity.getRiderAccountOpenId())){
                        String templateId = commonInfoService.findOne(436).getValue();
                        List<String> msgList=new ArrayList<>();
                        msgList.add(0,orders.getOrdersNo());
                        String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                        if(title.length()>20){
                            title=title.substring(0,15)+"...";
                        }
                        msgList.add(1,title);
                        msgList.add(2,DateUtils.format(new Date()));
                        SenInfoCheckUtil.sendRiderMsgGZH(driverEntity.getRiderAccountOpenId(),templateId,msgList,6);
                    }
                    if(StringUtils.isNotEmpty(driverEntity.getClientRiderId())){
                        String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                        if(title.length()>20){
                            title=title.substring(0,15)+"...";
                        }
                        userService.pushToSingleQiShou(title,"已退款",driverEntity.getClientRiderId());
                    }

                }

            });


            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("完成订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Result refundOrders(Long ordersId){
        reentrantReadWriteLock.writeLock().lock();
        try {
            Orders orders = baseMapper.selectById(ordersId);
            if(orders.getCouponId()!=null){
                TbCouponUser couponUser = couponUserService.getById(orders.getCouponId());
                couponUser.setStatus(0);
                couponUserService.updateById(couponUser);
            }
            if(orders.getStatus()==1){
                orders.setIsRefund(1);
                orders.setStatus(6);
                baseMapper.updateById(orders);
                return Result.success();
            }
            orders.setStatus(6);
            orders.setIsRefund(1);
            baseMapper.updateById(orders);
            if(orders.getPayWay()==1 || orders.getPayWay()==2 || orders.getPayWay()==3){
                PayDetails payDetails = payDetailsService.getOne(new QueryWrapper<PayDetails>().eq("classify", orders.getPayWay())
                        .eq("state", 2).eq("type", 2).eq("parent_id", ordersId));
                Result result = wxService.wxRefund(payDetails);
                String code = String.valueOf(result.get("code"));
                if("500".equals(code)){
                    return result;
                }
            }else if(orders.getPayWay()==4){
                PayDetails payDetails = payDetailsService.getOne(new QueryWrapper<PayDetails>().eq("classify", orders.getPayWay())
                        .eq("state", 2).eq("type", 2).eq("parent_id", ordersId));
                boolean b = aliPayController.aliRefund(payDetails);
                if(!b){
                    return Result.error("退款失败，请联系客服！");
                }
            }else if(orders.getPayWay()==5){
                userMoneyService.updateMoney(1,orders.getUserId(),orders.getPayMoney().doubleValue());
            }
            if(orders.getPayWay()!=6){
                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("退款订单："+orders.getOrdersNo());
                userMoneyDetails.setContent("原路退款："+orders.getPayMoney());
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(orders.getUserId());
                userMoneyDetails.setMoney(orders.getPayMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(9);
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }

            newCachedThreadPool.submit(() -> {
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                if(StringUtils.isNotEmpty(userEntity.getOpenId())){
                    String templateId = commonInfoService.findOne(427).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,"已退款");
                    msgList.add(3,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,msgList,1);
                }
                if(StringUtils.isNotEmpty(userEntity.getAccountOpenId())){
                    String templateId = commonInfoService.findOne(441).getValue();
                    List<String> msgList=new ArrayList<>();
                    msgList.add(0,orders.getOrdersNo());
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    msgList.add(1,title);
                    msgList.add(2,DateUtils.format(new Date()));
                    SenInfoCheckUtil.sendMsgGZH(userEntity.getAccountOpenId(),templateId,msgList,6);
                }
                if(StringUtils.isNotEmpty(userEntity.getClientid())){
                    String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                    if(title.length()>20){
                        title=title.substring(0,15)+"...";
                    }
                    userService.pushToSingle(title,"已退款",userEntity.getClientid());
                }


                if(orders.getDriverId()!=null){
                    Driver driver = driverService.getById(orders.getDriverId());
                    UserEntity driverEntity = userService.selectUserById(driver.getUserId());
                    if(StringUtils.isNotEmpty(driverEntity.getRiderOpenId())){
                        String templateId = commonInfoService.findOne(428).getValue();
                        List<String> msgList=new ArrayList<>();
                        msgList.add(0,orders.getOrdersNo());
                        String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                        if(title.length()>20){
                            title=title.substring(0,15)+"...";
                        }
                        msgList.add(1,title);
                        msgList.add(2,"已退款");
                        msgList.add(3,DateUtils.format(new Date()));
                        SenInfoCheckUtil.sendRiderMsg(driverEntity.getRiderOpenId(),templateId,msgList,2);
                    }

                    if(StringUtils.isNotEmpty(driverEntity.getRiderAccountOpenId())){
                        String templateId = commonInfoService.findOne(436).getValue();
                        List<String> msgList=new ArrayList<>();
                        msgList.add(0,orders.getOrdersNo());
                        String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                        if(title.length()>20){
                            title=title.substring(0,15)+"...";
                        }
                        msgList.add(1,title);
                        msgList.add(2,DateUtils.format(new Date()));
                        SenInfoCheckUtil.sendRiderMsgGZH(driverEntity.getRiderAccountOpenId(),templateId,msgList,6);
                    }
                    if(StringUtils.isNotEmpty(driverEntity.getClientRiderId())){
                        String title=orders.getShipAddress()+"-"+orders.getDeliveryAddress();
                        if(title.length()>20){
                            title=title.substring(0,15)+"...";
                        }
                        userService.pushToSingleQiShou(title,"已退款",driverEntity.getClientRiderId());
                    }

                }

            });
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("完成订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Map<String, Integer> getOrderSubscript(Long userId) {
        Map<String, Integer> hashMap = new HashMap<>();
        //订单状态 1待支付 2待接单 3已接单 4进行中 5已抵达 6已取消
        int dzfOrders = baseMapper.selectCount(new QueryWrapper<Orders>().eq("user_id", userId).eq("status", 1));
        int djdOrders = baseMapper.selectCount(new QueryWrapper<Orders>().eq("user_id", userId).eq("status", 2));
        int yjdOrders = baseMapper.selectCount(new QueryWrapper<Orders>().eq("user_id", userId).eq("status", 3));
        int jxzOrders = baseMapper.selectCount(new QueryWrapper<Orders>().eq("user_id", userId).eq("status", 4));
        int yddOrders = baseMapper.selectCount(new QueryWrapper<Orders>().eq("user_id", userId).eq("status", 5));
        int yqxOrders = baseMapper.selectCount(new QueryWrapper<Orders>().eq("user_id", userId).eq("status", 6));
        hashMap.put("dzfOrders", dzfOrders);
        hashMap.put("djdOrders", djdOrders);
        hashMap.put("yjdOrders", yjdOrders);
        hashMap.put("jxzOrders", jxzOrders);
        hashMap.put("yddOrders", yddOrders);
        hashMap.put("yqxOrders", yqxOrders);

        return hashMap;
    }

    @Override
    public Integer selectTakeOrdersCount(Long userId,String date){
        return baseMapper.selectTakeOrdersCount(userId, date);
    }

    @Override
    public Integer selectMyOrdersCount(Long userId,String date){
        return baseMapper.selectMyOrdersCount(userId, date);
    }

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

    @Override
    public Result findIncome(Long userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        int indentCount = baseMapper.selectOrdersDriverCount(userId);
        BigDecimal indentMoney = baseMapper.selectOrdersDriverMoney(userId);
        hashMap.put("indentCount", indentCount);
        hashMap.put("indentMoney", indentMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectOrderByStatus(String date, Integer flag) {
        Map<String, Integer> result = new HashMap<>();
        // 状态 1待支付 2待接单 3已接单 4进行中 5已抵达 6已取消
        Integer allCount = baseMapper.selectOrderByStatus(flag, date,null);
        Integer dzfCount = baseMapper.selectOrderByStatus(flag, date,1);
        Integer djdCount = baseMapper.selectOrderByStatus(flag, date,2);
        Integer yjdCount = baseMapper.selectOrderByStatus(flag, date,3);
        Integer jxzCount = baseMapper.selectOrderByStatus(flag, date,4);
        Integer yddCount = baseMapper.selectOrderByStatus(flag, date,5);
        Integer yqxCount = baseMapper.selectOrderByStatus(flag, date,6);

        result.put("allCount",allCount);
        result.put("dzfCount",dzfCount);
        result.put("djdCount",djdCount);
        result.put("yjdCount",yjdCount);
        result.put("jxzCount",jxzCount);
        result.put("yddCount",yddCount);
        result.put("yqxCount",yqxCount);
        return Result.success().put("data", result);
    }

    @Override
    public Result incomeStatistics(String date, Integer dateType) {
        HashMap<String, Object> hashMap = new HashMap<>();
        //扣除师傅保证金收入
        BigDecimal deductMoneySum = userMoneyDetailsDao.deductMoneySum(date, dateType);
        //师傅保证金收入
        BigDecimal cashDepositMoney = userMoneyDetailsDao.cashDepositMoney(date, dateType);
        //订单收益
        BigDecimal ordersPingMoney = baseMapper.selectOrdersPingMoney(dateType, date);
        //总收入=服务费+保价费+扣除师傅保证金
        BigDecimal allMoneySum = deductMoneySum.add(cashDepositMoney).add(ordersPingMoney);
        hashMap.put("allMoneySum", allMoneySum);
        hashMap.put("ordersPingMoney", ordersPingMoney);
        hashMap.put("cashDepositMoney", cashDepositMoney);
        hashMap.put("deductMoneySum", deductMoneySum);
        return Result.success().put("data", hashMap);
    }

    @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) {
        return baseMapper.selectOrdersMoneyCountByUserId(userId,type);
    }

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

    @Override
    public Result platformMoney(String dateType, String date) {
        Map<String,BigDecimal> result = new HashMap<>();
        //支付金额
        BigDecimal payOrdersMoney = baseMapper.sumOrdersPayMoneyByTime(dateType, date);
        //司机收益
        BigDecimal driverMoney = baseMapper.sumOrdersDriveMoneyByTime(dateType, date);
        //一级收益
        BigDecimal oneUserMoney = baseMapper.sumOrdersUserMoneyByTime(dateType, date,1);
        //二级收益
        BigDecimal twoUserMoney = baseMapper.sumOrdersUserMoneyByTime(dateType, date,1);
        //平台收益
        BigDecimal pingMoney = baseMapper.sumOrdersPingMoneyByTime(dateType, date);
        result.put("payOrdersMoney", payOrdersMoney);
        result.put("driverMoney", driverMoney);
        result.put("oneUserMoney", oneUserMoney);
        result.put("twoUserMoney", twoUserMoney);
        result.put("pingMoney", pingMoney);
        return Result.success().put("data", result);
    }

    @Scheduled(fixedRate  = 60 * 1000, zone = "Asia/Shanghai")
    public void cancelOrdersByTime(){
        List<Orders> ordersList = baseMapper.selectOrdersByStartTime();
        for (Orders orders:ordersList){
            cancelOrders(orders.getOrdersId(),3);
        }
    }

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

    @Override
    public IPage<Orders> selectOrdersListByInvoice(Integer page,Integer limit,Long userId,String ordersNo,String startTime,String endTime){
        return baseMapper.selectOrdersListByInvoice(new Page<>(page,limit), userId, ordersNo, startTime, endTime);
    }

}
