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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.controller.callback.ThirdCallBack;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.third.SfExpressServer;
import com.bohuikeji.delivery.backstage.util.capacity.SfExpressUtils;
import com.bohuikeji.frame.module.admin.base.MqListener;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.SpringUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.Duration;

/**
 * 顺丰下单结果核查，用于确定下单是否成功，以及下单费用和指派小哥信息
 * @author Admin
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SfOrderPlaceCheck extends MqListener<OrderDetailDO> {

    final ITOrderService orderService;
    final RedisUtil redisUtil;
    final MqTool mqTool;
    final SfExpressServer server;

    /**
     * 接收到消息会调用此方法
     *
     * @param msg 消息体
     * @return 【保留返回值】暂无实际用途，后续可能用于支持消息失败重试
     */
    @Override
    public boolean onReceive(OrderDetailDO msg) throws IOException {
        //获取下单结果
        JSONObject res = SfExpressUtils.orderCreateResult(msg.getOrderNumber());
        if (res != null) {
            int status = res.getIntValue("orderStatus");
            if (status == 6 || status == 2) {
                redisUtil.set(server.getCacheKey(msg.getOrderNumber()).replaceFirst("third", "result"), APIEntity.fail(res.toJSONString()), Duration.ofDays(45).getSeconds());
                log.error("【顺丰下单失败】顺丰接口返回异常，订单：{},结果为：{}", msg.getOrderNumber(), res);
                return true;
            }
            TOrder order = orderService.getByNum(msg.getOrderNumber());
            if (!"待接单".equals(order.getOrderStatus())) {
                log.error("【顺丰订单复核，订单已被接取】订单信息：{}", msg);
                SfExpressUtils.cancelOrder(msg.getOrderNumber(),msg.getThirdNum());
                return true;
            }

            //获取订单调度信息
            JSONArray infos = SfExpressUtils.orderRecord(msg.getOrderNumber(),msg.getThirdNum());
            if (infos != null && infos.size() > 0) {
                String empPhone;
                String empCode;
                for (int i = 0; i < infos.size(); i++) {
                    empPhone = infos.getJSONObject(i).getString("empPhone");
                    empCode = infos.getJSONObject(i).getString("empCode");
                    if (StringUtils.isNotBlank(empPhone) && StringUtils.isNotBlank(empCode)) {
                        msg.setCourierPhone(empPhone);
                        msg.setCourierName("工号:" + empCode);
                        break;
                    }
                }
            } else {
                //无调度信息等一分钟再次复核
                mqTool.sendDelayMsg(msg, SfOrderPlaceCheck.class, Duration.ofSeconds(20));
                return true;
            }
            //更新Redis缓存信息
            redisUtil.set(server.getCacheKey(msg.getOrderNumber()), msg, 3600 * 24 * 45);
            redisUtil.set(server.getCacheKey(msg.getOrderNumber()).replaceFirst("third","result"),APIEntity.success(msg),3600*24*45);
            ThirdCallBack callBack = SpringUtil.getBean(ThirdCallBack.class);
            JSONObject req = new JSONObject();
            req.put("orderCode", msg.getOrderNumber());
            req.put("waybillNo", msg.getThirdNum());
            req.put("shipperCode", "SF");
            req.put("actionCode", 100);
            req.put("actionDesc", "已分配揽收");
            callBack.sfOrderNotice(req.toJSONString());
            return true;
        }
        return true;
    }

    /**
     * 当消费者业务代码出现异常时会调用该方法
     *
     * @param msg 消息体
     * @param e   异常信息
     */
    @Override
    public void onError(OrderDetailDO msg, Exception e) {

    }
}
