package com.bohuikeji.delivery.backstage.listener.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TMaltField;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.delivery.backstage.entity.socket.AdminNotice;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.JdServer;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.base.MqListener;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.entity.sys.SysLog;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysLogService;
import com.bohuikeji.frame.module.admin.utils.LocalHostUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单延迟取消监听业务
 * @author Admin
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderDelayCancelListener extends MqListener<String> {
    final ITOrderService orderService;
    final ISysLogService logService;
    final ITRefundService refundService;
    final ITPayService payService;
    final ISocketService socketService;
    final IGmsService gmsService;
    final ITDiscountOrderService orderDiscountService;
    final ITNewsService newsService;
    final ITMaltFieldService maltFieldService;

    @Override
    public boolean onReceive(String orderNum) {
        if(JdServer.isJdOrder(orderNum)){
            log.error("京东订单不取消：{}",orderNum);
            return true;
        }
        SysLog sysLog = new SysLog();
        sysLog.setLogType("系统日志");
        sysLog.setLogUser(1);
        sysLog.setLogIp(LocalHostUtil.getLocalIP());
        sysLog.setLogModel("订单管理");
        sysLog.setLogMenu("待接单");
        sysLog.setLogAction("自动");
        sysLog.setLogName("订单超时自动取消");
        sysLog.setLogMethod("com.bohuikeji.delivery.backstage.controller.admin.process");
        sysLog.setLogParams("[" + orderNum + "]");
        sysLog.setLogReturn("void");
        sysLog.setLogNode(LocalHostUtil.getHostName() + ":" + StaticComponent.port);
        sysLog.setRunTime(0 + "ms");
        log.info("订单：{}自动取消进入。。。。。", orderNum);
        TOrder order = orderService.getByNum(orderNum);
        if (order == null) {
            sysLog.setLogResult("失败");
            sysLog.setLogDetail("无法找到订单对象，可能已被删除！");
            log.error("订单丢失，订单号：{}", orderNum);
            logService.save(sysLog);
            return true;
        }
        if("麦芽田".equals(order.getOrderChannel())){
            return true;
        }
        sysLog.setLogDetail(StringUtils.formatStr("订单：[{0}]", order));
        //平台的超时未接订单
        if ("待接单".equals(order.getOrderStatus())) {
            //order.setOrderStatus("已退款");
            order.setOrderEndTime(LocalDateTime.now());
            order.setOrderRemarks("订单已超时，系统自动取消");
            order.setCancelType(0);
            if (orderService.updateById(order)) {
                List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",order.getOrderId()).eq("pay_status","已支付"));
                refundService.cancel(order,tPays);
                //如果为第三方订单则同时取消
                ThirdUtils.orderCancelAll(order.getOrderNum());
                //发送无服务短信通知
                gmsService.sendNoServerMsg(order.getMailingPhone(), order.getMailingAddress().getCity());
                //发送socket通知给后台
                socketService.sendAdminMsg(new AdminNotice(StringUtils.formatStr("您好，来自{0}的订单已超时，已为您自动取消！",
                        order.getMailingAddress().getProvince() + order.getMailingAddress().getCity()))
                        .setType("warning").setFranId(order.getFranId()));
                log.info("订单已经取消了");
                sysLog.setLogResult("成功");
                logService.save(sysLog);
                AddressVo ads = order.getMailingAddress();
                newsService.pushCustomerMsg1(order.getPlayerId(), "订单取消通知",
                        "尊敬的客户您好，由于{0}的该区域运力不足，暂时无法为您提供配送服务，系统已为您取消订单{1}，给您带来的不便敬请谅解！", ads.getProvince() + ads.getCity(), order.getOrderNum());
                //待接单：超过规定时间无人接单，向客户推送订阅消息
                orderService.cancelOrder("当前运力紧张，系统已为您取消订单", order);
                if (!order.getDisId().equals(0)) {
                    //优惠卷恢复位置用状态
                    orderDiscountService.cancelOrderDisByVoucher(order);
                }
                /*if("麦芽田".equals(order.getOrderChannel())){
                    TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("cus_id",order.getPlayerId()));
                    log.info("自动取消时的订单状态：{}",order.getOrderStatus());
                    if(order.getCourierId()==null){
                        maltUtils.getDeliveryChange(order,null,maltField,null,order.getOrderRemarks(),"2");
                    }
                }*/
                return true;
            }
            log.error("订单取消失败，订单状态变为：" + order.getOrderStatus());
            sysLog.setLogResult("失败");
            sysLog.setLogDetail("订单状态已变为：" + order.getOrderStatus());
            logService.save(sysLog);
        }
        return true;
    }

    @Override
    public void onError(String msg, Exception e) {

    }
}
