package com.ruoyi.logistics.callback;
import com.ruoyi.logistics.service.impl.FeePushService;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.logistics.domain.SfFeeApiResponse;
import com.ruoyi.logistics.domain.SfFeePushRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;



/**
 * 顺丰物流费用清单回调
 * @author zxf
 * @date 2026-02-03
 */
@RestController
@RequestMapping("/callback")
public class SfFeePushCallback {
    private static final Logger logger = LoggerFactory.getLogger(SfFeePushCallback.class);
    private final ObjectMapper objectMapper;
    private final FeePushService feePushService;

    public SfFeePushCallback(ObjectMapper objectMapper, FeePushService feePushService) {
        this.objectMapper = objectMapper;
        this.feePushService = feePushService;
    }

    /**
     * 接收顺丰运费清单推送
     * 注意：接口整体报文为form表单格式，但content参数是JSON数据
     * @param sign 数字签名
     * @param content 业务数据JSON字符串
     * @return 标准响应
     */
    @PostMapping("/feePush")
    public ResponseEntity<SfFeeApiResponse> receiveFeePush(
            @RequestParam("sign") String sign,
            @RequestParam("content") String content) {
        logger.info("收到顺丰运费清单推送，content: {}", content);
        try {
            // 2. 解析JSON数据
            SfFeePushRequest feePushRequest = objectMapper.readValue(content, SfFeePushRequest.class);
            // 3. 参数验证
            if (feePushRequest.getWaybillNo() == null || feePushRequest.getWaybillNo().isEmpty()) {
                return ResponseEntity.ok(SfFeeApiResponse.error("运单号不能为空"));
            }
            if (feePushRequest.getOrderNo() == null || feePushRequest.getOrderNo().isEmpty()) {
                return ResponseEntity.ok(SfFeeApiResponse.error("订单号不能为空"));
            }
            // 4. 处理业务逻辑
            boolean success = feePushService.processFeePush(feePushRequest);
            if (success) {
                logger.info("运费清单处理成功，运单号: {}, 订单号: {}",
                        feePushRequest.getWaybillNo(), feePushRequest.getOrderNo());
                return ResponseEntity.ok(SfFeeApiResponse.success());
            } else {
                logger.error("运费清单处理失败，运单号: {}", feePushRequest.getWaybillNo());
                return ResponseEntity.ok(SfFeeApiResponse.error("业务处理失败"));
            }

        } catch (com.fasterxml.jackson.core.JsonParseException e) {
            logger.error("JSON解析失败: {}", e.getMessage());
            return ResponseEntity.ok(SfFeeApiResponse.error("非法的JSON格式"));
        } catch (Exception e) {
            logger.error("处理运费清单推送异常: {}", e.getMessage(), e);
            return ResponseEntity.ok(SfFeeApiResponse.error("系统发生数据错误或运行时异常"));
        }
    }

}
