package com.slodon.b2b2c.core.express;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.Md5;
import com.slodon.b2b2c.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 获取物流轨迹工具类
 *
 * @author wuxy
 */
@Slf4j
public class TrackUtil {

    /**
     * 获取快递鸟物流轨迹
     *
     * @param orderSn       订单号
     * @param expressCode   快递编码
     * @param expressName   快递公司
     * @param expressNumber 快递单号
     * @param eBusinessId   快递鸟EBusinessID
     * @param appKey        快递鸟AppKey
     * @param customerName  ShipperCode 为 SF 时必填，对应寄件人/ 收件人手机号后四位； ShipperCode 为其他快递时，可不填或保 留字段，不可传值
     * @return 物流轨迹
     */
    public static TracesResult getKdniaoTrack(String orderSn, String expressCode, String expressName, String expressNumber,
                                              String eBusinessId, String appKey, String customerName) {
        String expressTraceResult = null;
        //查询快递鸟
        KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
        try {
            expressTraceResult = api.getOrderTracesByJson(eBusinessId, appKey, orderSn, expressCode, expressNumber, customerName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("快递鸟查询物流信息：" + expressTraceResult);
        AssertUtil.isTrue(StringUtil.isEmpty(expressTraceResult), "获取快递轨迹信息失败，请稍后重试");

        DeliverInfo deliverInfo = JSON.parseObject(expressTraceResult, DeliverInfo.class);

        TracesResult tracesResult = new TracesResult();
        tracesResult.setExpressName(expressName);
        tracesResult.setExpressNumber(expressNumber);
        tracesResult.setType("0");
        List<DeliverInfo.Traces> tracesList = deliverInfo.getTraces();
        if (CollectionUtils.isEmpty(tracesList)) {
            tracesList = new ArrayList<>();
        } else {
            Collections.reverse(tracesList);
        }
        tracesResult.setRouteList(tracesList);
        return tracesResult;
    }

    /**
     * 获取快递100物流轨迹
     *
     * @param phone         手机号
     * @param expressCode   快递编码
     * @param expressName   快递公司
     * @param expressNumber 快递单号
     * @param key           授权key
     * @param customer      授权码
     * @return 物流信息轨迹
     */
    public static TracesResult getKd100Track(String phone, String expressCode, String expressName, String expressNumber,
                                             String key, String customer) {
        String url = "https://poll.kuaidi100.com/poll/query.do";

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        Map<String, String> params = new HashMap<>();
        params.put("com", expressCode);
        params.put("num", expressNumber);
        params.put("phone", phone);

        String param = JSON.toJSONString(params);
        String sign = Md5.printSign(param + key + customer);

        Map<String, Object> body = new HashMap<>(3);
        body.put("customer", customer);
        body.put("sign", sign);
        body.put("param", param);
        log.info("快递100查询物流入参信息：" + JSON.toJSON(body));
        HttpResponse execute = HttpUtil.createPost(url).headerMap(headers, true).form(body).execute();
        String result = execute.body();
        log.info("快递100查询物流返回信息：" + result);

        JSONArray jsonArray = JSONObject.parseObject(result).getJSONArray("data");

        TracesResult tracesResult = new TracesResult();
        tracesResult.setExpressName(expressName);
        tracesResult.setExpressNumber(expressNumber);
        tracesResult.setType("0");
        List<DeliverInfo.Traces> tracesList = new ArrayList<>();
        if (CollectionUtils.isEmpty(jsonArray)) {
            tracesList = new ArrayList<>();
        } else {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                DeliverInfo.Traces traces = new DeliverInfo.Traces();
                traces.setAcceptTime(jsonObject.getString("time"));
                traces.setRemark(jsonObject.getString("context"));
                tracesList.add(traces);
            }
        }
        tracesResult.setRouteList(tracesList);
        return tracesResult;
    }
}
