package com.yonge.cooleshow.mall.common.courier.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.api.Subscribe;
import com.kuaidi100.sdk.contant.ApiInfoConstant;
import com.kuaidi100.sdk.contant.CompanyConstant;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.request.SubscribeParam;
import com.kuaidi100.sdk.request.SubscribeParameters;
import com.kuaidi100.sdk.request.SubscribeReq;
import com.kuaidi100.sdk.utils.SignUtils;
import com.yonge.cooleshow.mall.common.courier.domain.CourierInfo;
import com.yonge.cooleshow.mall.common.courier.enums.CompanyEnum;
import com.yonge.cooleshow.mall.common.courier.service.CourierService;
import com.yonge.toolset.base.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description
 *
 * @author liujunchi
 * @date 2022-10-26
 */
@Service("Courier100Service")
public class Courier100ServiceImpl implements CourierService {

    private static final Logger LOG = LoggerFactory.getLogger(Courier100ServiceImpl.class);

    @Value("${courier.courier100.key:jvpXSAFN9687}")
    private String key;

    @Value("${courier.courier100.customer:B6E26D57F060E7D9C87032AF7F000046}")
    private String customer;


    @Override
    public CourierInfo queryTrack(CompanyEnum company, String courierNo) {
        QueryTrackReq queryTrackReq = new QueryTrackReq();
        QueryTrackParam queryTrackParam = new QueryTrackParam();

        queryTrackParam.setCom(getCompanyConstant(company));
        queryTrackParam.setNum(courierNo);
        queryTrackParam.setResultv2("4");
        String param = new Gson().toJson(queryTrackParam);

        queryTrackReq.setParam(param);
        queryTrackReq.setCustomer(customer);
        queryTrackReq.setSign(SignUtils.querySign(param , key, customer));

        IBaseClient baseClient = new QueryTrack();
        try {
            LOG.debug("查询快递参数： {}",queryTrackParam);
            HttpResult execute = baseClient.execute(queryTrackReq);
            LOG.info("查询快递信息参数： {}",execute);
            if (execute.getStatus() != 200) {
                throw new BizException(execute.getError());
            }
            String body = execute.getBody();
            return getCourierInfos(body);
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage());
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }
    }

    @Override
    public CourierInfo getCourierInfos(String body) {
        JSONObject jsonObject = JSON.parseObject(body);
        if (!"200".equals(jsonObject.getString("status"))) {
            throw new BizException(jsonObject.getString("message"));
        }
        CourierInfo courierInfo = new CourierInfo();
        List<CourierInfo.Logistics> data = JSON.parseArray(jsonObject.getString("data"), CourierInfo.Logistics.class);

        courierInfo.setLogisticsList(data);
        courierInfo.setCourierNo(jsonObject.getString("nu"));
        courierInfo.setCompany(CompanyEnum.codeOf(jsonObject.getString("com")));
        return courierInfo;
    }

    @Override
    public boolean subscribe(CompanyEnum company, String courierNo, String url) {
        SubscribeParameters subscribeParameters = new SubscribeParameters();
        subscribeParameters.setCallbackurl(url);
        subscribeParameters.setResultv2("4");

        SubscribeParam subscribeParam = new SubscribeParam();
        subscribeParam.setParameters(subscribeParameters);

        subscribeParam.setCompany(getCompanyConstant(company));
        subscribeParam.setNumber(courierNo);
        subscribeParam.setKey(key);

        SubscribeReq subscribeReq = new SubscribeReq();
        subscribeReq.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA);
        subscribeReq.setParam(new Gson().toJson(subscribeParam));

        IBaseClient subscribe = new Subscribe();
        try {
            LOG.debug("快递信息订阅参数： {}",subscribeReq);
            HttpResult execute = subscribe.execute(subscribeReq);
            LOG.info("快递信息订阅返回参数： {}",execute);
            if (execute.getStatus() != 200) {
                throw new BizException(execute.getError());
            }
            JSONObject jsonObject = JSON.parseObject(execute.getBody());
            if (!"200".equals(jsonObject.getString("returnCode"))) {
                throw new BizException(jsonObject.getString("message"));
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage());
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }
    }

    private String getCompanyConstant(CompanyEnum companyEnum) {
        switch (companyEnum) {
            case JD: return CompanyConstant.JD;
            case EMS: return CompanyConstant.EMS;
            case YUNDA: return CompanyConstant.YD;
            case SHENTONG: return CompanyConstant.ST;
            case SHUNFENG: return CompanyConstant.SF;
            case YUANTONG: return CompanyConstant.YT;
            case ZHONGTONG: return CompanyConstant.ZT;
            case ZHAIJISONG: return CompanyConstant.ZJS;
            case DEBANGKUAIDI: return CompanyConstant.DB;
            case HUITONGKUAIDI: return CompanyConstant.HT;
            default: return null;
        }
    }

    public static void main(String[] args) {
        Courier100ServiceImpl courier100Service = new Courier100ServiceImpl();
        courier100Service.queryTrack(CompanyEnum.DEBANGKUAIDI,"75606690482924");
    }
}
