package com.ruoyi.logistics.callback;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.logistics.domain.BizWaybillOrder;
import com.ruoyi.logistics.domain.OrderStateDetail;
import com.ruoyi.logistics.domain.SfApiResponse;
import com.ruoyi.logistics.domain.SfPushOrderStateRequest;
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.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 顺丰物流订单状态回调相关
 * 目前涉及的回调有：
 * 1.订单状态回调
 * 2.费用清单回调
 *
 * @author zxf
 * @date 2026-02-03
 */
@RestController
@RequestMapping("/callback")
public class SfPushOrderStatusCallback {
    private static final Logger logger = LoggerFactory.getLogger(SfPushOrderStatusCallback.class);


    @Autowired
    private IBizWaybillOrderService bizWaybillOrderService;

    /**
     * 顺丰物流订单状态回调
     * 说明：仅限于推送上门订单调度状态  非预约订单不推送
     *
     * @author zxf
     * @date 2026-02-03
     */
    @PostMapping("/orderStatus11")
    public SfApiResponse orderStatus(@RequestBody SfPushOrderStateRequest pushRequest) throws UnsupportedEncodingException, JsonProcessingException {
        logger.info("收到顺丰订单状态推送，requestId: {}", pushRequest.getRequestId());

        // 1.订单状态为空直接返给顺丰
        if (pushRequest.getOrderState() == null || pushRequest.getOrderState().isEmpty()) {
            logger.error("订单状态数据为空");
            return createErrorResponse("订单状态数据为空");
        }

        // 2. 处理每条订单状态更新
        List<OrderStateDetail> stateList = pushRequest.getOrderState();
        for (OrderStateDetail state : stateList) {
            try {
                processSingleOrderState(state);
            } catch (Exception e) {
                logger.error("处理订单状态失败，订单号: {}, 运单号: {}", state.getOrderNo(), state.getWaybillNo(), e);
                // 可根据业务决定是记录日志后继续，还是直接返回失败
            }
        }

        // 3. 返回成功响应（必须严格按此格式，否则顺丰可能认为推送失败）
        SfApiResponse response = new SfApiResponse();
        response.setSuccess("true");
        response.setCode("0");
        response.setMsg("");
        logger.info("订单状态推送处理完成，requestId: {}", pushRequest.getRequestId());
        return response;

    }


    /**
            * 处理单个订单的状态更新
     */
    private void processSingleOrderState(OrderStateDetail state) {
        logger.info("更新订单状态 - 订单号: {}, 运单号: {}, 状态码: {}, 状态描述: {}, 更新时间: {}",
                state.getOrderNo(),
                state.getWaybillNo(),
                state.getOrderStateCode(),
                state.getOrderStateDesc(),
                state.getLastTime());
        // 根据顺丰返回的状态吗进行系统状态变更  目前还没对
        switch (state.getOrderStateCode()) {
            case "04":
                BizWaybillOrder bizWaybillOrder= new BizWaybillOrder();
                bizWaybillOrder.setExternalWaybillNo(state.getOrderNo());
                bizWaybillOrder.setOrderStatus(1);
                bizWaybillOrderService.updateBizWaybillOrder(bizWaybillOrder);
                break;
            case "04-40001":

                break;
            case "04-40037":

                break;

            default:
                logger.info("收到未定义的状态码: {}", state.getOrderStateCode());
        }
    }













    private SfApiResponse createErrorResponse(String errorMsg) {
        SfApiResponse response = new SfApiResponse();
        response.setSuccess("false");
        response.setMsg(errorMsg);
        return response;
    }
}
