package com.bohuikeji.delivery.backstage.controller.admin;

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.controller.api.order.TorderCirceApi;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.listener.order.OrderCreateListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderSendThirdListener;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.base.InterfaceBase;
import com.bohuikeji.frame.module.admin.component.MqTool;
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.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ISysLogService;
import com.bohuikeji.frame.module.admin.service.ISysUserService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 *
 * @author 10552
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController extends ControllerBase {

    @Autowired
    ITOrderService orderService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ITFranchiseeInformationService franService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITOrderExceptionService exceptionService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    ITLogisticsService logisticsService;
    @Autowired
    ITOrderTemplateService templateService;
    @Autowired
    ISysUserService userService;
    @Autowired
    ISysLogService logService;
    @Autowired
    IGmsService gmsService;
    @Autowired
    ITConfigService configService;
    @Autowired
    ThirdUtils thirdUtils;
    @Autowired
    TorderCirceApi circeApi;
    @Autowired
    ITMaltFieldService maltFieldService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    MqTool mqTool;

    /**
     * 获取订单完成率
     * @param franName
     * @param timeType
     * @return
     */
    @GetMapping("/get/order/complete/rate")
    public APIEntity getRate(String franName,String timeType){
        Integer allCunt=null;//所有订单
        Integer completeCunt=null;//完成订单
        BigDecimal rate;//完成率
        JSONObject jsonObject = new JSONObject();
        SysUser sysUser = getLoginUser();
        if("运营管理员".equals(sysUser.getUserName())){
            if(StringUtils.isNotBlank(franName)){
                TFranchiseeInformation franchiseeInformation = franService.getOne(new QueryWrapper<TFranchiseeInformation>().like("fran_name",franName));
                completeCunt = orderService.count(new QueryWrapper<TOrder>().last("where fran_id="+franchiseeInformation.getFranId()+" and  order_status='已完成' and date(order_create_time)=CURDATE()"));
                allCunt = orderService.count(new QueryWrapper<TOrder>().last("where fran_id="+franchiseeInformation.getFranId()+" and date(order_create_time)=CURDATE()"));
            }else {
                completeCunt = orderService.count(new QueryWrapper<TOrder>().last("where order_status='已完成' and date(order_create_time)=CURDATE()"));
                allCunt = orderService.count(new QueryWrapper<TOrder>().last("where date(order_create_time)=CURDATE()"));
            }
        }
        rate= new BigDecimal(completeCunt).divide(new BigDecimal(allCunt),2, RoundingMode.DOWN).multiply(new BigDecimal("100"));
        jsonObject.put("allCunt",allCunt);
        jsonObject.put("completeCunt",completeCunt);
        jsonObject.put("rate",rate+"%");
        return APIEntity.success(jsonObject);
    }

    /**
     * 获取加盟商订单完成率
     * @param timeType
     * @return
     */
    @GetMapping("/get/order/fran/complete/rate")
    public APIEntity getFranRate(String timeType){
        Integer allCunt=null;//所有订单
        Integer completeCunt = null;//完成订单
        BigDecimal rate;//完成率
        JSONObject jsonObject = new JSONObject();
        SysUser sysUser = getLoginUser();
        if(sysUser != null){
            completeCunt = orderService.count(new QueryWrapper<TOrder>().last("where fran_id="+sysUser.getFranId()+" and  order_status='已完成' and date(order_create_time)=CURDATE()"));
            allCunt = orderService.count(new QueryWrapper<TOrder>().last("where fran_id="+sysUser.getFranId()+" and date(order_create_time)=CURDATE()"));
        }
        rate= new BigDecimal(completeCunt).divide(new BigDecimal(allCunt),2, RoundingMode.DOWN).multiply(new BigDecimal("100"));
        jsonObject.put("allCunt",allCunt);
        jsonObject.put("completeCunt",completeCunt);
        jsonObject.put("rate",rate+"%");
        return APIEntity.success(jsonObject);
    }

    /**
     * 重新推送第三方
     * @param orderId
     * @param type
     * @return
     */
    @RequestMapping("/repush")
    @InitLog("客户拉黑")
    public APIEntity rePush(Integer orderId,String type){
        log.error("#########################:{},第三方名称：{}",orderId,type);
        SysUser user = getLoginUser();
        if(user.getUserId()!=1){
            return APIEntity.fail("此功能只对平台开放，加盟商无需管理");
        }
        TOrder order = orderService.getById(orderId);

        if("已取消".equals(order.getOrderStatus())){
            return APIEntity.fail("订单已取消无法再次推送");
        }
        if(!"全部".equals(type)){
            order.setThirdName(type);
            orderService.updateById(order);
        }
        Duration time=Duration.ofSeconds(1);
        //mqTool.sendMsg(order.getOrderNum(), OrderCreateListener.class);
        mqTool.sendDelayMsg(order.getOrderId(), OrderSendThirdListener.class,time);
        return APIEntity.success("推送成功！");
    }

    /**
     * 指派订单/转派订单
     *
     * @param orderId
     * @param courierId
     * @return 周立武修改
     */
    @InitLog("订单转派")
    @GetMapping("/getEditStatus")
    public APIEntity getEditStatus(Integer orderId, Integer courierId,String flag,String sign) {
        SysUser user = getLoginUser();
        log.info("获取需要转派的派送员Id[{}]", courierId);
        TOrder order = orderService.getById(orderId);
        TCourier courier = courierService.getById(courierId);
        if (courier==null){
            return APIEntity.fail("未找到ID=["+courierId+"]的骑手，请确定网络环境正常，并刷新页面在试~");
        }
        if("关闭".equals(courier.getAssignSwitch())){
            return APIEntity.fail("该派送员未开启接受指派功能！");
        }
        if("ZP".equals(flag)&&(StringUtils.isBlank(sign))){
            TCourier nowCourier = courierService.getById(order.getCourierId());
            if(nowCourier!=null){
                return APIEntity.ask("当前订单已经由派送员：【{0}】 接单，是否强制指派：【{1}】 进行派送？",nowCourier.getCourierName(),courier.getCourierName());
            }
        }
        return orderService.pointCourier(user, order, courier);
    }

    /**
     * 订单新增或修改提交
     * @param params
     * @return
     */
    @InitLog()
    @PostMapping("/table/model/form")
    public InterfaceBase formSubmit(HttpServletRequest request, @RequestParam Map<String, String> params) {
        TOrder oldOrder = orderService.getById(params.get("orderId"));
        String templateId = params.get("templateId");
        //如果模板ID不为空，则读取订单模板
        if (StringUtils.isNotBlank(templateId)) {
            TOrderTemplate template = templateService.getById(templateId);
            params.put("vehicleConfigId", template.getVehicleConfigId() + "");
            params.put("cargoConfigId", template.getCargoConfigId() + "");
            params.put("worthConfigId", template.getWorthConfigId() + "");
            params.put("wayConfigId", template.getWayConfigId() + "");
            params.put("paymentConfigId", template.getPaymentConfigId() + "");
        }
        if(oldOrder==null){
            params.put("orderNum",null);
            params.put("orderChannel","后台下单");
        }
        TOrder order = (TOrder) crateEntityByMap(params);
        log.info("打印订单信息：[{}]", order);
        //order.setOrderDistance(Math.round(MapUtils.getDistanceKm(order.getMailingAddress(), order.getReceiptAddress())));
        /*order.setOrderExpectPrice(orderService.moneySumNew(order).getOrderExpectPrice());
        order.setVehicleName(configService.getById(order.getVehicleConfigId()).getConfigName());
        order.setCargoName(configService.getById(order.getCargoConfigId()).getConfigName());
        order.setWorthName(configService.getById(order.getWorthConfigId()).getConfigName());
        order.setWayName(configService.getById(order.getWayConfigId()).getConfigName());
        order.setPaymentType(configService.getById(order.getPaymentConfigId()).getConfigName());
        order.setFranId(franService.checkPio(order.getMailingAddress()).getFranId());*/
        //log.info("订单信息：[{}]",order);
        if (order.getOrderId() == null) {
            getLog(request).setLogAction("新增").setLogName("新增订单").setLogDetail(StringUtils.formatStr("新增订单：[{0}]", order));
        } else {
            getLog(request).setLogAction("修改").setLogName("订单修改")
                    .setLogDetail(StringUtils.formatStr("更改订单：[{0}]，原订单：[{1}]，修改后订单：[{2}]", oldOrder.getOrderNum(), oldOrder, order));
        }
        if (order.insertOrUpdate()) {
            return APIEntity.success();
        }
        return APIEntity.fail("系统繁忙，请稍后再试！");
    }

    /**
     * 异常订单处理——指派派送员模态框提交
     *
     * @param orderId
     * @param courierId
     * @return 周立武修改
     */
    @InitLog("异常订单指派")
    @GetMapping("/exception/assign")
    public APIEntity exceptionAssign(Integer exceptionId, Integer orderId, Integer courierId, String status, Integer userId) {
        TCourier tCourier = courierService.getById(courierId);
        if(StringUtils.isEmpty(status)){
            return APIEntity.fail("请选择订单状态！");
        }
        if("关闭".equals(tCourier.getAssignSwitch())){
            return APIEntity.fail("该派送员未开启接受指派功能！");
        }
        TOrder order = orderService.getById(orderId);
        if (order == null) {
            //更新异常处理结果
            TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
            exceptionEntit.setEndWay("订单已删除，自动处理");
            exceptionEntit.setStatus("处理完成");
            exceptionEntit.setEndTime(LocalDateTime.now());
            exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
            exceptionEntit.updateById();
            return APIEntity.success("无效的记录，该订单已被删除");
        }
        if("寄付".equals(order.getPaymentType()) && !"待支付".equals(status)){
            if(order.getOrderFactPrice().compareTo(new BigDecimal("0.00"))==0){
                return APIEntity.fail("该订单未支付，请选择待支付状态");
            }
        }
        if("到付".equals(order.getPaymentType()) && "待支付".equals(status)){
                return APIEntity.fail("该订单为到付订单，请不要选择待支付状态");
        }
        SysUser user = userId == null ? getLoginUser() : userService.getById(userId);
        //指派订单
        if("待支付".equals(status) || "待取件".equals(status) || "取件中".equals(status)){
            order.setSurplusPickTime(orderService.getSurplusTime(order));
        }
        if("去派送".equals(status)){
            order.setOrderExpectTime(orderService.getExpectTime(order,0));
        }
        order.setOrderStatus(status);
        newsService.pushCourierMsg(courierId, "业务通知", "订单接收提醒",
                "员工：" + tCourier.getCourierName()
                        + " 您好，接到来自系统管理员："
                        + user.getUserName()
                        + " 为您指派的订单："
                        + order.getOrderNum() + "请及时处理。");
        order.setCourierId(courierId);
        order.setCourierType(tCourier.getCourierType());
        orderService.updateById(order);
        tCourier.setJobStatus("工作中");
        courierService.updateById(tCourier);
        //更新异常处理结果
        TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
        exceptionEntit.setEndWay("已指派派送员：" + tCourier.getCourierName() + "，工号：" + tCourier.getCourierNum() + "处理，同时更改订单状态为：" + status);
        exceptionEntit.setStatus("处理完成");
        exceptionEntit.setEndTime(LocalDateTime.now());
        exceptionEntit.setEndUser(user.getUserId());
        exceptionEntit.updateById();
        return APIEntity.success();
    }

    /**
     * 异常订单处理——重置订单
     *
     * @param orderId
     * @return 周立武修改
     */
    @InitLog("异常订单重置")
    @GetMapping("/exception/reset")
    public APIEntity exceptionReset(Integer exceptionId, Integer orderId, Integer userId) {
        TOrder order = orderService.getById(orderId);
        if (order == null) {
            //更新异常处理结果
            TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
            exceptionEntit.setEndWay("订单已删除，自动处理");
            exceptionEntit.setStatus("处理完成");
            exceptionEntit.setEndTime(LocalDateTime.now());
            exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
            exceptionEntit.updateById();
            return APIEntity.success("无效的记录，该订单已被删除");
        }
        if("麦芽田".equals(order.getOrderChannel())){
            order.setOrderStatus("已取消");//订单状态修改
            TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",order.getShopId()));
            if(order.getCourierId()==null){
                maltUtils.getDeliveryChange(order,null,maltField,null,order.getOrderRemarks(),1);
            }else {
                TCourier courier = courierService.getById(order.getCourierId());
                CourierAddressVo cuv =redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS +courier.getCourierId(), CourierAddressVo.class);
                log.info("麦芽田订单取消查询骑手缓存信息：{}",cuv);
                if(cuv == null){
                    maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,null,"",1);
                }else {
                    maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,cuv.getAddress(),order.getOrderRemarks(),1);
                }
            }
            order.setOrderStatus("待接单");//订单状态修改
            order.setCourierId(null);
            order.setCourierPhone(null);
            orderService.updateById(order);
            TOrderCircu.insertCircu(order);//状态流转修改
            return APIEntity.success("麦芽田订单已重置成功！");
        }
        //获取用户付款记录
        List<TPay> payList = payService.list(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).eq("pay_status", "已支付"));
        if (payList.size() < 1) {
            payList = payService.list(new QueryWrapper<TPay>().eq("merchant_num", order.getOrderNum()).eq("pay_status", "已支付"));
        }
        if (payList.size() == 1) {
            //一条支付记录
            TPay pay = payList.get(0);
            TRefund refund = refundService.getOne(new QueryWrapper<TRefund>().eq("pay_id", pay.getPayId()));
            if (refund == null) {
                refund = refundService.getOne(new QueryWrapper<TRefund>().eq("pay_num", pay.getPayNum()));
            }
            if (refund == null || (!"退款成功".equals(refund.getRefundStatus()))) {
                return APIEntity.fail("该订单用户已完成支付，请先为用户完成退款！");
            }
        }
        //多条订单记录
        if (payList.size() > 1) {
            SysError.saveError("订单：" + order.getOrderNum() + "存在多条支付记录");
            return APIEntity.fail("该订单存在多条支付记录无返重置，请联系系统管理员核查！");
        }
        //未支付
        order.setOrderStatus("待接单");
        if (order.updateById()) {
            TOrderCircu.insertCircu(order);//状态流转修改
            /*List<TLogistics> tLogisticss = logisticsService.list(new QueryWrapper<TLogistics>().eq("order_id",orderId));
            logisticsService.updateOrderAndTLogistics(tLogisticss,order.getOrderStatus());//修改物流与流转的状态*/
            newsService.pushCustomerMsg1(order.getPlayerId(),  "订单重置通知",
                    "尊敬的用户您好，您的订单：{0}，以被重置为等待接单状态，如有疑问请使用微信小程序，客服助手进行反馈。", order.getOrderNum());
        }
        //更新异常处理结果
        TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
        exceptionEntit.setEndWay("已重置订单状态为：待接单");
        exceptionEntit.setStatus("处理完成");
        exceptionEntit.setEndTime(LocalDateTime.now());
        exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
        exceptionEntit.updateById();
        return APIEntity.success();
    }

    /**
     * 异常订单处理——取消订单
     *
     * @param orderId
     * @return 周立武修改
     */
    @InitLog("异常订单取消")
    @GetMapping("/exception/chanel")
    public APIEntity exceptionChanel(Integer exceptionId, Integer orderId, Integer userId) {
        TOrder order = orderService.getById(orderId);
        if (order == null) {
            //更新异常处理结果
            TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
            exceptionEntit.setEndWay("订单已删除，自动处理");
            exceptionEntit.setStatus("处理完成");
            exceptionEntit.setEndTime(LocalDateTime.now());
            exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
            exceptionEntit.updateById();
            return APIEntity.success("无效的记录，该订单已被删除");
        }
        //获取用户付款记录
        List<TPay> payList = payService.list(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).eq("pay_status", "已支付"));
        if (payList.size() < 1) {
            payList = payService.list(new QueryWrapper<TPay>().eq("merchant_num", order.getOrderNum()).eq("pay_status", "已支付"));
        }
        if (payList.size() == 1) {
            //一条支付记录
            TPay pay = payList.get(0);
            TRefund refund = refundService.getOne(new QueryWrapper<TRefund>().eq("pay_id", pay.getPayId()));
            if (refund == null) {
                refund = refundService.getOne(new QueryWrapper<TRefund>().eq("pay_num", pay.getPayNum()));
            }
            if (refund == null || (!"退款成功".equals(refund.getRefundStatus()))) {
                return APIEntity.fail("该订单用户已完成支付，请先为用户完成退款！");
            }
        }
        //多条订单记录
        if (payList.size() > 1) {
            SysError.saveError("订单：" + order.getOrderNum() + "存在多条支付记录");
            return APIEntity.fail("该订单存在多条支付记录无返重置，请联系系统管理员核查！");
        }
        //未支付
        order.setOrderStatus("已取消");
        if (order.updateById()) {
            ThirdUtils.orderCancel(order);
            TOrderCircu.insertCircu(order);//状态流转修改
            List<TLogistics> tLogisticss = logisticsService.list(new QueryWrapper<TLogistics>().eq("order_id", orderId));
            logisticsService.updateOrderAndTLogistics(tLogisticss, order.getOrderStatus());//修改物流与流转的状态
            orderService.cancelOrder("系统以为您取消订单，如有疑问请联系客服",order);
            newsService.pushCustomerMsg1(order.getPlayerId(),  "订单取消通知",
                    "尊敬的用户您好，您的订单：{0}，以被管理员取消，如有疑问请使用微信小程序，客服助手进行反馈。", order.getOrderNum());
        }
        //更新异常处理结果
        TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
        exceptionEntit.setEndWay("取消订单");
        exceptionEntit.setStatus("处理完成");
        exceptionEntit.setEndTime(LocalDateTime.now());
        exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
        exceptionEntit.updateById();
        if("麦芽田".equals(order.getOrderChannel())){
            //order.setOrderStatus("已取消");//订单状态修改
            TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",order.getShopId()));
            if(order.getCourierId()==null){
                maltUtils.getDeliveryChange(order,null,maltField,null,"无人接单，无法配送",1);
            }else {
                TCourier courier = courierService.getById(order.getCourierId());
                CourierAddressVo cuv =redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS +courier.getCourierId(), CourierAddressVo.class);
                log.info("麦芽田订单取消查询骑手缓存信息：{}",cuv);
                if(cuv == null){
                    maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,null,"商家取消",3);
                }else {
                    maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,cuv.getAddress(),"商家取消",3);
                }
            }
            //TOrderCircu.insertCircu(order);//状态流转修改
            return APIEntity.success("麦芽田订单已取消成功！");
        }
        return APIEntity.success();
    }

    /**
     * 异常订单处理——完结订单
     *
     * @param orderId
     * @return 周立武修改
     */
    @InitLog("异常订单完结")
    @GetMapping("/exception/end")
    public APIEntity exceptionEnd(Integer exceptionId, Integer orderId, Integer userId) {
        TOrder order = orderService.getById(orderId);
        if (order == null) {
            //更新异常处理结果
            TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
            exceptionEntit.setEndWay("订单已删除，自动处理");
            exceptionEntit.setStatus("处理完成");
            exceptionEntit.setEndTime(LocalDateTime.now());
            exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
            exceptionEntit.updateById();
            return APIEntity.success("无效的记录，该订单已被删除");
        }
        //获取用户付款记录
        List<TPay> payList = payService.list(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).eq("pay_status", "已支付"));
        if (payList.size() < 1) {
            payList = payService.list(new QueryWrapper<TPay>().eq("merchant_num", order.getOrderNum()).eq("pay_status", "已支付"));
        }
        if (payList.size() < 1) {
            return APIEntity.fail("该订单尚未付款，无法完结，请选择重置、取消、或指派派送员处理操作！");
        }
        //遍历支付记录
        TRefund refund;
        for (TPay pay : payList) {
            refund = refundService.getOne(new QueryWrapper<TRefund>().eq("pay_id", pay.getPayId()));
            if (refund == null) {
                refund = refundService.getOne(new QueryWrapper<TRefund>().eq("pay_num", pay.getPayNum()));
            }
            if (refund != null && "退款成功".equals(refund.getRefundStatus())) {
                //已支付，但已退款，无法完结
                return APIEntity.fail("该订单尚已退款，无法完结，取消订单或指派派送员处理！");
            }
        }
        order.setOrderEndTime(LocalDateTime.now());
        order = orderService.extractExtract(order);
        //已完成结算
        order.setOrderStatus("已完成");
        if (order.updateById()) {
            TOrderCircu.insertCircu(order);//状态流转修改
            List<TLogistics> tLogisticss = logisticsService.list(new QueryWrapper<TLogistics>().eq("order_id", orderId));
            logisticsService.updateOrderAndTLogistics(tLogisticss, order.getOrderStatus());
            //修改物流与流转的状态
            newsService.pushCustomerMsg1(order.getPlayerId(),"订单完成通知",
                    "尊敬的用户您好，您的订单：{0}，以被管理员取消，如有疑问请使用微信小程序，客服助手进行反馈。", order.getOrderNum());
        }
        if("麦芽田".equals(order.getOrderChannel())){
            if("取件中".equals(order.getOrderStatus())){
                return APIEntity.success();
            }
            TCourier courier = courierService.getById(order.getCourierId());
            TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",order.getShopId()));
            CourierAddressVo cuv=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS +order.getCourierId(), CourierAddressVo.class);
            if(cuv == null){
                maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,null,"",1);
            }else {
                maltUtils.getDeliveryChange(order,courier.getCourierName(),maltField,cuv.getAddress(),"",1);
            }
        }
        //更新异常处理结果
        TOrderExceptionEntity exceptionEntit = exceptionService.getById(exceptionId);
        exceptionEntit.setEndWay("设置订单为完结状态");
        exceptionEntit.setStatus("处理完成");
        exceptionEntit.setEndTime(LocalDateTime.now());
        exceptionEntit.setEndUser(userId == null ? getLoginUser().getUserId() : userId);
        exceptionEntit.updateById();
        return APIEntity.success();

    }

    /**
     * 发送无法服务短信
     *
     * @param phone
     * @param region
     * @return
     */
    @InitLog("发送无法服务短信")
    @PostMapping("/server/not")
    public APIEntity serverNot(String phone, String region) {
        return gmsService.sendNoServerMsg(phone,region)?APIEntity.success():APIEntity.fail("服务商发送短信失败，手机号码："+phone);
    }


    /**
     * 根据派送员id统计派送员所接订单（数量，金额之类）
     *
     * @param courierId
     * @return
     */
    @GetMapping("/getOrderByid")
    public APIEntity orderByid(Integer courierId) {
        SysConfig sysConfig = sysConfigService.getOne(new QueryWrapper<SysConfig>().eq("config_key", "courier"));
        BigDecimal bd = new BigDecimal(sysConfig.getConfigValue());
        BigDecimal dig = courierService.getTodayIncome(courierId);//派送员今日收入
        Integer coun = courierService.getTordercount(courierId);//派送员今日单量
        Integer totalCount = courierService.getTotalCount(courierId);//派送员订单总数
        Integer notCompleteCount = courierService.getNotCompleteCount(courierId);//派送员未完成订单总数
        Integer completeCount = courierService.getCompleteCount(courierId);//派送员完成订单总数
        BigDecimal totalIncomeCount = courierService.getTotalIncomeCount(courierId);//派送员总收入金额
        JSONObject obj = new JSONObject();
        if (dig == null) {
            obj.put("dig", 0);
        } else {
            obj.put("dig", dig);
        }
        if (totalIncomeCount == null) {
            obj.put("totalIncomeCount", 0);
        } else {
            obj.put("totalIncomeCount", totalIncomeCount);
        }
        obj.put("coun", coun);
        obj.put("totalCount", totalCount);
        obj.put("notCompleteCount", notCompleteCount);
        obj.put("completeCount", completeCount);
        return APIEntity.success(obj);
    }

    /**
     * 获取第三方订单信息
     * @param orderId
     * @return
     */
    @GetMapping("/get/third/info")
    public APIEntity thirdInfo(Integer orderId){
        TOrder order=orderService.getById(orderId);
        if (order!=null){
            OrderDetailDO detail=thirdUtils.orderDetail(order);
            if (detail==null){
                return APIEntity.fail("暂无信息，该订单当前不是由第三方进行配送！");
            }
            return APIEntity.success(detail);
        }
        return APIEntity.fail("无法找到订单信息，请刷新页面重试！");
    }
    /**
     * 获取第三方订单信息
     * @param orderId
     * @return
     */
    @GetMapping("/get/third/record")
    public APIEntity<List<TOrderCircu>> thirdRecord(Integer orderId){
        return circeApi.getByOrder(orderId);
    }
    /**
     * 获取第三方订单推送结果
     * @param orderNum 订单号
     * @return
     */
    @GetMapping("/get/third/result")
    public APIEntity thirdResult(String orderNum){
        StringBuilder strBuilder=new StringBuilder();
        Map<String,APIEntity<OrderDetailDO>> results=new HashMap<>(4);
        results.put("闪送",thirdUtils.orderResult(orderNum,"SS"));
        results.put("UU跑腿",thirdUtils.orderResult(orderNum,"UU"));
        results.put("京东快递",thirdUtils.orderResult(orderNum,"JD"));
        results.put("货拉拉",thirdUtils.orderResult(orderNum,"HLL"));
        results.put("顺丰快递",thirdUtils.orderResult(orderNum,"SFKD"));
        results.put("快递100",thirdUtils.orderResult(orderNum,"KD"));
        APIEntity sfRes=thirdUtils.orderResult(orderNum,"SF");

        if (sfRes==null||sfRes.getBody()==null){
            results.put("顺丰同城",APIEntity.fail("暂无推送信息"));
        }else {
            results.put("顺丰同城",thirdUtils.orderResult(orderNum,"SF"));
        }
        results.forEach((k,v)->{
            if (v==null){
                strBuilder.append("<span style='color: #DD524D;'>【").append(k).append("推送失败】</span>，无法找到推送记录，可能由于第三方系统延迟，请尝试等待1分钟再试！").append("<br>");return;
            }
            if (v.checkSuccess()){
                strBuilder.append("<span style='color: #00aa7f;'>【").append(k).append("推送成功】</span>，").append("第三方订单号：").append(v.myBody(OrderDetailDO.class).getThirdNum()).append("<br>");
            }else{
                strBuilder.append("<span style='color: #DD524D;'>【").append(k).append("推送失败】</span>，").append("第三方返回信息：").append(v.getMessage()).append("<br>");
            }
        });
        return APIEntity.success(strBuilder.toString());
    }
}
