package com.ruoyi.logistics.callback;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.logistics.domain.BizWaybillOrder;
import com.ruoyi.logistics.service.IBizWaybillOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 顺丰物流订单路由状态回调相关
 *
 * @author zxf
 * @date 2026-02-03
 */
@RestController
@RequestMapping("/callback")
public class SfRoutingPushCallback {
    private static final Logger logger = LoggerFactory.getLogger(SfRoutingPushCallback.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private IBizWaybillOrderService bizWaybillOrderService;
    /**
     * 接收JSON格式的路由推送数据
     * 请求方法为"json"时使用此接口
     */
    @PostMapping("/orderStatus")
    public Map<String, String> receiveRoutePushJson(@RequestBody Map<String, Object> requestBody) {
        logger.info("收到顺丰物流路由推送，requestBody: {}", requestBody);
        Map result = new HashMap<>();
        try {
            // 解析请求体
            Map<String, Object> body = (Map<String, Object>) requestBody.get("Body");
            if (body != null && body.containsKey("WaybillRoute")) {
                List<Map<String, Object>> waybillRoutes = (List<Map<String, Object>>) body.get("WaybillRoute");
                // 检查批次大小（顺丰限制最多10个WaybillRoute元素）
                if (waybillRoutes.size() > 10) {
                    result.put("return_code", "1000");
                    result.put("return_msg", "路由信息批次大小不能超过10条");
                    return result;
                }

                // 处理路由信息
                for (Map<String, Object> route : waybillRoutes) {
                    processRouteInfo(route);
                }
                // 返回成功响应（JSON格式）
                result.put("return_code", "0000");
                result.put("return_msg", "成功");
                return result;
            }
            // 返回失败响应
            result.put("return_code", "1000");
            result.put("return_msg", "请求数据格式错误：缺少Body或WaybillRoute字段");
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            result.put("return_code", "0000");
            result.put("return_msg", "系统异常：" + e.getMessage());
            return result;

        }
    }

    /**
     * 处理路由信息
     */
    private void processRouteInfo(Map<String, Object> route) {
        logger.info("开始处理顺丰路由信息 - 客户运单号: {}, 客户订单号: {}, 状态码: {}, 备注: {}, 收货时间: {}",
                route.get("mailno"),
                route.get("orderid"),
                route.get("opCode"),
                route.get("remark"),
                route.get("acceptTime"));
        // 提取路由信息
        String mailno = (String) route.get("mailno");          // 客户运单号
        String orderid = (String) route.get("orderid");       // 客户订单号
        String acceptTime = (String) route.get("acceptTime"); // 收货时间
        String remark = (String) route.get("remark");         // 备注
        String opCode = (String) route.get("opCode");         // 操作码
        // TODO:
        BizWaybillOrder bizWaybillOrder= new BizWaybillOrder();
        switch (opCode) {
            case "50": // 已收取快件
                bizWaybillOrder.setOrderStatus(2);
                bizWaybillOrder.setExternalWaybillNo(mailno);
                //揽收时间
                bizWaybillOrder.setPickupTime(new Date());
                bizWaybillOrderService.updateBizWaybillOrderState( bizWaybillOrder);
                break;
            case "30": // 到达中转场
                bizWaybillOrder.setOrderStatus(3);
                bizWaybillOrder.setExternalWaybillNo(mailno);
                bizWaybillOrderService.updateBizWaybillOrderState( bizWaybillOrder);
                break;
            case "44": // 派送中
                bizWaybillOrder.setOrderStatus(4);
                bizWaybillOrder.setExternalWaybillNo(mailno);
                bizWaybillOrder.setDeliveryTime(new Date());
                bizWaybillOrderService.updateBizWaybillOrderState( bizWaybillOrder);
                break;
            case "80": // 已签收
                bizWaybillOrder.setOrderStatus(5);
                bizWaybillOrder.setExternalWaybillNo(mailno);
                bizWaybillOrder.setSignTime(new Date());
                bizWaybillOrderService.updateBizWaybillOrderState( bizWaybillOrder);
                break;
            default:
                logger.info("收到未定义的状态码: {}", opCode);
        }


    }


}