package com.bohuikeji.delivery.backstage.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.controller.open.KeRuYunApi;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountRecord;
import com.bohuikeji.delivery.backstage.entity.open.vo.CourierVo;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.mapper.TOrderMapper;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.KDHundredServer;
import com.bohuikeji.delivery.backstage.service.third.SfExpressServer;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.util.AppPush;
import com.bohuikeji.delivery.backstage.util.CustomerAppPush;
import com.bohuikeji.delivery.backstage.util.OrderUtils;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import com.bohuikeji.delivery.backstage.util.capacity.HllUtils;
import com.bohuikeji.delivery.backstage.util.capacity.KDHundredUtils;
import com.bohuikeji.delivery.backstage.util.capacity.ShanSongUtils;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.TFranchiseeInformation;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.sys.SysError;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.exception.WebVerifiedException;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * <p>
 * 订单记录表 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-08-22
 */
@Service
@Slf4j
public class TOrderServiceImpl extends ServiceImplBase<TOrderMapper, TOrder> implements ITOrderService {

    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITFranchiseeInformationService franServer;
    @Autowired
    ITNewsService newsService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ITConfigService configService;
    @Autowired
    ITFranchiseeInformationService franService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITCustomerBigService customerBigService;
    @Autowired
    ITDiscountRecordService discountRecordService;
    @Autowired
    ITDiscountOrderService discountOrderService;
    @Autowired
    ITMaltFieldService maltFieldService;

    @Autowired
    ThirdUtils thirdUtils;


    /**
     * 下单
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveplace(TOrder order) {
        AddressVo sendVo=order.getMailingAddress().fillAddress();
        AddressVo receiveVo=order.getReceiptAddress().fillAddress();
        if(sendVo==null){
            throw new WebVerifiedException("参数校验错误，寄件地址格式错误！");
        }
        if(receiveVo==null){
            throw new WebVerifiedException("参数校验错误，收件地址格式错误！");
        }
        order.setMailingAddress(sendVo);
        order.setReceiptAddress(receiveVo);
        order = itOrderService.moneySumNew(order);
        order.setOrderNum(NumberUtils.get("A"));
        //两地之间的距离
        order.setOrderDistance(Math.round(MapUtils.getDistanceKm(order.getMailingAddress(),order.getReceiptAddress())));
        order.setOrderDistanceDec(MapUtils.getDistanceKma(order.getMailingAddress(),order.getReceiptAddress()));
        //计算预计时间
        order.setOrderExpectTime(LocalDateTime.now().plusMinutes(Math.round(order.getOrderDistance()/0.3334d)));
        //order.setOrderDistance(DistanceUtils.getDistance(mailingAddress.getLng(),mailingAddress.getLat(),receiptAddress.getLng(),receiptAddress.getLat()));
       //累计客户的下单次数
        TCustomer tCustomer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_id",order.getPlayerId()));
        tCustomer.setOrderFrequency(tCustomer.getOrderFrequency()+1);
        customerService.updateById(tCustomer);
        order.setFranId(franServer.checkPio(order.getMailingAddress()).getFranId());
        return save(order);
    }

    @Override
    public boolean savePlaceNew(TOrder order) {
        AddressVo sendVo=order.getMailingAddress().fillAddress();
        AddressVo receiveVo=order.getReceiptAddress().fillAddress();
        if(sendVo==null){
            throw new WebVerifiedException("参数校验错误，寄件地址格式错误！");
        }
        if(receiveVo==null){
            throw new WebVerifiedException("参数校验错误，收件地址格式错误！");
        }
        order.setMailingAddress(sendVo);
        order.setReceiptAddress(receiveVo);
        order = itOrderService.moneySumNew(order);
        //此处修改为，如果已有订单号则不在生成，避免上层业务指定了订单而造成覆盖
        //已使用场景一：对接海底捞客如云平台，直接使用对方系统的订单号，自身系统不在生成
        if(StringUtils.isBlank(order.getOrderNum())){
            order.setOrderNum(NumberUtils.get("A"));
        }
        //累计客户的下单次数
        TCustomer tCustomer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_id",order.getPlayerId()));
        tCustomer.setOrderFrequency(tCustomer.getOrderFrequency()+1);
        customerService.updateById(tCustomer);
        order.setFranId(franServer.checkPio(order.getMailingAddress()).getFranId());
        order.setContactPhone(tCustomer.getCustomerPhone());
        order.setOrderStatus("待接单");
        order.setOrderActualPrice(order.getOrderExpectPrice());//订单最终实际收入
        order.setOrderFactPrice(order.getOrderFactPrice().add(order.getOrderExpectPrice()));
        if(order.getReleaseId()!=0){//普通优惠卷使用
            TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("usage_status","未使用").eq("release_id",order.getReleaseId()).eq("customer_id",order.getPlayerId()));
            if(order.getTotalOrderAmount().compareTo(discountRecord.getStartAmount()) < 0){
                throw new WebVerifiedException("订单金额未满足要求不可使用此“优惠卷”!");
            }
        }
        TOrder tOrder = itOrderService.getByNum(order.getOrderNum());
        if(tOrder != null){
            throw new WebVerifiedException("订单保存成功！");
        }
        return save(itOrderService.estimate(order));
    }

    @Override
    public TOrder initialOrder(TOrder order) {
        AddressVo sendVo=order.getMailingAddress().fillAddress();
        AddressVo receiveVo=order.getReceiptAddress().fillAddress();
        if(sendVo==null){
            throw new WebVerifiedException("参数校验错误，寄件地址格式错误！");
        }
        if(receiveVo==null){
            throw new WebVerifiedException("参数校验错误，收件地址格式错误！");
        }
        order.setMailingAddress(sendVo);
        order.setReceiptAddress(receiveVo);
        //此处修改为，如果已有订单号则不在生成，避免上层业务指定了订单而造成覆盖
        //已使用场景一：对接海底捞客如云平台，直接使用对方系统的订单号，自身系统不在生成
        if(StringUtils.isBlank(order.getOrderNum())){
            order.setOrderNum(NumberUtils.get("A"));
        }
        order = itOrderService.moneySumNew(order);
        order.setFranId(franServer.checkPio(order.getMailingAddress()).getFranId());
        if(order.getReleaseId()!=0){//普通优惠卷使用
            TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("usage_status","未使用").eq("release_id",order.getReleaseId()).eq("customer_id",order.getPlayerId()));
            if(order.getTotalOrderAmount().compareTo(discountRecord.getStartAmount()) < 0){
                throw new WebVerifiedException("订单金额未满足要求不可使用此“优惠卷”!");
            }
        }
        TOrder tOrder = itOrderService.estimate(order);
        return tOrder;
    }

    /**
     * 算出订单的金额
     * 货物类型金额
     * 车辆类型金额
     * 服务类型金额
     * 货物价值金额
     * 距离金额
     * 重量金额
     */
    @Override
    @Transactional
    public TOrder moneySum(TOrder order) {
        //车俩类型选择
        SysConfig vehicleCfg=sysConfigService.getById(order.getVehicleConfigId());
        try{
            if("待接单".equals(order.getOrderStatus())){
                order.setOrderDistance(Math.round(MapUtils.getDistanceKm(order.getMailingAddress(),order.getReceiptAddress())));
                order.setOrderDistanceDec(MapUtils.getDistanceKma(order.getMailingAddress(),order.getReceiptAddress()));
            }

        }catch (Exception e){
            log.error("订单距离计算失败，取消");
            return order;
        }
        if(order.getCargoWeight()==null){
            log.error("订单重量为null，计算失败");
            return order;
        }
        if(order.getCargoWeight()<Integer.parseInt(vehicleCfg.getConfigDataOne())){
            order.setCargoWeight(Integer.valueOf(vehicleCfg.getConfigDataOne()));
        }
        //重量差(保证整数)
        int weight=order.getCargoWeight()-Integer.parseInt(vehicleCfg.getConfigDataOne());
        order.setOrderNorms(vehicleCfg.getConfigName());
        //如果为电动车则按配送类型计算
        if("car_type_ddc".equals(vehicleCfg.getConfigGroup())){
            //保证重量差不为负
            weight= Math.max(weight, 0);
            //运输方式
            SysConfig wayCfg=sysConfigService.getById(order.getWayConfigId());
            //货物类型
            SysConfig cargoCfg=sysConfigService.getById(order.getCargoConfigId());
            //配送方式的默认价格
            BigDecimal defaultPrice=new BigDecimal(wayCfg.getConfigDefault());
            //配送距离差(保证整数)
            int distance=order.getOrderDistance()-Integer.parseInt(wayCfg.getConfigDataOne());
            distance= Math.max(distance, 0);
            //重量计费
            BigDecimal weightPrice=new BigDecimal(weight).multiply(new BigDecimal(wayCfg.getConfigDataTwo()));
            //距离计费
            BigDecimal distancePrice=new BigDecimal(distance).multiply(new BigDecimal(wayCfg.getConfigValue()));
            //物品类型计费
            BigDecimal cargoPrice=new BigDecimal(cargoCfg.getConfigValue());
            //最终金额=默认价格+重量计费+距离计费+物品类型计费
            return order.setOrderExpectPrice(defaultPrice.add(weightPrice).add(distancePrice).add(cargoPrice));
        }
        else {
            //保证重量差不为负
            weight=weight<=0?Integer.valueOf(vehicleCfg.getConfigDataOne()):order.getCargoWeight();
            //重量计费
            BigDecimal weightPrice=new BigDecimal(weight).multiply(new BigDecimal(vehicleCfg.getConfigDataTwo()));
            //距离计费
            BigDecimal distancePrice=new BigDecimal(order.getOrderDistance()).multiply(new BigDecimal(vehicleCfg.getConfigValue()));
            //最终金额=默认价格+重量计费+距离计费
            return order.setOrderExpectPrice(weightPrice.add(distancePrice));
        }
    }


    @Override
    public TOrder moneySumNew(TOrder order) {
        //预计取件时间
        order.setSurplusPickTime(itOrderService.getSurplusTime(order));
        order.setOrderDistance(Math.round(MapUtils.getDistanceKm(order.getMailingAddress(),order.getReceiptAddress())));
        order.setOrderDistanceDec(MapUtils.getDistanceKma(order.getMailingAddress(),order.getReceiptAddress()));
        order.setFranId(franServer.checkPio(order.getMailingAddress()).getFranId());
        if(!orderComp(order)){
            return order;
        }
        if(order.getCargoWeight()==null||order.getCargoWeight()<1){
            order.setCargoWeight(1);
        }
        Integer dfConfId=5832;
        //快递模式计费
        if(dfConfId.equals(order.getWayConfigId())){
            log.info("【进入第三方计费计算里了】");
            //快递100计费
            if (order.getThird()&&StringUtils.isNotBlank(order.getThirdName()) && KDHundredServer.NAME.equals(order.getThirdName())){
                JSONObject sfRes= KDHundredUtils.kdOrderInquiry(order);
                if (!sfRes.getString("returnCode").equals("200")){
                    return order;
                }
                JSONObject body=sfRes.getJSONObject("data");
                log.error("第三方订单：第三方名字：{}，快递100订单推送信息：{}","圆通",body);
                if (sfRes!=null){
                    order.setOrderExpectPrice(body.getBigDecimal("price"));
                }
            }
            order.setThirdName("KD");
            order.setTotalOrderAmount(order.getOrderExpectPrice().setScale(2, RoundingMode.HALF_UP));
            order.setOrderExpectPrice(order.getOrderExpectPrice().setScale(2,RoundingMode.DOWN));
            JSONObject jsonObject = configService.getPremiumJson(order.getFranId(),"premium_type",order.getPlayerId());
            order.setExpenseDetails(orderexpenseDetails(order.getOrderExpectPrice(),new BigDecimal("0.00"),new BigDecimal("0.00"),new BigDecimal("0.00"),new BigDecimal("0.00"),new BigDecimal("0.00"),order.getOrdertTip(),order.getPrefAmount(),jsonObject,order.getSysPrice(),order.getInsuredPrice(),order.getPreName(),new BigDecimal("0.00")));
            return order;
        }
        //获取当前订单选择的车俩类型选择    大车需要根据车辆类型重新查询车辆id
        TConfig vehicleCfg=configService.getByIdWithCustomer(order.getVehicleConfigId(),order.getPlayerId(),order.getFranId());
        if(vehicleCfg==null) {
            vehicleCfg = configService.getConfigByMark(order.getVehicleConfigId(),order.getFranId());
            //return order;
        }
        Integer vehicleWeight=5;
        JSONObject vehicleCfgValue=vehicleCfg.getConfigValue();
        if (vehicleCfgValue==null){
            log.error("【计费错误】车辆首重计费项异常：[{}]",vehicleCfg);
        }
        else {
            //获取当前车辆首重配置
            vehicleWeight=vehicleCfg.getConfigValue().getInteger("首重(KG)");
        }
        //根据选择车型修改订单最低首重
        if(order.getCargoWeight()<vehicleWeight){
            order.setCargoWeight(vehicleWeight);
        }
        //计算重量差(保证整数)
        int weight=order.getCargoWeight()-vehicleWeight;
        //电动车为小件
        order.setOrderNorms(vehicleCfg.getConfigName());
        //BigDecimal allDiscount=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        if (vehicleCfg.getConfigGroup()==null){
            log.error("【订单计费信息不完整】缺少车辆信息");
            return order;
        }
        String[] vehicles={"电动车-电力","电动车","小件"};
        //电动车
        if(vehicleCfg.getConfigGroup().contains("car_type_ddc") || Arrays.asList(vehicles).contains(order.getOrderNorms())){
            log.info("【进入小车待计费订单参数】");
            //运输方式
            TConfig wayCfg=configService.getByIdWithCustomer(order.getWayConfigId(),order.getPlayerId(),order.getFranId());
            //跨城直配给默认值
            /*if("跨城寄付".equals(order.getWayName())){
                order.setWayConfigId(21);
                wayCfg=configService.getById(21);
            }*/
            if(wayCfg==null) {
                return order;
            }
            //货物类型
            TConfig cargoCfg=configService.getByIdWithCustomer(order.getCargoConfigId(),order.getPlayerId(),order.getFranId());
            if(cargoCfg==null) {
                return order;
            }
            //配送方式的默认价格
            BigDecimal defaultPrice=new BigDecimal(wayCfg.getConfigValue().getString("默认费用(元)"));
            //配送距离差(保证整数)
            int distance=order.getOrderDistance()-wayCfg.getConfigValue().getInteger("默认距离(公里)");
            distance= Math.max(distance, 0);
            //重量计费
            BigDecimal weightPrice=new BigDecimal(weight).multiply(new BigDecimal(wayCfg.getConfigValue().getString("续重(元/KG)")));
            //距离计费
            BigDecimal distancePrice=new BigDecimal(distance).multiply(new BigDecimal(wayCfg.getConfigValue().getString("超出默认距离续费(元/公里)")));
            //物品类型计费
            BigDecimal cargoPrice=new BigDecimal(cargoCfg.getConfigValue().getString("加价(元)"));
            //货物价值计费（保价计费）
            if(order.getInsured()){
                BigDecimal insuredPrice = orderInsured(order.getWorthName());
                order.setInsuredPrice(insuredPrice);
            }
            //最终金额=默认价格+重量计费+距离计费+物品类型计费
            order.setOrderExpectPrice(defaultPrice.add(weightPrice).add(distancePrice).add(cargoPrice));
            //远距离补充服务费
            BigDecimal supplPrice=replenishPrice(order);
            //溢价费用
            JSONObject jsonObject = configService.getPremiumJson(order.getFranId(),"premium_type",order.getPlayerId());
            log.error("下单计费加盟商模板：{}",cargoCfg.getFranName());
            log.error("默认计费金额：{}",defaultPrice);
            log.error("物品类型计费：{}",cargoPrice);
            log.error("重量计费金额：{},超出重量：{},续重费：{}",weightPrice,weight,vehicleCfg.getConfigValue().getString("续重(元/KG)"));
            log.error("距离计费金额：{},超出距离：{},超距费：{}",distancePrice,distance,vehicleCfg.getConfigValue().getString("距离(元/公里)"));
            log.error("订单溢价明细：{}",jsonObject);
            order = bigShopShanSongPrice(order);
            order.setOrderExpectPrice(order.getOrderExpectPrice()
                    .add(order.getInsuredPrice())
                    .add(bigCustomerAddPrice(order.getPlayerId())));
            //订单总金额
            order.setTotalOrderAmount(order.getOrderExpectPrice().add(jsonObject.getBigDecimal("总溢价")).add(supplPrice).setScale(2, RoundingMode.DOWN));
            //会员优惠、优惠卷金额
            order = discountRecordService.getDisOrder(order);
            //小费大于0计算新的结算金额
            if(order.getOrdertTip().compareTo(new BigDecimal("0.00")) > 0){
                order.setOrderExpectPrice(order.getOrderExpectPrice().add(order.getOrdertTip()).setScale(2, RoundingMode.HALF_UP));
                order.setTotalOrderAmount(order.getTotalOrderAmount().add(order.getOrdertTip()));
            }
            if(order.getDisId() !=0){//派送员取件核对信时预估金额需要减去已用优惠卷的金额
                order.setOrderExpectPrice(order.getTotalOrderAmount().subtract(order.getPrefAmount()).setScale(2, RoundingMode.HALF_UP));
            }
            //计算预计送达时间
            order.setOrderExpectTime(itOrderService.getExpectTime(order,0));
            order.setOrderExpectPrice(order.getOrderExpectPrice().add(jsonObject.getBigDecimal("总溢价")).add(supplPrice).setScale(1,RoundingMode.DOWN));
            order.setExpenseDetails(orderexpenseDetails(order.getOrderExpectPrice(),defaultPrice,weightPrice,distancePrice,cargoPrice,new BigDecimal("0.00"),order.getOrdertTip(),order.getPrefAmount(),jsonObject,order.getSysPrice(),order.getInsuredPrice(),order.getPreName(),supplPrice));
            return order;
        }
        //其他为货车
        else {
            log.info("【进入大车待计费订单参数】");
            if(!"car_type_lashuo".equals(vehicleCfg.getConfigGroup())){
                throw new WebVerifiedException("该账户已绑定计费模板，请到“出租拉货”下单!");
            }
            //跨城直配给默认值
            if("跨城直配".equals(order.getWayName())){
                TConfig wayCfg=configService.getOne(new QueryWrapper<TConfig>().eq("config_name",order.getWayName()));
                order.setWayConfigId(wayCfg.getId());
            }
            //搬运计费
            BigDecimal carryPrice= new BigDecimal("0.00");
            if("帮助搬运".equals(order.getCarryName())){
                TConfig carrys=configService.getOne(new QueryWrapper<TConfig>().eq("config_name",order.getCarryName()));
                carryPrice = new BigDecimal(carrys.getConfigValue().getInteger("搬运费用(元)"));
            }else {
                carryPrice = new BigDecimal("0.00");
            }
            int distance=order.getOrderDistance()-vehicleCfg.getConfigValue().getInteger("默认距离(公里)");
            distance= Math.max(distance, 0);
            //车辆的默认价格
            BigDecimal defaultPrice =new BigDecimal(vehicleCfg.getConfigValue().getString("默认费用"));
            //重量计费
            BigDecimal weightPrice=new BigDecimal(weight).multiply(new BigDecimal(vehicleCfg.getConfigValue().getString("续重(元/KG)")));
            //距离计费
            BigDecimal distancePrice=new BigDecimal(distance).multiply(new BigDecimal(vehicleCfg.getConfigValue().getString("距离(元/公里)")));
            //最终金额=默认价格+重量计费+距离计费
            order.setOrderExpectPrice(defaultPrice.add(weightPrice).add(distancePrice).add(carryPrice));
            TConfig cargoCfg=configService.getByIdWithCustomer(order.getVehicleConfigId(),order.getPlayerId(),order.getFranId());
            log.error("下单计费加盟商模板：{}",cargoCfg.getFranName());
            log.error("默认计费金额：{}",defaultPrice);
            log.error("搬运计费金额：{}",carryPrice);
            log.error("重量计费金额：{},超出重量：{},续重费：{}",weightPrice,weight,vehicleCfg.getConfigValue().getString("续重(元/KG)"));
            log.error("距离计费金额：{},超出距离：{},超距费：{}",distancePrice,distance,vehicleCfg.getConfigValue().getString("距离(元/公里)"));
            TFranchiseeInformation franchiseeInformation = franService.getOne(new QueryWrapper<TFranchiseeInformation>().eq("fran_id",order.getFranId()));
            log.error("加盟商名称：{},加盟商推送开关：{}",franchiseeInformation.getFranName(),franchiseeInformation.getFranPush());
            if(!"关闭".equals(franchiseeInformation.getFranPush())){
                Integer cityId = HllUtils.getCityId(order.getLocation());
                log.info("【获取下单人所属城市Id】城市：{},下单人：{}",cityId,order.getPlayerId());
                if(cityId == null){
                    throw new WebVerifiedException("该城市暂未开通大车配送服务!");
                }
                order.setThirdName("HLL");
                order.setThird(false);
                order.setTravelType(vehicleCfg.getConfigMark());
                order.setHuoToken(this.getHuolalaToken());
                order.setCityId(cityId);
                BigDecimal huolalaPrice = huoLalaOrderPrice(order);//货拉拉
                log.info("预估计费金额：{},货拉拉金额：{}",order.getOrderExpectPrice(),huolalaPrice);
                order.setOrderExpectPrice(order.getOrderExpectPrice().add(huolalaPrice));
            }
            //订单总金额
            order.setTotalOrderAmount(order.getOrderExpectPrice().setScale(2, RoundingMode.DOWN));
            //订单优惠
            order = discountRecordService.getDisOrder(order);
            //溢价费用
            JSONObject jsonObject = configService.getPremiumJson(order.getFranId(),"premium_type",order.getPlayerId());
            //小费大于0计算新的结算金额
            if(order.getOrdertTip().compareTo(new BigDecimal("0.00")) > 0){
                order.setOrderExpectPrice(order.getOrderExpectPrice().add(order.getOrdertTip()).setScale(2, RoundingMode.HALF_UP));
                order.setTotalOrderAmount(order.getTotalOrderAmount().add(order.getOrdertTip()).setScale(2, RoundingMode.HALF_UP));
            }
            //派送员取件核对信时预估金额需要减去已用优惠卷的金额
            if(order.getDisId()!=0){
                order.setOrderExpectPrice(order.getTotalOrderAmount().subtract(order.getPrefAmount()).setScale(2, RoundingMode.HALF_UP));
            }
            //计算预计送达时间
            order.setOrderExpectTime(itOrderService.getExpectTime(order,0));
            order.setOrderExpectPrice(order.getOrderExpectPrice().setScale(1,RoundingMode.DOWN));
            order.setExpenseDetails(orderexpenseDetails(order.getOrderExpectPrice(),defaultPrice,weightPrice,distancePrice,null,carryPrice,order.getOrdertTip(),order.getPrefAmount(),jsonObject,order.getSysPrice(),order.getInsuredPrice(),order.getPreName(),new BigDecimal("0.00")));
            return order;
        }
    }

    /**
     *
     * @param defaultPrice 默认价格
     * @param weightPrice 重量价格
     * @param distancePrice 距离价格
     * @param cargoPrice 货物类型价格
     * @param carryPrice 搬运费
     * @param ordertTip 前置小费
     * @param prefAmount 优惠价格
     * @return
     */
    private JSONObject orderexpenseDetails(BigDecimal orderExpectPrice,BigDecimal defaultPrice,BigDecimal weightPrice,BigDecimal distancePrice,BigDecimal cargoPrice,BigDecimal carryPrice,BigDecimal ordertTip,BigDecimal prefAmount,JSONObject jsonObject,BigDecimal sysPrice,BigDecimal InsuredPrice,String preName,BigDecimal supplPrice){
        //log.info("#########################计算计费明细###############################");
        //log.info("##################:{}",prefAmount);
        JSONObject allCost = new JSONObject(true);
        JSONArray jsonArray = new JSONArray();
        JSONObject cost1 = new JSONObject();
        cost1.put("key","起价：");
        cost1.put("value",defaultPrice);
        JSONObject cost2 = new JSONObject();
        cost2.put("key","续重：");
        cost2.put("value",weightPrice);
        JSONObject cost3 = new JSONObject();
        cost3.put("key","超距：");
        cost3.put("value",distancePrice);
        JSONObject cost4 = new JSONObject();
        cost4.put("key","品类：");
        cost4.put("value",cargoPrice);
        JSONObject cost5 = new JSONObject();
        cost5.put("key","搬运：");
        cost5.put("value",carryPrice);
        JSONObject cost6 = new JSONObject();
        cost6.put("key","小费：");
        cost6.put("value",ordertTip);
        JSONObject cost7 = new JSONObject();
        if(StringUtils.isNotBlank(preName)){
            cost7.put("key",preName);
            cost7.put("value",prefAmount);
        }else {
            cost7.put("key","优惠：");
            cost7.put("value",prefAmount);
        }
        JSONObject cost8 = new JSONObject();
        cost8.put("key","保价：");
        cost8.put("value",InsuredPrice);
        jsonArray.add(cost1);
        jsonArray.add(cost2);
        jsonArray.add(cost3);
        jsonArray.add(cost4);
        jsonArray.add(cost5);
        jsonArray.add(cost6);
        jsonArray.add(cost7);
        jsonArray.add(cost8);
        JSONArray detailedJson = null;
        if(jsonObject !=null){
            detailedJson = jsonObject.getJSONArray("detailed");
        }else {
            detailedJson = new JSONArray();
        }

        JSONObject cost9 = new JSONObject();
        cost9.put("key","平台溢价：");
        cost9.put("value",sysPrice);
        JSONObject cost10 = new JSONObject();
        cost10.put("key","远距离服务费：");
        cost10.put("value",supplPrice);
        detailedJson.add(cost9);
        detailedJson.add(cost10);
        allCost.put("expensesCost",jsonArray);
        allCost.put("premiumCost",detailedJson);
        return allCost;
    }

    /**
     * 运营计费配置
     * @param worthName
     * @return
     */
    private BigDecimal orderInsured(String worthName){
        BigDecimal worthPrice = new BigDecimal(worthName.replace("元",""));
        BigDecimal insuredPrice=new BigDecimal("0.00");
        if(worthPrice.compareTo(new BigDecimal("10000")) > 0){
            insuredPrice = worthPrice.divide(new BigDecimal("200"),2, RoundingMode.DOWN);
            return insuredPrice;
        }
        for (SysConfig conf : sysConfigService.getListByGroup("order_Insured_price")) {
            //判断当前订单价格是否在区间内
            if (worthPrice.compareTo(new BigDecimal(conf.getConfigDataOne())) > 0 && worthPrice.compareTo(new BigDecimal(conf.getConfigDataTwo()))<1){
                insuredPrice = new BigDecimal(conf.getConfigValue());
                return insuredPrice;
            }
        }
        return insuredPrice;
    }

    /**
     * 判断订单二次计费时，订单的各项计费参数是否变更
     * @param order 前端传入订单实体
     * @return 已变更返回 true;未变更返回false
     */
    private boolean orderComp(TOrder order){
        if(order.getOrderId()==null){
            return true;
        }
        TOrder newOrder=itOrderService.getById(order.getOrderId());
        if(newOrder.getCargoConfigId()==null){
            return true;
        }
        //比较重量是否变换
        if(!newOrder.getCargoWeight().equals(order.getCargoWeight())){
            return true;
        }//比较距离是否变化
        if(!newOrder.getOrderDistance().equals(order.getOrderDistance())){
            return true;
        }//比较车辆是否变化
        if(!newOrder.getVehicleConfigId().equals(order.getVehicleConfigId())){
            return true;
        }//比较运输方式是否变化
        if (!newOrder.getWayConfigId().equals(order.getWayConfigId())){
            return true;
        }//比较物品类型是否变化
        if (!newOrder.getCargoConfigId().equals(order.getCargoConfigId())){
            return true;
        }
        return false;
    }

    /**
     * 货拉拉订单预估计价
     */
    private BigDecimal huoLalaOrderPrice(TOrder order){
        BigDecimal totalPrice=new BigDecimal("0.00");
        JSONObject hulalaPrice= HllUtils.getEpriceCalculate(order);
        totalPrice = hulalaPrice.getBigDecimal("total_price_fen").divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
        order.setThirdPrice(totalPrice);
        //利润=订单金额-货拉拉
        log.info("【货拉拉订单预估金额】：{}",totalPrice);
        BigDecimal subPrice=order.getOrderExpectPrice().subtract(totalPrice);
        for (SysConfig conf : sysConfigService.getListByGroup("order_price_js_huo")) {
            //判断当前订单价格是否在区间内
            if (order.getOrderExpectPrice().compareTo(new BigDecimal(conf.getConfigDataOne()))>-1){
                if (order.getOrderExpectPrice().compareTo(new BigDecimal(conf.getConfigDataTwo()))<1){
                    //在区间内如果，订单利润高于配置价格则不再加价，返回0
                    BigDecimal dfPrice=order.getOrderExpectPrice().multiply(new BigDecimal(conf.getConfigValue()));
                    log.error("货拉拉价格区间：{}，起始金额：{}，结束金额：{}，利润：{}",conf.getConfigKey(),conf.getConfigDataOne(),conf.getConfigDataTwo(),dfPrice);
                    if (subPrice.compareTo(new BigDecimal("15"))>0){
                        log.error("货拉拉利润差价:{}大于15元，不再加价。",subPrice);
                        return new BigDecimal("0.00");
                    }
                    BigDecimal rs=subPrice.multiply(new BigDecimal("-1")).add(dfPrice);
                    log.error("货拉拉利润差价：{}低于15元，订单价格：{}，要求利润：{}，返回加价:{}",subPrice,order.getOrderExpectPrice(),dfPrice,rs);
                    //否则补齐利润为配置价格
                    //order.setOrderExpectPrice(order.getOrderExpectPrice().add(rs));
                    return rs;
                }
            }
        }
        //未找到区间配置，给默认20元利润
        //order.setOrderExpectPrice(subPrice.multiply(new BigDecimal("-1")).add(new BigDecimal("20.00")).add(order.getOrderExpectPrice()));
        return (subPrice.multiply(new BigDecimal("-1")).add(new BigDecimal("20.00")));
    }

    /**
     * 平台管理的加盟商闪送计费
     * @param order
     * @return
     */
    private TOrder bigShopShanSongPrice(TOrder order){
        BigDecimal bigDecimal=new BigDecimal("0");
        TCustomer customer=customerService.getById(order.getPlayerId());
        TFranchiseeInformation franchiseeInformation = franService.getOne(new QueryWrapper<TFranchiseeInformation>().eq("fran_id",order.getFranId()));
        if(franchiseeInformation == null){
            return order;
        }
        if("加盟商".equals(franchiseeInformation.getFranController())){
            return order;
        }
        if("关闭".equals(franchiseeInformation.getFranPush())){
            return order;
        }
        //已经绑定商家模板的订单不添加溢价费
        if(StringUtils.isNotBlank(customer.getTemplateId())){
            return order;
        }
        BigDecimal price = null;
        if("平台".equals(franchiseeInformation.getFranController())){
            //获取闪送价格
            APIEntity<JSONObject> res= ShanSongUtils.orderQueryBilling(order);
            if (res==null||!(res.checkSuccess())){
                return order;
            }
            JSONObject body=res.getBody();
            //闪送订单实付价格
            price=new BigDecimal(body.getString("totalFeeAfterSave")).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);
            if("商家用户".equals(customer.getCustomerType()) && StringUtils.isBlank(customer.getTemplateId())){
                BigDecimal shansongPrice = price.multiply(new BigDecimal("0.98")).setScale(2,  RoundingMode.DOWN);
                BigDecimal youhuiPrice = price.subtract(shansongPrice).setScale(2,  RoundingMode.DOWN);
                if(order.getOrderExpectPrice().compareTo(shansongPrice) > 0){
                    BigDecimal tallPrice = order.getOrderExpectPrice().subtract(shansongPrice).setScale(2,RoundingMode.DOWN);
                    order.setPrefAmount(order.getPrefAmount().add(youhuiPrice).add(tallPrice));
                    log.error("计算优惠后的的金额:预估金额：{},闪送金额：{}，优惠金额：{},差价金额：{},总优惠金额：{}",order.getOrderExpectPrice(),price,youhuiPrice,tallPrice,order.getPrefAmount());
                }else {
                    BigDecimal lowPrice = shansongPrice.subtract(order.getOrderExpectPrice());
                    order.setSysPrice(lowPrice);
                }
                log.info("平台代管理的计费,客户手机号：{},客户类型：{}，原金额：{},商户9.8折后金额：{},优惠金额：{}",customer.getCustomerPhone(),customer.getCustomerType(),price,shansongPrice,price.multiply(new BigDecimal("0.02")));
                order.setOrderExpectPrice(shansongPrice);
                log.error("计算优惠后的的金额111:预估金额：{}",order.getOrderExpectPrice());
                return order;
            }
            log.error("#######计算计费时的特惠方式########：{}",order.getOrderFlag());
            if(StringUtils.isNotBlank(order.getOrderFlag()) && "特惠".equals(order.getOrderFlag())){
                //溢价2元
                BigDecimal allPrice = price.add(new BigDecimal("2.00")).setScale(2,  RoundingMode.DOWN);
                /*if(order.getOrderExpectPrice().compareTo(allPrice) > 0){
                    //同城急送-闪送=差价(优惠)
                    BigDecimal diffPrice = order.getOrderExpectPrice().subtract(allPrice).setScale(2,RoundingMode.DOWN);
                    //order.setPrefAmount(order.getPrefAmount().add(diffPrice));
                    log.error("计算优惠后的的金额:预估金额：{},闪送金额溢价2元：{}，闪送原金额：{}，差价金额：{},总优惠金额：{}",order.getOrderExpectPrice(),allPrice,price,diffPrice,order.getPrefAmount());
                }else {
                    //闪送-同城急送=差价（溢价）
                    BigDecimal lowPrice = allPrice.subtract(order.getOrderExpectPrice());
                    order.setSysPrice(lowPrice);
                }*/
                log.info("平台代管理的计费,客户手机号：{},客户类型：{}，同城急送金额：{},闪送金额溢价2元：{},闪送原金额：{}",customer.getCustomerPhone(),customer.getCustomerType(),order.getOrderExpectPrice(),allPrice,price);
                order.setOrderExpectPrice(allPrice);
                return order;
            }
        }
        log.error("加盟商自管理的计费所属加盟商：{}",franchiseeInformation.getFranName());
        //利润=订单金额-闪送
        BigDecimal subPrice=order.getOrderExpectPrice().subtract(price);
        log.error("[{}]订单[{}->{}],{}公里，金额：{}，闪送订单金额：{}，差价：{}",order.getMailingAddress().getCity(),order.getMailingName(),order.getReceiptName(),order.getOrderDistance(),order.getOrderExpectPrice(),price,subPrice);
        //遍历后台价格配置
        for (SysConfig conf : sysConfigService.getListByGroup("order_price_js_role")) {
            //判断当前订单价格是否在区间内
            if (order.getOrderExpectPrice().compareTo(new BigDecimal(conf.getConfigDataOne()))>-1){
                if (order.getOrderExpectPrice().compareTo(new BigDecimal(conf.getConfigDataTwo()))<1){
                    //在区间内如果，订单利润高于配置价格则不再加价，返回0
                    BigDecimal dfPrice=order.getOrderExpectPrice().multiply(new BigDecimal(conf.getConfigValue()));
                    log.error("区间：{}，起始金额：{}，结束金额：{}，利润：{}",conf.getConfigKey(),conf.getConfigDataOne(),conf.getConfigDataTwo(),dfPrice);
                    if (subPrice.compareTo(new BigDecimal("5"))>0){
                        log.error("差价:{}大于5元，不再加价。",subPrice);
                        return order;
                    }
                    BigDecimal rs=subPrice.multiply(new BigDecimal("-1")).add(dfPrice);
                    log.error("差价：{}低于5元，订单价格：{}，要求利润：{}，返回加价:{}",subPrice,order.getOrderExpectPrice(),dfPrice,rs);
                    //否则补齐利润为配置价格
                    bigDecimal = rs.setScale(2, RoundingMode.HALF_UP);
                    if(bigDecimal.compareTo(new BigDecimal("0.00")) < 0){
                        order.setPrefAmount(order.getPrefAmount().add(bigDecimal.multiply(new BigDecimal("-1"))));
                        //order.setOrderExpectPrice(order.getOrderExpectPrice().add(bigDecimal));
                    }else {
                        order.setSysPrice(bigDecimal);
                        order.setOrderExpectPrice(order.getOrderExpectPrice().add(bigDecimal));
                    }
                    return order;
                }
            }
        }
        log.error("未匹配到[{}]的订单[{}->{}],{}公里，金额：{}，闪送订单金额：{}，差价：{}",order.getMailingAddress().getCity(),order.getMailingName(),order.getReceiptName(),order.getOrderDistance(),order.getOrderExpectPrice(),price,subPrice);
        //未找到区间配置，给默认6元利润\
        bigDecimal = (subPrice.multiply(new BigDecimal("-1")).add(new BigDecimal("600"))).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);
        order.setOrderExpectPrice(order.getOrderExpectPrice().add(bigDecimal));
        return order;
    }


    /**
     * 获取闪送服务费
     * @param order
     * @return
     */
    private BigDecimal shanSongPrice(TOrder order){
        BigDecimal bigDecimal=new BigDecimal("0");
        /*return bigDecimal;*/
        TCustomer customer=customerService.getById(order.getPlayerId());
        //已经绑定商家模板的订单不添加溢价费
        if(StringUtils.isNotBlank(customer.getTemplateId())){
            return bigDecimal;
        }
        //判断下单选择的车辆来指定对应的交通方式
        TConfig vehicleCfg=configService.getById(order.getVehicleConfigId());
        if("car".equals(vehicleCfg.getConfigMark())){
            order.setTravelWay(ShanSongUtils.travelWay(order.getMailingAddress().getAdcode()));
        }
        //获取闪送价格
        APIEntity<JSONObject> res= ShanSongUtils.orderQueryBilling(order);
        if (res==null||!(res.checkSuccess())){
            return bigDecimal;
        }
        JSONObject body=res.getBody();
        //闪送订单实付价格
        BigDecimal price=new BigDecimal(body.getString("totalFeeAfterSave")).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);
        //利润=订单金额-闪送
        BigDecimal subPrice=order.getOrderExpectPrice().subtract(price);
        log.error("[{}]订单[{}->{}],{}公里，金额：{}，闪送订单金额：{}，差价：{}",order.getMailingAddress().getCity(),order.getMailingName(),order.getReceiptName(),order.getOrderDistance(),order.getOrderExpectPrice(),price,subPrice);
        //遍历后台价格配置
        for (SysConfig conf : sysConfigService.getListByGroup("order_price_js_role")) {
            //判断当前订单价格是否在区间内
            if (order.getOrderExpectPrice().compareTo(new BigDecimal(conf.getConfigDataOne()))>-1){
                if (order.getOrderExpectPrice().compareTo(new BigDecimal(conf.getConfigDataTwo()))<1){
                    //在区间内如果，订单利润高于配置价格则不再加价，返回0
                    BigDecimal dfPrice=order.getOrderExpectPrice().multiply(new BigDecimal(conf.getConfigValue()));
                    log.error("区间：{}，起始金额：{}，结束金额：{}，利润：{}",conf.getConfigKey(),conf.getConfigDataOne(),conf.getConfigDataTwo(),dfPrice);
                    if (subPrice.compareTo(new BigDecimal("15"))>0){
                        log.error("差价:{}大于15元，不再加价。",subPrice);
                        return bigDecimal;
                    }
                    BigDecimal rs=subPrice.multiply(new BigDecimal("-1")).add(dfPrice);
                    log.error("差价：{}低于15元，订单价格：{}，要求利润：{}，返回加价:{}",subPrice,order.getOrderExpectPrice(),dfPrice,rs);
                    //否则补齐利润为配置价格
                    return rs.setScale(2, RoundingMode.HALF_UP);
                }
            }
        }
        log.error("未匹配到[{}]的订单[{}->{}],{}公里，金额：{}，闪送订单金额：{}，差价：{}",order.getMailingAddress().getCity(),order.getMailingName(),order.getReceiptName(),order.getOrderDistance(),order.getOrderExpectPrice(),price,subPrice);
        //未找到区间配置，给默认6元利润
        return (subPrice.multiply(new BigDecimal("-1")).add(new BigDecimal("600"))).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);
    }

    /**
     * 订单远距离服务费
     * @param order
     * @return
     */
    private BigDecimal replenishPrice(TOrder order){
        BigDecimal replenishPrice = new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        if(StringUtils.isNotBlank(order.getOrderFlag()) && "特惠".equals(order.getOrderFlag())){
            return replenishPrice;
        }
        if(order.getFranId()==52){
            if(7<=order.getOrderDistance() && order.getOrderDistance()<10){
                replenishPrice = new BigDecimal("7.00");
            }
            if(10<=order.getOrderDistance()&& order.getOrderDistance()<20){
                replenishPrice = new BigDecimal("17.00");
            }
            if(20<=order.getOrderDistance()){
                replenishPrice = new BigDecimal("50.00");
            }
            return replenishPrice;
        }
        if(7<=order.getOrderDistance() && order.getOrderDistance()<=8){
            replenishPrice = new BigDecimal("2.00");
        }
        if(9<=order.getOrderDistance()){
            replenishPrice = new BigDecimal("5.00");
        }
        //否则直接返回差价并且加1元利润
        return replenishPrice;
    }
    /**
     * 获取大客户附加计费金额
     * @param customerId
     * @return
     */
    private BigDecimal bigCustomerAddPrice(Integer customerId){
        BigDecimal price = new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        List<TCustomerTemplate> list=configService.getBigCustomerAddList(customerId);
        if (list==null||list.size()<1){
            return price;
        }
        for (TCustomerTemplate template : list) {
            price=price.add(template.getConfigValue().getBigDecimal("费用"));
        }
        return price;
    }

    @Override
    public TOrder pickUpParts(TOrder order,Integer courierId) {
        order.setCourierId(courierId);
        order.setOrderStatus("待取件");
        order.setAcceptanceTime(LocalDateTime.now());
        itOrderService.updateById(order);
        return null;
    }

    /**
     *新版三方抽成（1）
     * @param order
     * @return
     */
    @Override
    @Transactional
    public  TOrder extractExtract(TOrder order){
        TCourier courier=courierService.getById(order.getCourierId());
        /*if(courier==null){
            log.error("订单异常，订单骑手信息丢失，订单号：{}",order.getOrderNum());
            SysError.saveError("[订单骑手信息丢失]订单号:{0}",order.getOrderNum());
            order = getTorder(order,psrt);
            return order;
        }*/
        Integer[] frans={95,168,52};
        for (int i = 0; i < frans.length; i++) {
            if(order.getFranId().equals(frans[i]) && order.getOrderDistance()<=3){
                order.setOrderSysMoney(new BigDecimal("0.00"));//平台抽成
                order.setOrderFranMoney(new BigDecimal("0.00"));//加盟商抽成
                order.setOrderCourierMoney(order.getOrderFactPrice());//配送员抽成
                if(order.getOrdertTip().compareTo(new BigDecimal("0.00")) > 0){//小费大于0计算新的结算金额
                    order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrdertTip()));
                }
                if(order.getOrderReward().compareTo(new BigDecimal("0.00")) > 0){//订单打赏大于0计算新的派送员结算金额
                    order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrderReward()));
                }
                if(StringUtils.isNotBlank(order.getOrderRemarks())){
                    order.setOrderRemarks(order.getOrderRemarks()+";3公里内0抽成");
                }else {
                    order.setOrderRemarks("3公里内0抽成");
                }
                order = getTorder(order,null);
                return order;
            }
        }
        TFranchiseeInformation franchiseeInformation;
        if(order.getFranId()==null){
            franchiseeInformation = franService.getOne(new QueryWrapper<TFranchiseeInformation>().eq("fran_id",1));
        }else {
            franchiseeInformation = franService.getOne(new QueryWrapper<TFranchiseeInformation>().eq("fran_id",order.getFranId()));
        }
        JSONObject full = franchiseeInformation.getFullTimeDivided();//全职的三方抽成
        JSONObject psrt = franchiseeInformation.getPartTimeDivided();//兼职的三方抽成
        JSONObject distc = franchiseeInformation.getDistTimeDivided();//距离的三方抽成
        if("待接单".equals(order.getOrderStatus())){
            order = getTorder(order,psrt);
            return order;
        }
        if(order.getFranId()==184 && order.getOrderDistance()<=Integer.parseInt(distc.getString("dist"))){
            order = getTorder(order,distc);
            return order;
        }
        if("全职".equals(courier.getCourierType())){
            order = getTorder(order,full);
        }
        if("兼职".equals(courier.getCourierType())){
            order = getTorder(order,psrt);
        }
        return order;
    }

    private TOrder getTorder(TOrder order,JSONObject jsonObject){
        BigDecimal syst;
        BigDecimal fran;
        BigDecimal rider;
        if(jsonObject !=null){
            syst = new BigDecimal(jsonObject.getString("syst"));
            fran = new BigDecimal(jsonObject.getString("fran"));
            rider = new BigDecimal(jsonObject.getString("rider"));
            //BigDecimal alldivided = syst.add(fran).add(rider);
            /*if(alldivided.compareTo(new BigDecimal("100.00")) != 0){
                throw new WebVerifiedException("三方分成比例不均!");
            }*/
            order.setOrderSysMoney(order.getOrderFactPrice().multiply(syst.divide(new BigDecimal("100"))).setScale(2, RoundingMode.DOWN));//平台抽成
            order.setOrderFranMoney(order.getOrderFactPrice().multiply(fran.divide(new BigDecimal("100"))).setScale(2, RoundingMode.DOWN));//加盟商抽成
            order.setOrderCourierMoney(order.getOrderFactPrice().multiply(rider.divide(new BigDecimal("100"))).setScale(2, RoundingMode.DOWN));//配送员抽成
        }

        if(order.getOrdertTip().compareTo(new BigDecimal("0.00"))==1){//小费大于0计算新的结算金额
            order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrdertTip()));
        }
        if(order.getOrderReward().compareTo(new BigDecimal("0.00"))==1){//订单打赏大于0计算新的派送员结算金额
            order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrderReward()));
        }
        return order;
    }

   /* @Override
    @Transactional
    public  TOrder extractExtract(TOrder order){
        TCourier courier=courierService.getById(order.getCourierId());
        if(courier==null){
            log.error("订单异常，订单骑手信息丢失，订单号：{}",order.getOrderNum());
            SysError.saveError("[订单骑手信息丢失]订单号:{0}",order.getOrderNum());
            return order;
        }
        BigDecimal allMoney = order.getOrderFactPrice().multiply(new BigDecimal("0.15")).setScale(2, RoundingMode.DOWN);//订单总抽成
        order.setOrderFranMoney(allMoney.multiply(new BigDecimal("0.70")).setScale(2, RoundingMode.DOWN));//加盟商抽成
        order.setOrderSysMoney(allMoney.subtract(order.getOrderFranMoney()).setScale(2, RoundingMode.DOWN));//平台抽成
        if(!"兼职".equals(courier.getCourierType())){
            order.setOrderFranMoney(new BigDecimal("0.00").setScale(2, RoundingMode.DOWN));
        }
        //骑手佣金=订单实付金额-(加盟商佣金+平台佣金)
        order.setOrderCourierMoney(order.getOrderFactPrice().subtract(order.getOrderFranMoney().add(order.getOrderSysMoney())));
        //log.info("订单佣金计算结果：[{}]",order);
        if(order.getOrdertTip().compareTo(new BigDecimal("0.00")) > 0){//小费大于0计算新的结算金额
            order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrdertTip()));
        }
        if(order.getOrderReward().compareTo(new BigDecimal("0.00")) > 0){//订单打赏大于0计算新的派送员结算金额
            order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrderReward()));
        }
        return order;
    }*/


    @Override
    public TOrder estimate(TOrder order) {
        BigDecimal allMoney = order.getOrderFactPrice().multiply(new BigDecimal("0.15")).setScale(2, RoundingMode.DOWN);//订单总抽成
        order.setOrderFranMoney(allMoney.multiply(new BigDecimal("0.70")).setScale(2, RoundingMode.DOWN));//加盟商抽成
        //order.setOrderSysMoney(allMoney.subtract(order.getOrderFranMoney()).setScale(2, RoundingMode.DOWN));//平台抽成
        order.setOrderSysMoney(new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN));
        //骑手佣金=订单实付金额-(加盟商佣金+平台佣金)
        order.setOrderCourierMoney(order.getOrderExpectPrice().subtract(order.getOrderFranMoney().add(order.getOrderSysMoney())));
        //log.info("订单佣金计算结果：[{}]",order);
        if(order.getOrdertTip().compareTo(new BigDecimal("0.00"))==1){//订单小费大于0计算新的派送员结算金额
            order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrdertTip()));
        }
        if(order.getOrderReward().compareTo(new BigDecimal("0.00"))==1){//订单打赏大于0计算新的派送员结算金额
            order.setOrderCourierMoney(order.getOrderCourierMoney().add(order.getOrdertTip()));
        }
        return order;
    }

    @Override
    @Transactional
    public APIEntity pointCourier(SysUser user, TOrder order, TCourier courier) {
        //指派订单
        if (order.getCourierId() == null && "待接单".equals(order.getOrderStatus())) {
            order.setOrderStatus("待取件");
            newsService.pushCourierMsg(courier.getCourierId(), "业务通知", "订单接收提醒",
                    "员工：" + courier.getCourierName()
                            + " 您好，接到来自系统管理员："
                            + user.getUserName()
                            + " 为您指派的订单："
                            + order.getOrderNum() + "请及时处理。");
        } else {//转派订单
            if (courier.getCourierId().equals(order.getCourierId())) {
                return APIEntity.fail("当前订单派送员和选择派送员不能是同一个人！");
            }
            if("待接单".equals(order.getOrderStatus())){
                order.setOrderStatus("待取件");
            }
            TCourier oldCourier = courierService.getById(order.getCourierId());
            //发送消息给接收订单的派送员
            newsService.pushCourierMsg(courier.getCourierId(), "业务通知", "订单转派接收",
                    "员工：" + courier.getCourierName()
                            + " 您好，接到来自系统管理员："
                            + user.getUserName()
                            + " 为您转派的订单："
                            + order.getOrderNum()
                            + "，当前订单状态："
                            + order.getOrderStatus()
                            + "，负责派送员：" + oldCourier.getCourierName()
                            + "  电话：" + oldCourier.getCourierPhone()
                            + "，请您联系当前派送员确认，及时处理订单。");
            newsService.pushCourierMsg(oldCourier.getCourierId(), "业务通知", "订单转出提醒",
                    "派送员：" + oldCourier.getCourierName()
                            + "  您好，您的订单："
                            + order.getOrderNum()
                            + "被系统管理员转出，现由派送员："
                            + courier.getCourierName()
                            + " 负责派送，请您及时联系。电话："
                            + courier.getCourierPhone());
        }
        order.setAcceptanceTime(LocalDateTime.now());
        order.setSurplusPickTime(itOrderService.getCourSurplusTime(order));
        order.setOrderExpectTime(itOrderService.getExpectTime(order,0));
        order.setCourierId(courier.getCourierId());
        order.setCourierType(courier.getCourierType());
        super.updateById(itOrderService.extractExtract(order));
        courier.setJobStatus("工作中");
        courierService.updateById(courier);
        itOrderService.post(order.getOrderId(),"派送员已接单，请留意接听电话");//向客户推送订阅消息
        if("麦芽田".equals(order.getOrderChannel())){
            TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",order.getShopId()));
            CourierAddressVo cuv=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS +courier.getCourierId(), CourierAddressVo.class);
            if(cuv == null){
                maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,null,"",1);
            }else {
                maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,cuv.getAddress(),"",1);
            }
        }
        return APIEntity.success();
    }

    @Override
    public TOrder getByNum(String orderNum) {
        return getOne(new QueryWrapper<TOrder>().eq("order_num",orderNum),false);
    }

    /**
     * 配送大厅：根据派送员与订单距离排序
     * @param order
     * @param address
     * @return
     */
    @Override
    public BigDecimal getDistanceByOrder(TOrder order, AddressVo address) {
        BigDecimal dist;
        if(null != address){
           dist =  MapUtils.getDistanceKma(order.getMailingAddress(),address);//根据经纬度计算两点之间距离
        }else {
            dist=new BigDecimal("0.1");
        }
        return dist;
    }

    /**
     * 派送员抢单订阅消息推送
     * @param tOrderid
     * @return
     */
    @Override
    public String post(Integer tOrderid,String dsc) {
        LocalDate now = LocalDate.now();
        TOrder tOrder = itOrderService.getById(tOrderid);
        if(tOrder.getCourierId() != null){
            TCourier tCourier = courierService.getById(tOrder.getCourierId());
            if (tOrder.getThird()){
                OrderDetailDO detailDO=thirdUtils.orderDetail(tOrder);
                tCourier.setCourierName(detailDO.getCourierName());
                tCourier.setCourierPhone(detailDO.getCourierPhone());
            }
            tOrder.setCourier(tCourier);
        }
        if("客户APP".equals(tOrder.getOrderChannel())){
            itOrderService.customerAppPush(tOrder,"订单通知",dsc);
            return null;
        }
        String jsonStr = JSONObject.toJSONString(tOrder);
        JSONObject js = JSONObject.parseObject(jsonStr);
        TCustomer customer = customerService.getById(tOrder.getPlayerId());
        String time8 = now.getYear()+"年"+now.getMonthValue()+"月"+LocalDateTime.now().getDayOfMonth()+"日"+" "+LocalDateTime.now().getHour()+":"+LocalDateTime.now().getMinute();
        //JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WXPayVo.getAppID() + "&secret=" + WXPayVo.getKey()));
        JSONObject body=new JSONObject();
        body.put("touser",customer.getOpenId());
        body.put("template_id","oNd2_Iw4F4NvXhE0KcV1YMNmKmp254SC3yRb5kmBawk");
        body.put("page","pages/orderDetails/orderDetails?order="+js.toString());
        //body.put("miniprogram_state","developer");
        JSONObject json=new JSONObject();
        JSONObject object=new JSONObject();
        object.put("value",customer.getCustomerName());
        JSONObject object1=new JSONObject();
        object1.put("value","￥"+tOrder.getOrderExpectPrice()+"元");
        JSONObject object2=new JSONObject();
        object2.put("value",tOrder.getOrderNum());
        JSONObject object3=new JSONObject();
        object3.put("value",time8);
        JSONObject object4=new JSONObject();
        object4.put("value",dsc);
        json.put("thing12",object);
        json.put("amount3",object1);
        json.put("character_string1",object2);
        json.put("time8",object3);
        json.put("thing2",object4);
        body.put("data",json);
        //发送
        String accessToken= WxUtils.getAccessToken(WxAppEm.MP_CLIENT);
        String post =  cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
        log.info("订阅消息推送成功：[{}]",post);
        return post;
    }

    /**
     * 客户取消订单，订阅消息推送
     * @param dec
     * @param tOrder
     * @return
     */
    @Override
    public String cancelOrder(String dec,TOrder tOrder) {
        LocalDate now = LocalDate.now();
        //TRefund tRefund = null;
        if(tOrder.getCourierId() != null){
            TCourier tCourier = courierService.getById(tOrder.getCourierId());
            if (tOrder.getThird()){
                ThirdUtils.orderCancel(tOrder);
            }
            tOrder.setCourier(tCourier);
        }
        if("客户APP".equals(tOrder.getOrderChannel())){
            itOrderService.customerAppPush(tOrder,"订单取消通知",dec);
            return null;
        }
        String jsonStr = JSONObject.toJSONString(tOrder);
        JSONObject js = JSONObject.parseObject(jsonStr);
        TCustomer customer = customerService.getById(tOrder.getPlayerId());
        String time12 = now.getYear()+"年"+now.getMonthValue()+"月"+LocalDateTime.now().getDayOfMonth()+"日"+" "+LocalDateTime.now().getHour()+":"+LocalDateTime.now().getMinute();
        //JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WXPayVo.getAppID() + "&secret=" + WXPayVo.getKey()));
        JSONObject body=new JSONObject();
        body.put("touser",customer.getOpenId());
        body.put("template_id","hx3WZVXKYu8zB8RXD3P_iammEeJgj5Q7ffS3eN19IZk");
        body.put("page","pages/orderDetails/orderDetails?order="+js.toString());
        //body.put("miniprogram_state","developer");
        JSONObject json=new JSONObject();
        JSONObject object=new JSONObject();
        object.put("value",tOrder.getOrderNum());
        JSONObject object1=new JSONObject();
        object1.put("value","￥"+tOrder.getOrderExpectPrice()+"元");
        JSONObject object2=new JSONObject();
        object2.put("value",time12);
        JSONObject object3=new JSONObject();
        object3.put("value","400-690-0105");
        JSONObject object4=new JSONObject();
        object4.put("value",dec);
        json.put("character_string2",object);
        json.put("amount10",object1);
        json.put("time12",object2);
        json.put("phone_number4",object3);
        json.put("thing5",object4);
        body.put("data",json);
        //发送
        String accessToken= WxUtils.getAccessToken(WxAppEm.MP_CLIENT);
        String post =  cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
        log.info("订阅消息推送成功：[{}]",post);
        TOrderCircu.insertCircu(tOrder);//根据订单状态修改订单流转状态
        //推送客如云取消订单，非客如云自动识别，按订单号
        KeRuYunApi.cancelPush(tOrder.getOrderNum(),dec);
        return post;
    }

    /*@Override
    public void cancelOrder(TOrder tOrder) {
        tOrder.setOrderStatus("已取消");
        tOrder.setOrderEndTime(LocalDateTime.now());
        itOrderService.updateById(tOrder);
        if(!tOrder.getDisId().equals(0)){
            discountOrderService.cancelOrderDisByVoucher(tOrder);
        }
        TOrderCircu.insertCircu(tOrder);//根据订单状态修改订单流转状态
        //推送客如云取消订单，非客如云自动识别，按订单号
        KeRuYunApi.cancelPush(tOrder.getOrderNum(),"客户主动取消");
        if("微信小程序".equals(tOrder.getOrderChannel())){
            itOrderService.cancelOrder("订单取消成功，如有疑问请联系客服",tOrder);//客户主动取消订单想哭推送订阅消息
        }else {
            itOrderService.customerAppPush(tOrder,"订单取消通知","订单取消成功，如有疑问请联系客服");//客户app通知栏推送消息
        }
        this.curAppPush(tOrder,"订单取消提醒",tOrder.getMailingAddress().getArea()+"的订单已取消");//骑手app通知栏推送
        newsService.pushCustomerMsg1(tOrder.getPlayerId(),"订单取消通知","尊敬的客户您好,您的订单已取消成功，订单号:{0}!",tOrder.getOrderNum());
        //如果是第三方订单，告知第三方取消
        ThirdUtils.orderCancel(tOrder);
    }*/

    /**
     * 通知栏通知派送员
     * @param tOrder
     * @param type
     * @param dec
     */
    @Override
    public void curAppPush(TOrder tOrder,String type,String dec) {
        List<Object> cids =courierService.listObjs(new QueryWrapper<TCourier>().select("cid").eq("courier_id",tOrder.getCourierId()));
        try {
            //AppPush.pusBatch("订单取消提醒",tOrder.getMailingAddress().getArea()+"的订单已取消",cids);
            AppPush.pusBatch(type,dec,cids);
        } catch (Exception e) {
            log.error("【通知栏消息推送失败】批量推送异常：",e);
        }
    }

    /**
     * 通知栏通知客户
     * @param tOrder
     * @param type
     * @param deca
     */
    @Override
    public void customerAppPush(TOrder tOrder,String type,String deca) {
        TCustomer customer =customerService.getById(tOrder.getPlayerId());
        try {
            if(customer.getPushOrNot()){
                CustomerAppPush.push(type,deca,customer.getCid());
            }
        } catch (Exception e) {
            log.error("【通知栏消息推送失败】批量推送异常：",e);
        }
    }

    @Override
    public QueryWrapper<TOrder> getTF(QueryWrapper<TOrder> queryWrapper, TCourier courier) {
        SysConfig fiveFrequency  = sysConfigService.getOne(new QueryWrapper<SysConfig>().eq("config_key","kilometre_five"));
        List<Object> customerIds  = customerBigService.listObjs(new QueryWrapper<TCustomerBig>().select("customer_id").eq("courier_id",courier.getCourierId()));
        if(customerIds.size()>0){
            List<TOrder> tOrders = itOrderService.list(new QueryWrapper<TOrder>().notIn("player_id",customerIds).eq("order_status","待接单").eq("courier_type","营销"));
            if(tOrders.size()>0){
                for(TOrder order : tOrders){
                    log.info("######################################1:[{}]",order);
                    queryWrapper = itOrderService.getWrapper(queryWrapper,order,courier);
                }
            }else {
                if("兼职".equals(courier.getCourierType())){
                    log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%1兼职显示");
                    queryWrapper.eq("order_batch_num","0");
                    //queryWrapper.lt("order_create_time",LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataTwo())).format(StringUtils.dataTimeFormat));
                } else{
                    log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%1全职显示");
                    //queryWrapper.lt("order_create_time", LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataOne())).format(StringUtils.dataTimeFormat));
                }
            }
        }else {
            List<TOrder> tOrders = itOrderService.list(new QueryWrapper<TOrder>().eq("order_status","待接单").eq("courier_type","营销"));
            if(tOrders.size()>0){
                for(TOrder order : tOrders){
                    log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2:[{}]",order.getOrderId());
                    queryWrapper = itOrderService.getWrapper(queryWrapper,order,courier);
                }
            }else {
                if("兼职".equals(courier.getCourierType())){
                    log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2兼职显示");
                    queryWrapper.eq("order_batch_num","0");
                    //queryWrapper.lt("order_create_time",LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataTwo())).format(StringUtils.dataTimeFormat));
                } else{
                    log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2全职显示");
                    //queryWrapper.lt("order_create_time", LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataOne())).format(StringUtils.dataTimeFormat));
                }
            }
        }
        return queryWrapper;
    }

    @Override
    public QueryWrapper<TOrder> getWrapper(QueryWrapper<TOrder> queryWrapper, TOrder order, TCourier courier) {
        SysConfig fiveFrequency  = sysConfigService.getOne(new QueryWrapper<SysConfig>().eq("config_key","kilometre_five"));
        if(Duration.between(order.getOrderCreateTime(),LocalDateTime.now()).toMinutes()<2 && "营销".equals(courier.getCourierType())){
            log.info("##################################营销1,[{}]",order.getOrderId());
            queryWrapper.notIn("order_id",order.getOrderId());
        }
        if(Duration.between(order.getOrderCreateTime(),LocalDateTime.now()).toMinutes()<2 && "全职".equals(courier.getCourierType())){
            log.info("##################################全职1");
            queryWrapper.notIn("order_id",order.getOrderId());
            //queryWrapper.lt("order_create_time", LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataOne())).format(StringUtils.dataTimeFormat));
        }else if("全职".equals(courier.getCourierType())){
            log.info("##################################全职2");
            //queryWrapper.lt("order_create_time", LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataOne())).format(StringUtils.dataTimeFormat));
        }
        if(Duration.between(order.getOrderCreateTime(),LocalDateTime.now()).toMinutes()<2 && "兼职".equals(courier.getCourierType())){
            log.info("##################################兼职1");
            queryWrapper.eq("order_batch_num","0");
            queryWrapper.notIn("order_id",order.getOrderId());
            //queryWrapper.lt("order_create_time",LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataTwo())).format(StringUtils.dataTimeFormat));
        }else if("兼职".equals(courier.getCourierType())){
            log.info("##################################兼职2");
            queryWrapper.eq("order_batch_num","0");
            //queryWrapper.lt("order_create_time",LocalDateTime.now().minusSeconds(Integer.parseInt(fiveFrequency.getConfigDataTwo())).format(StringUtils.dataTimeFormat));
        }
        return queryWrapper;
    }

    /**
     * 计算取件剩余时间
     * @param order
     * @return
     */
    @Override
    public LocalDateTime getSurplusTime(TOrder order) {
        String orderPickStr=order.getPickTime();
        LocalDateTime now=LocalDateTime.now().plusMinutes(5);
        if("今天/2小时内".equals(orderPickStr)){
            return now.plusHours(2);
        }
        if("今天/一小时内".equals(orderPickStr)){
            return now.plusHours(1);
        }
        if("今天/半小时内".equals(orderPickStr)){
            return now.plusMinutes(30);
        }
        if("今天/立即取件".equals(orderPickStr)){
            return now.plusMinutes(30);
        }
        LocalDate date=LocalDate.now();
        if (orderPickStr.contains("明天")){
            date=date.plusDays(1);
        }
        else if(orderPickStr.contains("后天")){
            date=date.plusDays(2);
        }
        if (orderPickStr.length()<14){
            String[] nums= StringUtils.strGetNum(orderPickStr).split(";");
            for (int i = 0; i < nums.length; i++) {
                if (nums[i].length()<2){
                    nums[i]=0+nums[i];
                }
            }
            return LocalDateTime.of(date,LocalTime.parse(nums[2]+":"+nums[3]+":00"));
        }
        return LocalDateTime.of(date,LocalTime.parse(orderPickStr.substring(9,14)+":00"));

    }

    /**
     * 骑手接单后计算剩余取件时间
     * @param order
     * @return
     */
    @Override
    public LocalDateTime getCourSurplusTime(TOrder order) {
        LocalDateTime surplusTime = LocalDateTime.now().plusMinutes(15);
        return surplusTime;
    }

    /**
     * 新版计算预计送达时间
     * @param order
     * @param orderDis
     * @return
     */
    public LocalDateTime getExpectTime(TOrder order,long orderDis) {
        long defaultTims=7;
        long exceedTims=0;
        //long signTimes=15;
        LocalDateTime expectTime = null;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if("KD".equals(order.getThirdName())){
            expectTime=order.getSurplusPickTime().plusDays(3);
            return expectTime;
        }
        if(OrderUtils.isUrgent(order)){//急件，接单后几个小时之内
            //3公里内，35分钟，超出三公里每公里加五分钟+完成上下楼时间
            long disnum=order.getOrderDistance();
            exceedTims = disnum*5;
            long allTime = defaultTims+exceedTims;
            String[] status={"待派送","派送中"};
            //log.info("订单状态：{}，距离：{},超距离时间：{},总时间：{}",order.getOrderStatus(),order.getOrderDistance(),exceedTims,allTime);
            if(Arrays.asList(status).contains(order.getOrderStatus())){
                expectTime=order.getConfirmPickTime()
                        .plusMinutes(allTime);
            }else {
                expectTime=order.getSurplusPickTime()
                        .plusMinutes(allTime);
            }
        }else {
            if(order.getOrderCreateTime().plusMinutes(40).getHour()<15){//普件，下午三点之前接的当天晚上24点之前送到
                log.info("下单40分钟后的时间：{}",order.getOrderCreateTime().plusMinutes(40));
                String localTime = df.format(LocalDate.now());
                String sss = localTime+" "+"23:50"+":00";
                expectTime =LocalDateTime.parse(sss,dtf);
            }else {//普件，下午三点之之后接的当第二天12点之前送到
                String localTime = df.format(LocalDate.now().plusDays(1));
                String sss = localTime+" "+"12:00"+":00";
                expectTime =LocalDateTime.parse(sss,dtf);
            }
        }

        return expectTime;
    }

    /**
     * 计算预计送达时间
     * @param order
     * @param
     * @return
     */
    /*@Override
    public LocalDateTime getExpectTime(TOrder order,long orderDis) {
        LocalDateTime expectTime = null;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if("KD".equals(order.getThirdName())){
            expectTime=order.getSurplusPickTime().plusDays(3);
            return expectTime;
        }
        int runOrders=itOrderService.count(new QueryWrapper<TOrder>().eq("courier_id",order.getCourierId()).in("order_status","待取件","取件中","待派送","派送中"));
        if(OrderUtils.isUrgent(order)){//急件，接单后几个小时之内
            //计算订单预估送达时间=订单原预计送达时间+((骑手取件距离+订单距离)/电动车速度333.4米/分钟)+(当前骑手正在进行中的其他订单数量*15分钟)+随机(1-15分钟)
            long dis = orderDis+order.getOrderDistance();
            long tims = Math.round(dis*1000/250d);
            //long ssss = tims+30;
            //log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:距离：{},距离时间：{},总时间：{}",dis,tims,ssss);
            expectTime=order.getSurplusPickTime()
                    .plusMinutes(tims)
                    .plusMinutes(runOrders* 15L)
                    .plusMinutes(((int) (Math.random() * 10))+1);
        }else {
            if(order.getOrderCreateTime().plusMinutes(40).getHour()<15){//普件，下午三点之前接的当天晚上24点之前送到
                log.info("下单40分钟后的时间：{}",order.getOrderCreateTime().plusMinutes(40));
                String localTime = df.format(LocalDate.now());
                String sss = localTime+" "+"23:50"+":00";
                expectTime =LocalDateTime.parse(sss,dtf);
            }else {//普件，下午三点之之后接的当第二天12点之前送到
                String localTime = df.format(LocalDate.now().plusDays(1));
                String sss = localTime+" "+"12:00"+":00";
                expectTime =LocalDateTime.parse(sss,dtf);
            }
        }
        return expectTime;
    }*/

    @Override
    public TOrder updatePriceByTime(TOrder order) {
        long pickTime = Duration.between(order.getSurplusPickTime(),order.getConfirmPickTime()).toMinutes();
        long songTime = Duration.between(order.getOrderExpectTime(),order.getOrderEndTime()).toMinutes();
        log.info("预计取件与实际取件相差多少时间：[{}]",pickTime);
        log.info("预计送达与实际送达相差多少时间：[{}]",songTime);
        BigDecimal result=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        TCourier courier = courierService.getById(order.getCourierId());
        int timeNum = 0;
        if(pickTime>songTime && pickTime>0){
            if(pickTime>=30 && pickTime<=60){
                result = order.getOrderCourierMoney().multiply(new BigDecimal("0.2"));
            }
            if(pickTime>60){
                result = order.getOrderCourierMoney().multiply(new BigDecimal("0.5"));
            }
            timeNum = (int)pickTime;
            log.info("取件超时扣除费用：[{}]",result);
        }
        if(songTime>pickTime && songTime>0){
            if(songTime>=30 && songTime<=60){
                result = order.getOrderCourierMoney().multiply(new BigDecimal("0.2"));
            }
            if(songTime>60){
                result = order.getOrderCourierMoney().multiply(new BigDecimal("0.5"));
            }
            timeNum = (int)songTime;
            log.info("取件超时扣除费用：[{}]",result);
        }
        if(!"全职".equals(courier.getCourierType()) && "考核".equals(courier.getAssessSet())){
            BigDecimal couMoney=order.getOrderCourierMoney().subtract(result);
            BigDecimal sysMoney=order.getOrderSysMoney().add(result);
            log.info("骑手扣费后金额：[{}]",couMoney);
            log.info("平台新增收入：[{}]",sysMoney);
            order.setTimeOut(timeNum);
            order.setOverDeduction(result);
            order.setOrderCourierMoney(couMoney);
            order.setOrderSysMoney(sysMoney);
            //itOrderService.updateById(order);
        }else {
            order.setTimeOut(timeNum);
        }
        return order;
    }

    @Override
    public String getOrderStatus(Integer orderId) {
        return String.valueOf(baseMapper.selectColumnById("order_status",orderId));
    }

    @Override
    public void cancelAndRefund(TOrder order) {
        List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",order.getOrderId()).eq("pay_status","已支付"));
        if(tPays.size()>0){
            refundService.cancel(order,tPays);
        }
    }

    @Override
    public String getCustomerPhone(String orderNum) {
        TOrder order=getByNum(orderNum);
        TCustomer customer=customerService.getById(order.getPlayerId());
        if (StringUtils.isBlank(customer.getCustomerPhone())){
            return order.getMailingPhone();
        }
        return customer.getCustomerPhone();
    }

    /**
     * 获取用户今日接单后取消的订单数量
     *
     * @param customerId 客户ID
     * @return
     */
    @Override
    public int cancelOrderTimes(Integer customerId) {
        return itOrderService.count(new QueryWrapper<TOrder>()
                .eq(" date(order_create_time)", " CURDATE()")
                .eq("cancel_type",1)
                .in("order_status","已取消","已退款")
                .isNotNull("acceptance_time"));
    }
    /**
     * 获取当前配置环境
     */
    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public String getHuolalaToken() {
        SysConfig config = sysConfigService.getOneByKey(active);
        //LocalDateTime takeTime=LocalDateTime.parse(config.getConfigGroup());
        LocalDateTime takeTime=LocalDateTime.parse("2023-08-18 12:26:17", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("获取货拉拉TOKEN：环境:{}，信息：{},有效期：{}",active,config.getConfigDataOne(),takeTime);
        long days = ChronoUnit.DAYS.between(LocalDateTime.now(),takeTime);
        if(days<=Long.valueOf(config.getConfigValue())){
            JSONObject res = HllUtils.getaccessToken(null,config.getConfigDataTwo());
            sysConfigService.getHuolalaToken(null,res);
        }
        return config.getConfigDataOne();
    }

    @Override
    public void satusFlow(CourierVo courierVo, TOrder order) {
        TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",order.getShopId()));
        log.info("获取商铺授权信息：{}",maltField);
        maltUtils.getDeliveryChange(order,courierVo.getCourierName(),maltField,courierVo.getLastLocation(),"",1);

    }
}
