package com.hzs.third.delivery.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hzs.third.delivery.dto.DeliveryDTO;
import com.hzs.third.delivery.config.DeliveryConfig;
import com.hzs.third.delivery.dto.DeliveryResultDTO;
import com.hzs.third.delivery.service.IDeliveryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: 快递地址识别服务
 * @Author: jiang chao
 * @Time: 2024/12/26 15:13
 * @Classname: DeliveryServiceImpl
 * @PackageName: com.hzs.third.delivery.service.impl
 */
@Slf4j
@Service
public class DeliveryServiceImpl implements IDeliveryService {

    @Autowired
    private DeliveryConfig deliveryConfig;

    // 请求接口URL
    private final String URL = "https://jmkddzjx.market.alicloudapi.com/express/address-parse";

    @Override
    public DeliveryDTO handleDeliveryAddress(String address) {
        String appcode = deliveryConfig.getAppCode();

        try {
            HttpRequest httpRequest = HttpUtil.createPost(URL);
            // 最后在header中的格式(中间是英文空格)为 Authorization:  APPCODE 83359fd73fe94948385f570e3c139105
            httpRequest.header("Authorization", "APPCODE " + appcode);
            // 根据API的要求，定义相对应的Content-Type
            httpRequest.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            // 请求体
            httpRequest.body("address=" + address);

            // 请求执行
            HttpResponse httpResponse = httpRequest.execute();

            log.info("快递地址识别返回数据：{}", httpResponse.body());

            // 返回结果数据
            DeliveryResultDTO resultDTO = JSONUtil.toBean(httpResponse.body(), DeliveryResultDTO.class);
            if (HttpStatus.HTTP_OK == resultDTO.getCode()) {
                // 请求返回成功
                // 返回数据内容解析
                return JSONUtil.toBean(resultDTO.getData(), DeliveryDTO.class);
            } else {
                log.error("快递地址识别失败，msg: {}", resultDTO.getMsg());
            }
        } catch (Exception e) {
            log.error("快递地址识别异常，address: {}", address, e);
        }
        return null;
    }

}
