package com.fzm.mall.server.front.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.front.enums.GoodsRedisEnum;
import com.fzm.mall.server.front.user.service.IRedisService;
import com.fzm.mall.server.front.util.HttpUtil;
import com.fzm.mall.server.front.util.MD5Util;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WuLiuService {

    @Value("${express.showapi-url}")
    private String baseUrl;

    @Value("${express.appid}")
    private String appid;

    @Value("${express.secret}")
    private String secret;

    @Value("${express.activeTime}")
    private Long activeTime;

    @Autowired
    private IRedisService redisService;

    private String geExpressDetail(String expressName, String expressNo) {
        //com(快递公司简称),nu(订单号)
        String str = new StringBuilder().append("com").append(expressName)
                .append("nu").append(expressNo)
                .append("showapi_appid").append(appid).append(secret).toString();
        String showapiSign = MD5Util.getMD5String(str);
        String url = new StringBuilder(baseUrl).append("com=").append(expressName)
                .append("&").append("nu=").append(expressNo)
                .append("&").append("showapi_appid=").append(appid)
                .append("&").append("showapi_sign=").append(showapiSign).toString();
        String response = HttpUtil.httpGet(url);
        System.out.println(response);
        JSONObject responseObj = JSON.parseObject(response);
        System.out.println(responseObj.get("showapi_res_code"));
        if (!responseObj.get("showapi_res_code").equals(0)) {
            log.error("物流查询异常");
            return "";
        }
        //快递状态 1 暂无记录 2 在途中 3 派送中 4 已签收 (完结状态) 5 用户拒签 6 疑难件 7 无效单 (完结状态) 8 超时单 9 签收失败 10 退回
        JSONObject bodyObj = (JSONObject) responseObj.get("showapi_res_body");

        return bodyObj.toString();
    }

    String getWuliu(String orderDeliveryId,String expressName, String expressNo){
        System.out.println("expressName:"+expressName);
        System.out.println("expressNo:"+expressNo);
        //redisService.del(GoodsRedisEnum.ORDER_RETURN_WULIU_KEY.value()+orderDeliveryId);
        String wuliu = redisService.getKey(GoodsRedisEnum.ORDER_RETURN_WULIU_KEY.value()+orderDeliveryId);
        System.out.println(wuliu);
        if(StringUtil.isNullOrEmpty(wuliu)){
            wuliu = geExpressDetail(expressName,expressNo);
            redisService.setKey(GoodsRedisEnum.ORDER_RETURN_WULIU_KEY.value()+orderDeliveryId,wuliu,1000*60*60*6);
        }
        return  wuliu;
    }
}
