com.visionet.platform.cooperation.service.OrderService.java Source code

Java tutorial

Introduction

Here is the source code for com.visionet.platform.cooperation.service.OrderService.java

Source

package com.visionet.platform.cooperation.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.visionet.core.aws.SQSService;
import com.visionet.core.exception.BizException;
import com.visionet.core.redis.RedisUtil;
import com.visionet.core.service.BaseService;
import com.visionet.core.util.Constants;
import com.visionet.core.util.DateUtil;
import com.visionet.core.util.HttpClient;
import com.visionet.core.util.OrderCreaterUtil;
import com.visionet.core.util.ResourceUtil;
import com.visionet.core.util.ValidateUtils;
import com.visionet.domain.BaseJson;
import com.visionet.platform.cooperation.dto.CarInfoDTO;
import com.visionet.platform.cooperation.dto.CarsModelDTO;
import com.visionet.platform.cooperation.dto.CarsModelListDTO;
import com.visionet.platform.cooperation.dto.JPushDto;
import com.visionet.platform.cooperation.dto.MetaDTO;
import com.visionet.platform.cooperation.dto.OrderCancelDTO;
import com.visionet.platform.cooperation.dto.OrderResultDTO;
import com.visionet.platform.cooperation.dto.PeekFareIncreaseDTO;
import com.visionet.platform.cooperation.dto.PeekFareIncreaseDayDTO;
import com.visionet.platform.cooperation.dto.PeekListDTO;
import com.visionet.platform.cooperation.dto.PollingResultDTO;
import com.visionet.platform.cooperation.mapper.CarUserMapper2;
import com.visionet.platform.cooperation.mapper.CustomerMapper;
import com.visionet.platform.cooperation.mapper.OrderInvoiceMapper;
import com.visionet.platform.cooperation.mapper.OrderMapper2;
import com.visionet.platform.cooperation.mapper.OrderPayDetailMapper2;
import com.visionet.platform.cooperation.mapper.OrderStatusTrackingMapper;
import com.visionet.platform.cooperation.mapper.PushDesMapper;
import com.visionet.platform.cooperation.mapper.SysDictMapper;
import com.visionet.platform.cooperation.model.CarUser;
import com.visionet.platform.cooperation.model.Customer;
import com.visionet.platform.cooperation.model.Order;
import com.visionet.platform.cooperation.model.OrderInvoice;
import com.visionet.platform.cooperation.model.OrderStatusTracking;
import com.visionet.platform.cooperation.model.PushDes;
import com.visionet.platform.cooperation.model.SysDict;
import com.visionet.platform.thirdpartydata.mapper.ThirdPartyCityMapper;
import com.visionet.platform.thirdpartydata.mapper.ThirdPartyOrderMapper;
import com.visionet.platform.thirdpartydata.model.ThirdPartyCity;
import com.visionet.platform.thirdpartydata.model.ThirdPartyOrder;

/**
 * projectName:dzcx_partner
 * author:liusy@visionet.com.cn
 */
@Service
public class OrderService extends BaseService<Order> {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);
    private static final int OPERATOR_SHOUQI = 4;//
    private static final String serverUrl = ResourceUtil.getValueBykey("base", "order.server.url");
    private static final String bizUrl = ResourceUtil.getValueBykey("base", "cancleorder.server.url");
    private static final String car_order_pay_with_app = "?,?";
    private static final String car_will_start = ResourceUtil.getValueBykey("base", "car.willStart");// ,??,?
    private static final String yz_car_ready_for_customer_onboard = ResourceUtil.getValueBykey("base",
            "car.yz.readyForCustomerOnBoard");// yuzu?,??
    private static final String RECIVE_SHOUYUE_ORDER = ResourceUtil.getValueBykey("base", "recive.shouyue.order");// ???
    private static final String order_payed = ResourceUtil.getValueBykey("base", "car.orderPayed");// ???
    private static final Long yuyuedanShishidanPoint = Long
            .valueOf(ResourceUtil.getValueBykey("base", "yuyuedan.shishidan.point"));
    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private OrderMapper2 orderMapper;
    @Autowired
    private OrderStatusTrackingMapper orderStatusTrackingMapper;
    @Autowired
    private ThirdPartyOrderMapper thirdPartyOrderMapper;
    @Autowired
    private OrderInvoiceMapper orderInvoiceMapper;
    @Autowired
    private CarUserMapper2 carUserMapper;
    @Autowired
    private PushDesMapper pushDesMapper;
    @Autowired
    private OrderPayDetailMapper2 orderPayDetailMapper;
    @Autowired
    private ThirdPartyCityMapper thirdPartyCityMapper;

    /**
     * ?  ?
     *
     * @param orderNo
     * @param partnerOrderNo
     * @param evaluateScore
     * @param describe
     */
    public void evaluateDriver(String orderNo, String partnerOrderNo, Integer evaluateScore, String describe) {
        if (StringUtils.isBlank(orderNo)) {
            throw new BizException("???");
        }
        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        if (order.getStatus() == null || order.getStatus() != 2) {
            throw new BizException("???");
        }
        Integer evaluateScore2 = order.getCarUserGrade();
        if (evaluateScore2 != null) {
            throw new BizException("????");
        }
        Customer customer = customerMapper.selectByPrimaryKey(order.getCustomerPhone());
        if (customer == null) {
            throw new BizException("??");
        }
        order.setCarUserGrade(evaluateScore);
        order.setBakstr4(describe);
        orderMapper.updateByPrimaryKeySelective(order);

        CarUser carUser = carUserMapper.selectByPrimaryKey(order.getCarId());
        if (carUser == null) {
            throw new BizException("??");
        }
        String starStr = carUser.getBakstr2();
        Integer allStar = 0;
        if (StringUtils.isBlank(starStr)) {
            allStar = 0;
        } else {
            allStar = Integer.parseInt(starStr);
        }
        Integer orderNum = carUser.getOrderCount();
        if (orderNum == 0) {
            throw new BizException("???");
        }
        Integer star = allStar + evaluateScore;
        Double d = (double) star;
        Double avgstar = d / orderNum;
        double value = new BigDecimal(avgstar).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (value > 5) {
            value = 5;
        }
        carUser.setBakstr2(star.toString());
        carUser.setGrade(value);
        carUserMapper.updateByPrimaryKey(carUser);
    }

    /**
     * ??  ?
     *
     * @param cityId
     * @return
     * @throws Exception
     */
    public CarsModelListDTO getCarsModelList(Integer cityId) throws Exception {
        if (cityId == null || "".equals(cityId) || cityId.intValue() == 0) {
            throw new BizException("ID?");
        }
        CarsModelListDTO carsModelListDTO = new CarsModelListDTO();

        // 
        List<SysDict> list = sysDictMapper.selectByDictTypeAndCityId("", cityId);
        if (list != null && !list.isEmpty()) {
            List<CarInfoDTO> carInfos = Lists.newArrayList();
            for (SysDict sysDict : list) {
                if (sysDict != null) {
                    String dictValue = sysDict.getDictValue();
                    if (StringUtils.isNotBlank(dictValue)) {
                        carInfos.add(JSONObject.parseObject(dictValue, CarInfoDTO.class));
                    }
                }
            }
            CarsModelDTO carsModelDTO = new CarsModelDTO();
            carsModelDTO.setCarInfos(carInfos);
            carsModelListDTO.setCarsModels(carsModelDTO);
        }
        // 
        List<SysDict> list2 = sysDictMapper.selectByDictTypeAndCityId("", cityId);
        if (list2 != null && !list2.isEmpty()) {
            PeekFareIncreaseDTO peekFareIncreaseDTO = new PeekFareIncreaseDTO();
            List<PeekFareIncreaseDayDTO> peekFareIncreaseDays = Lists.newArrayList();
            for (SysDict sysDict : list2) {
                if (sysDict != null) {
                    String dictValue = sysDict.getDictValue();
                    String dictName = sysDict.getDictName();
                    if (StringUtils.isNotBlank(dictValue) && StringUtils.isNotBlank(dictName)) {
                        PeekFareIncreaseDayDTO peekFareIncreaseDayDTO = new PeekFareIncreaseDayDTO();
                        peekFareIncreaseDayDTO.setDay(dictName);
                        peekFareIncreaseDayDTO.setPeekList(JSONObject.parseObject(dictValue, PeekListDTO.class));
                        peekFareIncreaseDays.add(peekFareIncreaseDayDTO);
                    }
                }
            }
            peekFareIncreaseDTO.setPeekFareIncreaseDays(peekFareIncreaseDays);
            carsModelListDTO.setPeekFareIncreases(peekFareIncreaseDTO);
        }

        return carsModelListDTO;
    }

    /**
     * ?
     *
     * @return
     * @throws Exception
     */
    public OrderResultDTO insertOrder(String partnerOrderId, String partnerOrderNo, Integer businessType,
            Integer orderType, String carType, String startPlace, String startGps, String endPlace,
            Double expectedKm, String endGps, String expectedPrice, String customerPhone, String customerName,
            String callDate, String bookDate, Integer orderSource, String city, Integer cityId, String sign,
            String channel) throws Exception {
        if (!"1".equals(RECIVE_SHOUYUE_ORDER)) {
            throw new BizException("?");
        }

        if (cityId == null || "".equals(cityId)) {
            throw new BizException("?ID?");
        }
        ThirdPartyCity thirdPartyCity = thirdPartyCityMapper.selectByDzcxCityId(cityId, 1);
        if (thirdPartyCity == null) {
            throw new BizException("?");
        }
        Integer reciveOrder = thirdPartyCity.getReciveOrder();
        if (reciveOrder == 0) {
            throw new BizException("?");
        }
        Date orderBookDate = null;
        // ----------------?? -------------------
        if (StringUtils.isEmpty(partnerOrderId)) {
            throw new BizException("???ID");
        }
        if (StringUtils.isEmpty(partnerOrderNo)) {
            throw new BizException("???");
        }
        ThirdPartyOrder tpo = thirdPartyOrderMapper.selectOneByPartnerOrderNo(partnerOrderNo);
        if (tpo != null) {
            throw new BizException("???");
        }
        if (StringUtils.isEmpty(customerPhone)) {
            throw new BizException("??");
        }
        if (expectedKm == null || "".equals(expectedKm)) {
            throw new BizException("");
        }
        if (expectedPrice == null || "".equals(expectedPrice)) {
            throw new BizException("?");
        }
        if (StringUtils.isEmpty(bookDate)) {
            throw new BizException("??");
        } else {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                orderBookDate = sdf.parse(bookDate);
            } catch (Exception e) {
                throw new BizException("???yyyy-MM-dd HH:mm:ss");
            }
            if (orderBookDate.before(new Date())) {
                throw new BizException("????");
            }
        }
        if (orderType == null || "".equals(orderType)) {
            throw new BizException("?");
        }

        if (StringUtils.isEmpty(city)) {
            throw new BizException("??");
        }
        if (businessType == null || "".equals(businessType)) {
            throw new BizException("??");
        }
        // ----------------?? ?-------------------

        // -------------??? ------------------
        Customer customer = customerMapper.selectByPrimaryKey(customerPhone);
        if (customer == null) {
            // ?
            Customer customer_new = new Customer();
            customer_new.setPhone(customerPhone);
            customer_new.setName(customerName);
            customer_new.setCreateDate(new Date());
            customer_new.setDelFlag(1);
            customer_new.setIsValid(0);
            customer_new.setLevel(1);
            customer_new.setIsApp(0);// 0APP
            customer_new.setStatus(4);// 4
            customer_new.setIsLogin(0);// 10
            customer_new.setSource("5");// 5
            customer_new.setCity(city);
            customer_new.setCityId(cityId);
            customerMapper.insertSelective(customer_new);
        }
        // -----------------??? ?---------------

        // ----------------------? ---------------------
        OrderResultDTO orderResultDTO = new OrderResultDTO();
        Order tOrder = new Order();
        Date date = new Date();
        String orderID = OrderCreaterUtil.createrOrder(businessType + "");
        tOrder.setOrderId(orderID);
        tOrder.setBusinessType(businessType);
        tOrder.setOrderType(orderType);// 6 
        tOrder.setOrderSource(4);// 4 
        tOrder.setCarType(carType);
        tOrder.setCarNumber(1);
        tOrder.setStartPlace(startPlace);
        tOrder.setStartGps(startGps);
        tOrder.setEndPlace(endPlace);
        tOrder.setEndGps(endGps);
        tOrder.setCustomerPhone(customerPhone);
        tOrder.setCustomerName(customerName);
        tOrder.setCallDate(date);// ??
        tOrder.setStatus(0);// ?0
        tOrder.setExpectedKm(expectedKm.floatValue());
        tOrder.setVirtual(0f);
        tOrder.setExpectedPrice(Float.valueOf(expectedPrice));
        tOrder.setIncreasePrice(0.0);
        tOrder.setIncreaseType(0);// ?012
        tOrder.setCity(city);
        tOrder.setCityId(cityId);
        tOrder.setBookDate(orderBookDate);

        orderMapper.insertSelective(tOrder);// ?

        SQSService.put(JSONObject.toJSONString(tOrder)); // aws SQS

        // ?????
        OrderStatusTracking orderStatusTracking = new OrderStatusTracking();
        orderStatusTracking.setOrderId(orderID);
        orderStatusTracking.setCustomerPhone(customerPhone);
        orderStatusTracking.setBusinessType(businessType);
        orderStatusTracking.setNewStatus(0);// 0?
        orderStatusTracking.setCreateDate(date);
        orderStatusTracking.setOperator(0);// 
        orderStatusTrackingMapper.insertSelective(orderStatusTracking);

        // ???
        Integer thirdPartyOrderType = 1;// 0 ? 1 ?
        Long minutes = DateUtil.minusTime(new Date(), orderBookDate);
        if (yuyuedanShishidanPoint > minutes) {
            thirdPartyOrderType = 0;
        }
        ThirdPartyOrder thirdPartyOrder = new ThirdPartyOrder();
        thirdPartyOrder.setMerchantId(1);// 1
        thirdPartyOrder.setSource(1);// ???0?1
        thirdPartyOrder.setOrderId(orderID);// ??
        thirdPartyOrder.setPartnerOrderId(partnerOrderId);
        thirdPartyOrder.setPartnerOrderNo(partnerOrderNo);
        thirdPartyOrder.setCreateDate(new Date());
        thirdPartyOrder.setOrderType(thirdPartyOrderType);
        thirdPartyOrder.setNotice(0);
        thirdPartyOrderMapper.insertSelective(thirdPartyOrder);

        // ----------------------? ?---------------------

        orderResultDTO.setOrderNo(orderID);
        return orderResultDTO;
    }

    /**
     * ??  ??
     *
     * @param orderNo
     * @param partnerOrderNo
     * @param orderStatus
     * @param sign
     * @param channel
     * @author ?
     *//*
        public void updateOrderStatus(String orderNo, String partnerOrderNo, String orderStatus, String sign, String channel) {
        if (StringUtils.isEmpty(orderNo)) {
            throw new BizException("???");
        }
        if (StringUtils.isEmpty(partnerOrderNo)) {
            throw new BizException("????");
        }
        if (StringUtils.isEmpty(orderStatus)) {
            throw new BizException("????");
        }
        if (!ValidateUtils.checkIsInt(orderStatus)) {
            throw new BizException("????");
        }
        Order result = orderMapper.selectByPrimaryKey(orderNo);
        Order order = new Order();
        order.setOrderId(orderNo);
        order.setStatus(Integer.valueOf(orderStatus));
        order.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        OrderStatusTracking orderStatusTracking = new OrderStatusTracking();
        orderStatusTracking.setOrderId(orderNo);
        orderStatusTracking.setCustomerPhone(result.getCustomerPhone());
        orderStatusTracking.setBusinessType(result.getBusinessType());
        orderStatusTracking.setPreStatus(result.getStatus());
        orderStatusTracking.setNewStatus(Integer.valueOf(orderStatus));
        orderStatusTracking.setCreateDate(new Date());
        orderStatusTracking.setOperator(OPERATOR_SHOUQI);//
        orderStatusTrackingMapper.insertSelective(orderStatusTracking);
        }*/

    /**
     * ?? 
     *
     * @param sign
     * @param channel
     * @param orderNo
     * @param partnerOrderNo
     * @param payType
     * @author ?
     */
    public void settlementNotice(String sign, String channel, String orderNo, String partnerOrderNo, String payType,
            BigDecimal payAmount) {
        if (StringUtils.isEmpty(orderNo)) {
            throw new BizException("???");
        }
        if (StringUtils.isEmpty(partnerOrderNo)) {
            throw new BizException("????");
        }
        if (StringUtils.isEmpty(payType)) {
            throw new BizException("??");
        }
        if (!ValidateUtils.checkIsInt(payType)) {
            throw new BizException("??");
        }
        if ("2".equals(payType)) {// ?
            int amount = payAmount.compareTo(BigDecimal.ZERO);
            if (amount == 0) {
                throw new BizException("???0");
            }
        }
        // ??
        ThirdPartyOrder tpOrder = new ThirdPartyOrder();
        tpOrder.setOrderId(orderNo);
        tpOrder.setPartnerOrderNo(partnerOrderNo);
        tpOrder.setUpdateDate(new Date());
        if (Integer.valueOf(payType) == 1) {// 
            tpOrder.setPayType(Integer.valueOf(payType));
            tpOrder.setFinishDate(new Date());
            // ????
            Order order = new Order();
            order.setStatus(2);// ?
            order.setFinishDate(new Date());
            order.setOrderId(orderNo);
            order.setUpdateDate(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }
        if (Integer.valueOf(payType) == 2) {// ?
            // TODO ?
            tpOrder.setPayType(Integer.valueOf(payType));
            tpOrder.setPayAmount(payAmount);
        }
        thirdPartyOrderMapper.updateBySelective(tpOrder);
    }

    /**
     * ??
     *
     * @param orderNo
     * @param partnerOrderNo
     * @param cancelType
     * @param reason
     * @author ?
     */
    public void cancelOrder(String orderNo, String partnerOrderNo, Integer cancelType, BigDecimal cancelAmount,
            String reason) {
        if (StringUtils.isEmpty(orderNo)) {
            throw new BizException("???");
        }
        if (StringUtils.isEmpty(partnerOrderNo)) {
            throw new BizException("????");
        }
        if (cancelType == null || cancelType.intValue() == 0) {
            throw new BizException("??");
        }

        ThirdPartyOrder tpo = thirdPartyOrderMapper.selectByOrderIdAndPartnerOrderNo(orderNo, partnerOrderNo);
        if (tpo == null) {
            throw new BizException("?????");
        }

        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        Integer status = order.getStatus();
        if ("1".equals(order.getBusinessType())) {
            if (status == 8 || status == 9 || status == 11 || status == 12) {
                throw new BizException("10", "???");
            }
        }
        if (status == 2) {
            throw new BizException("11", "?");
        }
        if (status == 3) {
            throw new BizException("11", "?");
        }
        //?
        if (cancelType.intValue() == 1) {
            BaseJson<OrderCancelDTO> baseJson = new BaseJson<>();
            OrderCancelDTO orderCancelDTO = new OrderCancelDTO();
            List<String> orderIds = Lists.newArrayList();
            orderIds.add(orderNo);
            orderCancelDTO.setOrderIds(orderIds);
            orderCancelDTO.setType(1);// ?? 0?1
            orderCancelDTO.setSourceType(4);// ?0 1? 2?? 3?? 4
            orderCancelDTO.setDescription(reason);
            baseJson.setBody(orderCancelDTO);

            String ret = HttpClient.post(serverUrl + bizUrl, JSONObject.toJSONString(baseJson));
            if (StringUtils.isBlank(ret)) {
                throw new BizException("11", "?");
            }
            JSONObject json = JSONObject.parseObject(ret);
            if (json.containsKey("success")) {
                if (!"0".equals(json.getString("success"))) {
                    throw new BizException(json.getString("msg"));
                }
                // ??
            } else {
                throw new BizException("11", "?");
            }

            tpo.setCustomerCancelCharge(cancelAmount);
            tpo.setUpdateDate(new Date());
            Integer num = thirdPartyOrderMapper.updateByPrimaryKeySelective(tpo);
            if (num != 1) {
                throw new BizException("??");
            }
        } else if (cancelType.intValue() == 2) {
            RedisUtil.setData(REDIS_ORDER_STATUS + order.getOrderId(), ORDER_STATUS_CANCLE_VALUE, 3 * 60);
            RedisUtil.delData(GRAP_ORDER_RESULT + orderNo);
            log.info("=====??{}", order.getOrderId());
        } else if (cancelType.intValue() == 3) {
            RedisUtil.setData(REDIS_ORDER_STATUS + order.getOrderId(), ORDER_STATUS_CANCLE_VALUE, 3 * 60);
            RedisUtil.delData(GRAP_ORDER_RESULT + orderNo);
            BaseJson<OrderCancelDTO> baseJson = new BaseJson<>();
            OrderCancelDTO orderCancelDTO = new OrderCancelDTO();
            List<String> orderIds = Lists.newArrayList();
            orderIds.add(orderNo);
            orderCancelDTO.setOrderIds(orderIds);
            orderCancelDTO.setType(1);// ?? 0?1
            orderCancelDTO.setSourceType(4);// ?0 1? 2?? 3?? 4
            orderCancelDTO.setDescription(reason);
            baseJson.setBody(orderCancelDTO);

            String ret = HttpClient.post(serverUrl + bizUrl, JSONObject.toJSONString(baseJson));
            if (StringUtils.isBlank(ret)) {
                throw new BizException("11", "?");
            }
            log.info("=====?{}", order.getOrderId());
        }

        // ??----???
        log.info("?" + orderNo + "??");
    }

    public static final String ORDER_STATUS_CANCLE_VALUE = "cancle";// ???

    /**
     * ?
     *
     * @param orderNo
     * @param partnerOrderNo
     * @param invoiceTitle
     * @param invoiceContent
     * @param address
     * @param postCode
     * @param addressee
     * @param phone
     * @param amount
     * @param sign
     * @param channel
     * @author fangren
     */
    public void postInvoice(String orderNo, String partnerOrderNo, String invoiceTitle, String invoiceContent,
            String address, String postCode, String addressee, String phone, BigDecimal amount, String sign,
            String channel) {
        if (StringUtils.isEmpty(orderNo)) {
            throw new BizException("???");
        }
        if (StringUtils.isEmpty(partnerOrderNo)) {
            throw new BizException("????");
        }
        ThirdPartyOrder tpo = thirdPartyOrderMapper.selectByOrderIdAndPartnerOrderNo(orderNo, partnerOrderNo);
        if (tpo == null) {
            throw new BizException("?????");
        }

        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        if (StringUtils.isEmpty(phone)) {
            throw new BizException("??");
        }
        if (StringUtils.isEmpty(address)) {
            throw new BizException("??");
        }
        if (StringUtils.isEmpty(invoiceTitle)) {
            throw new BizException("??");
        }
        // Customer customer = customerMapper.selectByPrimaryKey(phone);
        // Double invoiceBalance = customer.getInvoiceBalance();
        // Double invailInvoice = invoiceBalance - moneySum;
        // if (invailInvoice < 0) {
        // throw new BizException("????");
        // }
        // customer.setInvoiceBalance(invailInvoice);
        // customerMapper.updateByPrimaryKeySelective(customer);

        if (order.getIsInvoice() != 0) {
            throw new BizException("??");
        }
        // -----------?----------
        OrderInvoice orderInvoice = new OrderInvoice();
        orderInvoice.setNumber(1);// 
        orderInvoice.setAmount(amount.doubleValue());// ??
        orderInvoice.setOrderId(orderNo);// ?id,
        orderInvoice.setPhone(phone);// ?
        orderInvoice.setTotalAmount(amount.doubleValue());// ?
        orderInvoice.setReceiver(addressee);// 
        orderInvoice.setCompanyName(invoiceTitle);// ???
        orderInvoice.setApplyDate(new Date());
        orderInvoice.setReceiverPhone(phone);
        orderInvoice.setReceiverAddress(address);
        orderInvoice.setInvoiceType(1);//0:?1??
        orderInvoice.setStatus(1);// 
        orderInvoice.setArea(order.getCity());// 
        orderInvoice.setZipCode(postCode);// 
        orderInvoice.setInvoiceDescription(invoiceContent);// ??
        Integer num = orderInvoiceMapper.insertSelective(orderInvoice);
        if (num != 1) {
            throw new BizException("");
        }
        // -----------??----------

        // ????
        order.setIsInvoice(1);// ?0   ; 1 
        order.setUpdateDate(new Date());
        int j = orderMapper.updateByPrimaryKeySelective(order);
        if (j != 1) {
            throw new BizException("???");
        }
    }

    public boolean syncOrderInformation(String orderId, Integer driverId) {
        CarUser cu = carUserMapper.selectByPrimaryKey(driverId);
        if (cu == null) {
            throw new BizException("??");
        }
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new BizException("???");
        }
        order.setCarId(cu.getId());
        order.setCarUserPhone(cu.getPhone());
        order.setCarUserName(cu.getName());
        if (!(orderMapper.updateByPrimaryKeySelective(order) > 0)) {
            throw new BizException("??");
        }
        return true;
    }

    public void checkSyncOrderInfoDTO(String orderNo, String partnerOrderNo, Integer driverId, String driverName,
            String vehicleLicense, String driverPhone, String carModel, String driverRate, String driverPhoto,
            String latitude, String longitude, String sign, String channel) {
        if (StringUtils.isBlank(orderNo)) {
            throw new BizException("orderNo?");
        }
        if (StringUtils.isBlank(partnerOrderNo)) {
            throw new BizException("partnerOrderNo?");
        }
        if (driverId == null) {
            throw new BizException("driverId?");
        }
        if (StringUtils.isBlank(driverName)) {
            throw new BizException("driverName?");
        }
        if (StringUtils.isBlank(vehicleLicense)) {
            throw new BizException("vehicleLicense?");
        }
        if (StringUtils.isBlank(driverPhone)) {
            throw new BizException("driverPhone?");
        }
        if (StringUtils.isBlank(carModel)) {
            throw new BizException("carModel?");
        }
        if (StringUtils.isBlank(driverRate)) {
            throw new BizException("driverRate?");
        }
        if (StringUtils.isBlank(driverPhoto)) {
            throw new BizException("driverPhoto?");
        }
        if (StringUtils.isBlank(latitude)) {
            throw new BizException("latitude?");
        }
        if (StringUtils.isBlank(longitude)) {
            throw new BizException("longitude?");
        }
        if (StringUtils.isBlank(sign)) {
            throw new BizException("sign?");
        }
        if (StringUtils.isBlank(channel)) {
            throw new BizException("channel?");
        }
    }

    /*public void reassignmentNotice(String orderNo, String partnerOrderNo, Integer driverId, String driverName,
                               String vehicleLicense, String driverPhone, String carModel, Integer driverRate, String driverPhoto, String latitude,
                               String longitude, String sign, String channel) {
        
    if (StringUtils.isEmpty(orderNo)) {
        throw new BizException("???");
    }
    if (driverId == null) {
        throw new BizException("?ID?");
    }
    if (StringUtils.isEmpty(driverName)) {
        throw new BizException("????");
    }
    if (StringUtils.isEmpty(vehicleLicense)) {
        throw new BizException("??");
    }
    if (StringUtils.isEmpty(driverPhone)) {
        throw new BizException("???");
    }
    if (driverRate == null) {
        throw new BizException("??");
    }
    if (StringUtils.isEmpty(carModel)) {
        throw new BizException("?");
    }
    if (StringUtils.isEmpty(driverPhoto)) {
        throw new BizException("??URL?");
    }
        
    CarUser carUserParameter = new CarUser();
    carUserParameter.setId(driverId);
        
    Order orderParameter = new Order();
    orderParameter.setOrderId(orderNo);
    Order order = orderMapper.selectOne(orderParameter);
    CarUser selectOne = carUserMapper.selectOne(carUserParameter);
    if (selectOne == null) {
        carUserParameter.setPhone(driverPhone);
        carUserParameter.setName(driverName);
        carUserParameter.setCarNumber(vehicleLicense);
        carUserParameter.setType(0);//(0?1??)
        carUserParameter.setDriverSource(1);//???(0:,1:)
        carUserParameter.setCity(order.getCity());
        carUserParameter.setCityId(order.getCityId());
        carUserParameter.setDelFlag(1);
        carUserParameter.setGrade(Double.parseDouble(driverRate.toString()));
        carUserParameter.setStatus(1);//?012?3, 4,5,6?? 7:?
        carUserParameter.setRegisterDate(new Date());
        carUserParameter.setHeadPic(driverPhoto);
        if (carUserMapper.insertSelective(carUserParameter) != 1) {
            throw new BizException("?");
        }
        
    }
        
    orderParameter.setCarId(driverId);
    orderParameter.setCarType(carModel);
    orderParameter.setCarUserPhone(driverPhone);
    orderParameter.setCarUserName(driverName);
    orderParameter.setUpdateDate(new Date());
    orderParameter.setStatus(1);//?01?2?3?4567?,89, 10?(?),11,12?,13?,14??,15
    if (orderMapper.updateByPrimaryKeySelective(orderParameter) != 1) {
        throw new BizException("?");
    }
        
    //????
    OrderStatusTracking orderStatusTracking = new OrderStatusTracking();
    orderStatusTracking.setOrderId(orderNo);
    orderStatusTracking.setCarUserPhone(driverPhone);
    orderStatusTracking.setCustomerPhone(order.getCustomerPhone());
    orderStatusTracking.setBusinessType(order.getBusinessType());
    orderStatusTracking.setPreStatus(order.getStatus());
    orderStatusTracking.setNewStatus(1);
    orderStatusTracking.setCreateDate(new Date());
    orderStatusTracking.setOperator(4);//?01?2?? 3??4
    orderStatusTrackingMapper.insertSelective(orderStatusTracking);
    }*/

    /**
     * ??
     * @param orderNo
     * @param partnerOrderNo
     * @param sign
     * @param channel
     * @return
     */
    public PollingResultDTO pollingOrder(String orderNo, String partnerOrderNo, String sign, String channel) {
        if (orderNo == null) {
            throw new BizException("?orderNo");
        }
        if (partnerOrderNo == null) {
            throw new BizException("?partnerOrderNo");
        }
        if (sign == null) {
            throw new BizException("?sign");
        }
        if (channel == null) {
            throw new BizException("?channel");
        }
        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        PollingResultDTO resultDTO = new PollingResultDTO();
        resultDTO.setOrderNo(order.getOrderId());
        resultDTO.setOrderStatus(order.getStatus().toString());
        if (order.getCarId() != null) {
            CarUser carUser = carUserMapper.selectByPrimaryKey(order.getCarId());
            if (carUser == null) {
                throw new BizException("???");
            }
            resultDTO.setDriverId(order.getCarId().toString());
            resultDTO.setDriverName(carUser.getName());
            resultDTO.setDriverPhone(carUser.getPhone());
            resultDTO.setStartAddr(order.getStartPlace());
            resultDTO.setEndAddr(order.getEndPlace());
            resultDTO.setCarModel(carUser.getCarType().toString());
            resultDTO.setVehicleLicense(carUser.getCarNumber());
        }
        return resultDTO;
    }

    public void payNotify(String orderNo, BigDecimal amount) {
        if (orderNo == null) {
            throw new BizException("?orderNo");
        }
        if (amount == null) {
            throw new BizException("?amount");
        }
        if (amount.compareTo(BigDecimal.valueOf(0)) != 1) {//-1? 0 1  ???0??
            throw new BizException("??0");
        }
        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        String customerPhone = order.getCustomerPhone();
        if (customerPhone != null) {
            Customer customer = customerMapper.selectByPrimaryKey(customerPhone);
            if (customer == null) {
                throw new BizException("?");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("phone", customerPhone);
            map.put("userType", "2");
            List<PushDes> pushDesList = pushDesMapper.selectByPhoneAndUserType(map);
            if (pushDesList == null || pushDesList.isEmpty()) {
                throw new BizException("?");
            }
            PushDes pushDes = pushDesList.get(0);
            if (pushDes == null || StringUtils.isBlank(pushDes.getChannelId())) {
                throw new BizException("?");
            }
            String channelId = pushDes.getChannelId();
            BaseJson<JPushDto> JPushDtoJson = new BaseJson<JPushDto>();
            JPushDto jPushdto = new JPushDto();
            JSONObject contentJson = new JSONObject();
            contentJson.put("type", "orderNeedPay");
            contentJson.put("content", car_order_pay_with_app);
            contentJson.put("orderId", orderNo);
            contentJson.put("money", amount);
            jPushdto.setContent(contentJson);
            List<String> desList = new ArrayList<String>();
            desList.add(channelId);
            jPushdto.setDes(desList);
            jPushdto.setAlert(car_order_pay_with_app);
            jPushdto.setTimeToLive(6000);
            jPushdto.setType(1);// 12?
            jPushdto.setUserType(2);//  1:?23:?
            jPushdto.setPushType(1);// 0?1?2tag?
            JPushDtoJson.setBody(jPushdto);
            push2socket(JPushDtoJson);// socket?
        }
    }

    /**
     * push to customer
     */
    public static JSONObject push2socket(BaseJson<JPushDto> jPushDtoJson) throws BizException {
        String push2socket = null;
        push2socket = ResourceUtil.getValueBykey("base", "yzc_car_transport_info");
        String jso = HttpClient.post(push2socket, JSONObject.toJSONString(jPushDtoJson));
        if (jso == null) {
            throw new BizException("?");
        }
        JSONObject json = JSONObject.parseObject(jso);
        return json;
    }

    /**
     *    ??
     *
     * @param meta
     * @author ?
     */
    public void carUserOrderTaking(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 1) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        // ???
        String carType = "";
        CarUser carUserResult = carUserMapper.selectByParam(metaDto.getDriverInfo().getDriverId(), 1);
        if (carUserResult == null) {
            carUserResult = new CarUser();
            carUserResult.setDriverId(metaDto.getDriverInfo().getDriverId());// ?Id
            carUserResult.setDriverSource(1); // ???
            carUserResult.setName(metaDto.getDriverInfo().getName());// ???
            carUserResult.setPhone(metaDto.getDriverInfo().getPhone());// ??
            carUserResult.setCarNumber(metaDto.getDriverInfo().getLicensePlates());// ??
            carUserResult.setGrade(Double.valueOf(metaDto.getDriverInfo().getDriverRate()));
            carUserResult.setBusinessType(1);// 
            carUserResult.setType(1);// 
            carUserResult.setRegisterDate(new Date());// 
            carUserResult.setIsValid(1);// ?
            carUserResult.setCity(result.getCity());// ??
            carUserResult.setCityId(result.getCityId());// ?Id?Id
            carUserResult.setHeadPic(metaDto.getDriverInfo().getPhotoSrc());// ??
            carUserResult.setCompany("");
            carUserResult.setStatus(1);// 
            carUserResult.setDelFlag(1);// 
            if ("34".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(0);
                carType = "";
            }
            if ("35".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(1);
                carType = "";
            }
            if ("41".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(2);
                carType = "?";
            }
            carUserMapper.insertUseGeneratedKeys(carUserResult);
            order.setCarId(carUserResult.getId());
            order.setCarUserName(metaDto.getDriverInfo().getName());
            order.setCarUserPhone(metaDto.getDriverInfo().getPhone());
        } else {
            // ??
            carUserResult.setName(metaDto.getDriverInfo().getName());// ???
            carUserResult.setPhone(metaDto.getDriverInfo().getPhone());// ??
            carUserResult.setCarNumber(metaDto.getDriverInfo().getLicensePlates());// ??
            carUserResult.setBusinessType(1);// 
            carUserResult.setType(1);// 
            carUserResult.setRegisterDate(new Date());// 
            carUserResult.setIsValid(1);// ?
            carUserResult.setCity(result.getCity());// ??
            carUserResult.setCityId(result.getCityId());// ?Id?Id
            carUserResult.setHeadPic(metaDto.getDriverInfo().getPhotoSrc());// ??
            carUserResult.setCompany("");
            carUserResult.setStatus(1);// 
            carUserResult.setDelFlag(1);// 
            carUserResult.setGrade(Double.valueOf(metaDto.getDriverInfo().getDriverRate()));
            if ("34".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(0);
                carType = "";
            }
            if ("35".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(1);
                carType = "";
            }
            if ("41".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(2);
                carType = "?";
            }
            carUserMapper.updateByPrimaryKey(carUserResult);
            order.setCarId(carUserResult.getId());
            order.setCarUserName(carUserResult.getName());
            order.setCarUserPhone(carUserResult.getPhone());
        }
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("accepted".equals(metaDto.getStatus())) {
            order.setStatus(1);// ?
            order.setOrderStartDate(new Date());
        }
        order.setCarUserChannel(1);// 1
        order.setUpdateDate(new Date());
        order.setOrderStartDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        // ???
        addOrderStatusDetail(result, 1);
        String orderId = metaDto.getPartnerOrderNo();
        // redis????
        RedisUtil.setData("CARUSER_ORDER_TAKING_" + metaDto.getPartnerOrderNo(), metaDto.getPartnerOrderNo(),
                60 * 10);
        // TODO: liusy 16/7/18 17:06  ?
        RedisUtil.delData("bkOrderData-" + result.getOrderId());

        RedisUtil.delData("yydkd-" + orderId);// ???
        RedisUtil.delData("yydkdReject-" + orderId);
        RedisUtil.delData("yywfGrab-" + orderId);
        RedisUtil.setData(REDIS_ORDER_STATUS + order.getOrderId(), "grabed", 20 * 60);
        RedisUtil.setData(SHOUYUE_RECIVE_KEY + order.getOrderId(), order.getOrderId() + ";" + carUserResult.getId(),
                20 * 60);

        // TODO: 16/7/7 ????
        String carNumber = StringUtils.isBlank(carUserResult.getCarNumber()) ? ""
                : carUserResult.getCarNumber().substring(carUserResult.getCarNumber().length() - 4,
                        carUserResult.getCarNumber().length());
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("phone", result.getCustomerPhone());
            map.put("userType", "2");
            List<PushDes> pushDesList = pushDesMapper.selectByPhoneAndUserType(map);
            if (pushDesList == null || pushDesList.isEmpty()) {
                throw new BizException("?");
            }
            PushDes pushDes = pushDesList.get(0);
            if (pushDes == null || StringUtils.isBlank(pushDes.getChannelId())) {
                throw new BizException("?");
            }
            // TODO: 16/7/7 ? ?
            String channelId = pushDes.getChannelId();
            BaseJson<JPushDto> JPushDtoJson = new BaseJson<>();
            JPushDto jPushdto = new JPushDto();
            JSONObject contentJson = new JSONObject();
            contentJson.put("type", "ok");
            contentJson.put("orderId", orderId);
            jPushdto.setContent(contentJson);
            List<String> desList = new ArrayList<String>();
            desList.add(channelId);
            jPushdto.setDes(desList);
            jPushdto.setAlert("??");
            jPushdto.setTimeToLive(6000);
            jPushdto.setType(1);// 12?
            jPushdto.setUserType(2);//  1:?23:?
            jPushdto.setPushType(1);// 0?1?2tag?
            JPushDtoJson.setBody(jPushdto);
            push2socket(JPushDtoJson);// socket?

            String name = StringUtils.isBlank(carUserResult.getName()) ? ""
                    : carUserResult.getName().substring(0, 1);
            sendBySMS(result.getCustomerPhone(),
                    "??-" + result.getStartPlace() + "??" + carNumber
                            + "" + carType + "?" + name + "?"
                            + carUserResult.getPhone() + "",
                    1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendBySMS(String phone, String messages, Integer type) {
        String serverUrl = ResourceUtil.getValueBykey("base", "order.server.url");
        String smsUrl = ResourceUtil.getValueBykey("base", "sms.server.url");
        JSONObject body = new JSONObject();
        body.put("dest", phone);
        body.put("message", messages);
        body.put("type", type);
        System.out.println("messages===" + messages);
        String headstr = "{\"screeny\":\"1334\",\"cd\":\"fTr/KQDa8vYVauyd0592HQ==\",\"mos\":\"IOS 8.3\",\"ver\":\"1\",\"de\":\"2015-07-28 14:04:42\",\"aid\":\"NetworkFramework\",\"phone\":\"1234567\",\"screenx\":\"750\"}";
        JSONObject headsjson = JSONObject.parseObject(headstr);
        JSONObject json = new JSONObject();
        json.put("head", headsjson);
        json.put("body", body);
        HttpClient.post(serverUrl + smsUrl, json.toJSONString());
    }

    /**
     *   ??
     *
     * @param meta
     */
    public void carUserSetOut(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("accepted".equals(metaDto.getStatus())) {
            order.setStatus(1);// ?
        }
        order.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *   ?
     *
     * @param meta
     * @author ?
     */
    public void carUserReach(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("arriving".equals(metaDto.getStatus())) {
            order.setStatus(14);// ??
        }
        order.setTranportStartDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        // ???
        addOrderStatusDetail(result, 14);
        // TODO  ??
        String customerPhone = result.getCustomerPhone();// ?
        PushDes pushDes = pushDesMapper.selectByPhone(customerPhone, "2");
        if (pushDes != null && StringUtils.isNotEmpty(pushDes.getChannelId())) {
            String channelId = pushDes.getChannelId();
            BaseJson<JPushDto> jPushDtoJson = new BaseJson<JPushDto>();
            JPushDto jPushdto = new JPushDto();
            JSONObject contentJson = new JSONObject();
            String ss = yz_car_ready_for_customer_onboard;// ,
            contentJson.put("content", ss);
            contentJson.put("type", "pickPassenger");
            contentJson.put("orderId", metaDto.getPartnerOrderNo());
            jPushdto.setContent(contentJson);// ?? Json?
            List<String> desList = new ArrayList<String>();
            desList.add(channelId);
            jPushdto.setDes(desList);// ?? pushType:0
            // ?1:?// 2:?tag
            jPushdto.setAlert(ss);// ??
            jPushdto.setTimeToLive(6000);// ?? ??
            jPushdto.setType(1);// type? 1? 2?? //
            jPushdto.setUserType(2);//  1:?23:?
            jPushdto.setPushType(1);// 0?1?2tag?
            jPushDtoJson.setBody(jPushdto);
            push2socket(jPushDtoJson);
        }
    }

    /**
     *   ??
     *
     * @param meta
     * @author ?
     */
    public void orderStart(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("in_progress".equals(metaDto.getStatus())) {
            order.setStatus(11);// 
        }
        orderMapper.updateByPrimaryKeySelective(order);
        // ???
        addOrderStatusDetail(result, 11);
        // TODO  ??
        String customerPhone = result.getCustomerPhone();
        PushDes pushDes = pushDesMapper.selectByPhone(customerPhone, "2");
        if (pushDes != null && StringUtils.isNotEmpty(pushDes.getChannelId())) {
            String channelId = pushDes.getChannelId();
            BaseJson<JPushDto> JPushDtoJson = new BaseJson<JPushDto>();
            JPushDto jPushdto = new JPushDto();
            JSONObject contentJson = new JSONObject();
            contentJson.put("content", car_will_start);
            contentJson.put("type", "pickpi");
            contentJson.put("orderId", metaDto.getPartnerOrderNo());
            List<String> desList = new ArrayList<String>();
            desList.add(channelId);
            jPushdto.setContent(contentJson);
            jPushdto.setDes(desList);
            jPushdto.setAlert(car_will_start);
            jPushdto.setTimeToLive(6000);
            jPushdto.setType(1);// 12?
            jPushdto.setUserType(2);// 1:?23:?
            jPushdto.setPushType(1);// 0?1?2tag?
            JPushDtoJson.setBody(jPushdto);
            push2socket(JPushDtoJson);// socket?,????
        }
    }

    /**
     *   ?
     *
     * @param meta
     * @author ?
     */
    public void orderReassign(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        // ???
        CarUser carUserResult = carUserMapper.selectByParam(metaDto.getDriverInfo().getDriverId(), 1);
        if (carUserResult == null) {
            CarUser carUser = new CarUser();
            carUser.setDriverId(metaDto.getDriverInfo().getDriverId());// ?Id
            carUser.setDriverSource(1); // ???
            carUser.setName(metaDto.getDriverInfo().getName());// ???
            carUser.setPhone(metaDto.getDriverInfo().getPhone());// ??
            carUser.setCarNumber(metaDto.getDriverInfo().getLicensePlates());// ??
            carUser.setBusinessType(1);// 
            carUser.setType(1);// 
            carUser.setRegisterDate(new Date());// 
            carUser.setIsValid(1);// ?
            carUser.setCity(result.getCity());// ??
            carUser.setCityId(result.getCityId());// ?Id?Id
            carUser.setCompany("");
            carUser.setHeadPic(metaDto.getDriverInfo().getPhotoSrc());// ??
            carUser.setStatus(1);// 
            carUser.setDelFlag(1);// 
            carUser.setGrade(Double.valueOf(metaDto.getDriverInfo().getDriverRate()));
            if ("34".equals(metaDto.getDriverInfo().getGroupName())) {
                carUser.setCarType(0);
            }
            if ("35".equals(metaDto.getDriverInfo().getGroupName())) {
                carUser.setCarType(1);
            }
            if ("41".equals(metaDto.getDriverInfo().getGroupName())) {
                carUser.setCarType(2);
            }
            carUserMapper.insertUseGeneratedKeys(carUser);
            order.setCarId(carUser.getId());
            order.setCarUserName(metaDto.getDriverInfo().getName());
            order.setCarUserPhone(metaDto.getDriverInfo().getPhone());
        } else {
            // ??
            carUserResult.setName(metaDto.getDriverInfo().getName());// ???
            carUserResult.setPhone(metaDto.getDriverInfo().getPhone());// ??
            carUserResult.setCarNumber(metaDto.getDriverInfo().getLicensePlates());// ??
            carUserResult.setBusinessType(1);// 
            carUserResult.setType(1);// 
            carUserResult.setRegisterDate(new Date());// 
            carUserResult.setIsValid(1);// ?
            carUserResult.setCity(result.getCity());// ??
            carUserResult.setCityId(result.getCityId());// ?Id?Id
            carUserResult.setHeadPic(metaDto.getDriverInfo().getPhotoSrc());// ??
            carUserResult.setCompany("");
            carUserResult.setStatus(1);// 
            carUserResult.setDelFlag(1);// 
            carUserResult.setGrade(Double.valueOf(metaDto.getDriverInfo().getDriverRate()));
            if ("34".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(0);
            }
            if ("35".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(1);
            }
            if ("41".equals(metaDto.getDriverInfo().getGroupName())) {
                carUserResult.setCarType(2);
            }
            carUserMapper.updateByPrimaryKey(carUserResult);
            order.setCarId(carUserResult.getId());
            order.setCarUserName(carUserResult.getName());
            order.setCarUserPhone(carUserResult.getPhone());
            order.setOrderStartDate(new Date());
        }
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("reassign".equals(metaDto.getStatus())) {
            order.setStatus(1);// ?
            order.setOrderStartDate(new Date());
        }
        order.setCarUserChannel(1);// 1
        order.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        ThirdPartyOrder thirdPartyOrder = new ThirdPartyOrder();
        thirdPartyOrder.setPartnerOrderNo(metaDto.getOrderNo());
        thirdPartyOrder.setOrderId(metaDto.getPartnerOrderNo());
        thirdPartyOrder.setMerchantId(1);// ?ID   1:
        thirdPartyOrder.setUpdateDate(new Date());
        thirdPartyOrderMapper.updateByParams(thirdPartyOrder);
        String orderId = metaDto.getPartnerOrderNo();
        // redis????
        RedisUtil.setData("CARUSER_ORDER_TAKING_" + metaDto.getPartnerOrderNo(), metaDto.getPartnerOrderNo(),
                60 * 10);
        // TODO: liusy 16/7/18 17:06  ?
        RedisUtil.delData("bkOrderData-" + result.getOrderId());

        RedisUtil.delData("yydkd-" + orderId);// ???
        RedisUtil.delData("yydkdReject-" + orderId);
        RedisUtil.delData("yywfGrab-" + orderId);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("phone", result.getCustomerPhone());
            map.put("userType", "2");
            List<PushDes> pushDesList = pushDesMapper.selectByPhoneAndUserType(map);
            if (pushDesList == null || pushDesList.isEmpty()) {
                throw new BizException("?");
            }
            PushDes pushDes = pushDesList.get(0);
            if (pushDes == null || StringUtils.isBlank(pushDes.getChannelId())) {
                throw new BizException("?");
            }
            // TODO: 16/7/7 ? ?
            String channelId = pushDes.getChannelId();
            BaseJson<JPushDto> JPushDtoJson = new BaseJson<>();
            JPushDto jPushdto = new JPushDto();
            JSONObject contentJson = new JSONObject();
            contentJson.put("type", "toSend");
            contentJson.put("orderId", orderId);
            jPushdto.setContent(contentJson);
            List<String> desList = new ArrayList<String>();
            desList.add(channelId);
            jPushdto.setDes(desList);
            jPushdto.setAlert("??");
            jPushdto.setTimeToLive(6000);
            jPushdto.setType(1);// 12?
            jPushdto.setUserType(2);//  1:?23:?
            jPushdto.setPushType(1);// 0?1?2tag?
            JPushDtoJson.setBody(jPushdto);
            push2socket(JPushDtoJson);// socket?
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *   ?
     *
     * @param meta
     * @author ?
     */
    public void carUserPay(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        order.setOrderId(metaDto.getPartnerOrderNo());
        // ??????
        if ("offline_pay".equals(metaDto.getStatus())) {
            order.setStatus(2);
        }
        order.setFinishDate(new Date());
        order.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        // ??
        ThirdPartyOrder tpOrder = new ThirdPartyOrder();
        tpOrder.setOrderId(metaDto.getPartnerOrderNo());
        tpOrder.setPartnerOrderNo(metaDto.getOrderNo());
        tpOrder.setUpdateDate(new Date());
        tpOrder.setPayStatus(1);// ??
        tpOrder.setFinishDate(new Date());
        thirdPartyOrderMapper.updateBySelective(tpOrder);
        // ???
        addOrderStatusDetail(result, 2);
        // ?
        PushDes pushDes = pushDesMapper.selectByPhone(result.getCustomerPhone(), "2");
        String channelId = pushDes.getChannelId();
        BaseJson<JPushDto> jPushDtoJson = new BaseJson<JPushDto>();
        JPushDto jpushdto = new JPushDto();
        JSONObject contentJson = new JSONObject();
        contentJson.put("type", "ordedPayed");
        contentJson.put("content", order_payed);
        contentJson.put("orderId", result.getOrderId());
        jpushdto.setContent(contentJson);// ?? Json?
        List<String> desList = new ArrayList<String>();
        desList.add(channelId);
        jpushdto.setDes(desList);// ?? pushType:0 ?1:?,
        // 2:?tag
        jpushdto.setAlert(order_payed);// ??
        jpushdto.setTimeToLive(6000);// ?? ??
        jpushdto.setType(1);// type? 1? 2??
        jpushdto.setUserType(2);//  1:?23:?
        jpushdto.setPushType(1);// 0?1?2tag?
        jPushDtoJson.setBody(jpushdto);
        // socket?,??????
        push2socket(jPushDtoJson);
        System.out.println("push2socket------------??");
    }

    /**
     *   ???/??
     *
     * @param meta
     * @author ?
     */
    public void syCancelOrder(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("sys_canceled".equals(metaDto.getStatus()) || "cs_canceled".equals(metaDto.getStatus())) {
            order.setStatus(3);// ?
        }
        order.setBakstr1(metaDto.getCustomerServiceInfo().getCancelReason());
        order.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        // ???
        addOrderStatusDetail(result, 3);
        // 
        String name = org.springframework.util.StringUtils.isEmpty(result.getCarUserName()) ? ""
                : result.getCarUserName().substring(0, 1);
        sendBySMS(result.getCustomerPhone(),
                "???-" + result.getStartPlace()
                        + "?????" + name + "?"
                        + result.getCarUserPhone() + "",
                1);
        log.info("??:" + metaDto.getPartnerOrderNo());
    }

    /**
     *   ??
     *
     * @param meta
     * @author ?
     */
    public void orderCompleted(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 2) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() == 3) {
            throw new BizException("??");
        }
        // ???
        if (result.getStatus() == 6) {
            throw new BizException("?");
        }
        Order order = new Order();
        order.setOrderId(metaDto.getPartnerOrderNo());
        if ("completed".equals(metaDto.getStatus())) {
            order.setStatus(9);// 
        }
        order.setTotalPrice(Float.valueOf(metaDto.getFeeInfo().getActualPayAmount()));
        order.setActualPrice(Float.valueOf(metaDto.getFeeInfo().getActualPayAmount()));
        order.setUpdateDate(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date sDate = sdf.parse(metaDto.getFeeInfo().getStartDate());
            Date eDate = sdf.parse(metaDto.getFeeInfo().getEndDate());
            order.setTranportStartDate(sDate);
            order.setTranportEndDate(eDate);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        orderMapper.updateByPrimaryKeySelective(order);
        // ???
        addOrderStatusDetail(result, 9);
        // ????
        String customerPhone = result.getCustomerPhone();
        if (customerPhone != null) {
            Customer customer = customerMapper.selectByPrimaryKey(customerPhone);
            if (customer == null) {
                throw new BizException("?");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("phone", customerPhone);
            map.put("userType", "2");
            List<PushDes> pushDesList = pushDesMapper.selectByPhoneAndUserType(map);
            if (pushDesList == null || pushDesList.isEmpty()) {
                throw new BizException("?");
            }
            PushDes pushDes = pushDesList.get(0);
            if (pushDes == null || StringUtils.isBlank(pushDes.getChannelId())) {
                throw new BizException("?");
            }
            String channelId = pushDes.getChannelId();
            BaseJson<JPushDto> JPushDtoJson = new BaseJson<JPushDto>();
            JPushDto jPushdto = new JPushDto();
            JSONObject contentJson = new JSONObject();
            contentJson.put("type", "orderNeedPay");
            contentJson.put("content", car_order_pay_with_app);
            contentJson.put("orderId", metaDto.getPartnerOrderNo());
            contentJson.put("money", metaDto.getFeeInfo().getActualPayAmount());
            jPushdto.setContent(contentJson);
            List<String> desList = new ArrayList<String>();
            desList.add(channelId);
            jPushdto.setDes(desList);
            jPushdto.setAlert(car_order_pay_with_app);
            jPushdto.setTimeToLive(6000);
            jPushdto.setType(1);// 12?
            jPushdto.setUserType(2);//  1:?23:?
            jPushdto.setPushType(1);// 0?1?2tag?
            JPushDtoJson.setBody(jPushdto);
            push2socket(JPushDtoJson);// socket?
        }
        Order order1 = new Order();
        order1.setOrderId(metaDto.getPartnerOrderNo());
        order1.setStatus(8);// 
        order1.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order1);
        // ???
        result.setStatus(9);// // 
        addOrderStatusDetail(result, 8);
    }

    /**
     * ???
     *
     * @param order
     * @param status
     * @author ?
     */
    private void addOrderStatusDetail(Order order, int status) {
        OrderStatusTracking orderStatusTracking = new OrderStatusTracking();
        orderStatusTracking.setOrderId(order.getOrderId());
        orderStatusTracking.setCustomerPhone(order.getCustomerPhone());
        orderStatusTracking.setBusinessType(order.getBusinessType());
        orderStatusTracking.setPreStatus(order.getStatus());
        orderStatusTracking.setNewStatus(status);
        orderStatusTracking.setCreateDate(new Date());
        orderStatusTracking.setOperator(OPERATOR_SHOUQI);//
        orderStatusTrackingMapper.insertSelective(orderStatusTracking);
    }

    /**
     *   ??
     *
     * @param meta
     * @return
     * @author ?
     */
    public BigDecimal printInvoiceApplication(String meta) {
        if (StringUtils.isEmpty(meta)) {
            throw new BizException("meta??");
        }
        MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class);
        Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo());
        if (result == null) {
            throw new BizException("??");
        }
        // ????
        if (result.getStatus() != 2) {
            throw new BizException("??,??");
        }
        BigDecimal invoice = new BigDecimal(0);
        if ("apply_invoice".equals(metaDto.getStatus())) {
            Customer customer = customerMapper.selectOneByPhone(result.getCustomerPhone());
            if (customer != null) {
                if (result.getTotalPrice() < customer.getInvoiceBalance()) {
                    invoice = new BigDecimal(result.getTotalPrice());
                    Double balance = customer.getInvoiceBalance() - invoice.doubleValue();
                    customer.setInvoiceBalance(balance);
                } else {
                    invoice = new BigDecimal(customer.getInvoiceBalance());
                    customer.setInvoiceBalance(0d);
                }
                // ?
                customerMapper.updateByPrimaryKeySelective(customer);
                // ????
                Order order = new Order();
                order.setOrderId(metaDto.getPartnerOrderNo());
                order.setIsInvoice(1);// 
                order.setOtherPrice2(invoice.floatValue());
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
        return invoice;
    }

    /**
     * ????
     * @param orderNo
     * @param partnerOrderNo
     * @param driverId
     * @param sign
     * @param channel
     */
    public void usingTheDriver(String orderNo, String partnerOrderNo, Integer driverId, String sign,
            String channel) {

        if (StringUtils.isBlank(orderNo)) {
            throw new BizException("???");
        }
        if (StringUtils.isBlank(partnerOrderNo)) {
            throw new BizException("????");
        }
        if (driverId == null) {
            throw new BizException("?ID?");
        }
        String data = RedisUtil.getData("RETURN_CODE_ERROR_" + orderNo);
        if (StringUtils.isNotBlank(data)) {
            throw new BizException("???");
        }
        CarUser carUser = carUserMapper.selectByPrimaryKey(driverId);
        if (carUser == null) {
            throw new BizException("??");
        }
        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        Date bookDate = order.getBookDate();
        Long seconds = 24 * 60 * 60l;
        if (bookDate != null) {
            seconds = (bookDate.getTime() - System.currentTimeMillis()) / 1000;
            seconds += 4 * 60 * 60;
        }
        Order parameterOrder = new Order();
        parameterOrder.setOrderId(orderNo);
        parameterOrder.setCarId(driverId);
        parameterOrder.setBusinessType(carUser.getBusinessType());
        parameterOrder.setOrderType(6);//?(0.app1.allcenter2.app3.callcenter4.??5.?6.)
        parameterOrder.setOrderSource(4);//???0 android1 IOS2 wechat3 callcenter4 
        //        parameterOrder.setCarType(carUser.getCarType() + "");
        parameterOrder.setCarUserPhone(carUser.getPhone());
        parameterOrder.setCarUserName(carUser.getName());
        parameterOrder.setStatus(1);//?01?2?3? ......
        parameterOrder.setUpdateDate(new Date());
        parameterOrder.setOrderStartDate(new Date());
        int i = orderMapper.updateByPrimaryKeySelective(parameterOrder);
        if (i != 1) {
            throw new BizException("?");
        }

        //????
        OrderStatusTracking orderStatusTracking = new OrderStatusTracking();
        orderStatusTracking.setOrderId(orderNo);
        orderStatusTracking.setCarUserPhone(carUser.getPhone());
        orderStatusTracking.setCustomerPhone(order.getCustomerPhone());
        orderStatusTracking.setBusinessType(order.getBusinessType());
        orderStatusTracking.setPreStatus(order.getStatus());
        orderStatusTracking.setNewStatus(1);
        orderStatusTracking.setCreateDate(new Date());
        orderStatusTracking.setOperator(4);//?01?2?? 3??4
        int i1 = orderStatusTrackingMapper.insertSelective(orderStatusTracking);
        if (i1 != 1) {
            throw new BizException("????");
        }
        ThirdPartyOrder thirdPartyOrder = thirdPartyOrderMapper.selectByOrderIdAndPartnerOrderNo(orderNo,
                partnerOrderNo);
        thirdPartyOrder.setDriverInfoNoticeCallBack(1);
        thirdPartyOrder.setDriverId(driverId);
        thirdPartyOrderMapper.updateByPrimaryKey(thirdPartyOrder);
        RedisUtil.setData(Constants.SQORDER_DZCAR_ + orderNo, driverId + "", seconds.intValue());
    }

    public void noticeDriver(String orderNo, String partnerOrderNo, BigDecimal amount) {
        if (orderNo == null) {
            throw new BizException("?orderNo");
        }
        Order order = orderMapper.selectByPrimaryKey(orderNo);
        if (order == null) {
            throw new BizException("??");
        }
        if (partnerOrderNo == null) {
            throw new BizException("?partnerOrderNo");
        }
        if (amount == null) {
            throw new BizException("?amount");
        }
        if (amount.compareTo(BigDecimal.valueOf(0)) != 1) {//-1? 0 1  ???0??
            throw new BizException("??0");
        }
        ThirdPartyOrder thirdPartyOrder = thirdPartyOrderMapper.selectByOrderIdAndPartnerOrderNo(orderNo,
                partnerOrderNo);
        if (thirdPartyOrder == null) {
            throw new BizException("??");
        }
        thirdPartyOrder.setPayAmount(amount);
        thirdPartyOrder.setPayType(2);
        thirdPartyOrder.setPayStatus(1);
        if (!(thirdPartyOrderMapper.updateByPrimaryKeySelective(thirdPartyOrder) > 0)) {
            throw new BizException("??update");
        }
    }

    public static final String GRAP_ORDER_RESULT = "grap_order_result_";// ??
    public static final String ORDER_STATUS_GRABED_VALUE = "grabed";// ??
    public static final String REDIS_ORDER_STATUS = "order_status_";
    public static final String SHOUYUE_RECIVE_KEY = "SHOUYUE_RECIVE_KEY_";

    public void stopAssNotice(String orderNo, String partnerOrderNo) {
        RedisUtil.setData(REDIS_ORDER_STATUS + orderNo, orderNo, 20 * 60);
    }
}