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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.socket.AdminNotice;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.util.AppPush;
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.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 OrderPayCancelListener extends MqListener<String> {
    final ITOrderService orderService;
    final ISysLogService logService;
    final ITNewsService newsService;
    final IGmsService gmsService;
    final ISocketService socketService;
    final ITCourierService courierService;
    @Override
    public boolean onReceive(String orderNum) {
        log.info("监听待支付自动取消订单号：[{}]", orderNum);
        SysLog sysLog = new SysLog();
        TOrder order = orderService.getByNum(orderNum);
        if (order == null) {
            sysLog.setLogResult("失败");
            sysLog.setLogDetail("无法找到订单对象，可能已被删除！");
            log.error("订单丢失，订单号：{}", orderNum);
            logService.save(sysLog);
            return true;
        }
        sysLog.setLogType("系统日志");
        sysLog.setLogUser(1);
        sysLog.setLogIp(LocalHostUtil.getLocalIP());
        sysLog.setLogModel("订单管理");
        sysLog.setLogMenu(order.getOrderStatus());
        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");
        sysLog.setLogDetail(StringUtils.formatStr("订单：[{0}]", order));
        log.info("订单：{}自动取消进入。。。。。", orderNum);
        if ("到付".equals(order.getPaymentType())) {
            return true;
        }
        //客户超时未支付
        if ("待支付".equals(order.getOrderStatus())) {
            order.setOrderStatus("已取消");
            order.setOrderEndTime(LocalDateTime.now());
            order.setOrderRemarks("支付已超时，系统自动取消");
            if (orderService.updateById(order)) {
                ThirdUtils.orderCancelAll(order.getOrderNum());
                //发送无服务短信通知
                gmsService.sendCancelMsg(order.getMailingPhone(), order.getOrderNum());
                //发送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);
                newsService.pushCustomerMsg1(order.getPlayerId(), "订单取消通知",
                        "尊敬的客户您好，由于您长时间未支付该订单，系统已为您取消订单{0}，给您带来的不便敬请谅解！", order.getOrderNum());
                List<Object> cids = courierService.listObjs(new QueryWrapper<TCourier>().select("cid").eq("courier_id", order.getCourierId()));
                try {//待支付：客户超过规定时间未付款，向客户推送订阅消息
                    orderService.cancelOrder("订单长时间未支付，系统已为您自动取消", order);
                    AppPush.pusBatch("订单取消提醒", order.getMailingAddress().getArea() + "的订单已取消", cids);
                } catch (Exception e) {
                    log.error("【通知栏消息推送失败】批量推送异常：", e);
                }
                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) {

    }
}
