package com.kmall.manager.manager.express.sf.properties;

import com.google.common.base.Strings;
import com.kmall.manager.manager.express.sf.*;
import com.kmall.manager.manager.express.sf.entity.RouteEntity;
import com.kmall.manager.manager.express.sf.entity.RouteResponseEntity;
import com.kmall.manager.manager.express.sf.entity.SfRouteServiceResponseEntity;
import com.kmall.manager.manager.express.sf.request.Body;
import com.kmall.manager.manager.express.sf.request.Request;
import com.kmall.manager.manager.express.sf.request.RouteRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huangyq
 * @version 1.0
 * 2019-03-29 17:03
 */
public class SFUtil {
    private static Log logger = LogFactory.getLog(SFUtil.class);
    /**
     * 顺丰查询路由接口
     *
     * @param code
     * @param url
     * @return
     * @throws
     */
    public final static SfRouteServiceResponseEntity routeService(String code, String account, String password, String url){
        RouteRequest routeRequest = new RouteRequest();
        routeRequest.setTracking_type(1);
        routeRequest.setTracking_number(code);
        routeRequest.setMethod_type(1);
        Body body = new Body();
        body.setRouteRequest(routeRequest);
        Request request = new Request();
        request.setBody(body);
        request.setLang("zh-CN");
        request.setHead(account);
        request.setService("RouteService");
        String searchServiceXml = "";
        try {
            searchServiceXml = XmlUtil.toXmlNotHead(request);
        } catch (Exception e) {
            logger.info("=====xml解析错误===========");
        }

        final byte[] searchServiceDigest = SecurityUtil.md5Digest((searchServiceXml
                + password).getBytes(StandardCharsets.UTF_8));
        final String searchServiceVerifyCode = Base64.encode(searchServiceDigest);
        final Map<String, String> searchForm = new HashMap<>();
        searchForm.put("xml", searchServiceXml);
        searchForm.put("verifyCode", searchServiceVerifyCode);
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "routeService xml=" + searchServiceXml + ", \r\nverifyCode=" + searchServiceVerifyCode);
        }
        try {
            String response = sendSSLPostToWx(url,searchForm);
            if (Strings.isNullOrEmpty(response)) {
                if (logger.isErrorEnabled()) {
                    logger.error(ResultCodeEnum.ORDERSEARCHFAIL.getCode()+"请求顺丰 RouteService接口失败. searchXml = " + searchServiceXml
                            + "; verifyCode = " + searchServiceVerifyCode);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("call routeService response=" + response);
            }
            SfRouteServiceResponseEntity entity = (SfRouteServiceResponseEntity)XmlUtil.toObject(response, SfRouteServiceResponseEntity.class);
//            System.out.println(entity.toString());
            return entity;
        } catch (final Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ResultCodeEnum.ORDERSEARCHFAIL.getCode()+"请求顺丰 RouteService接口失败. searchXml = " + searchServiceXml
                        + "; verifyCode = " + searchServiceVerifyCode, e);
            }
            return null;
        }

    }

    /**
     * 请求微信https
     **/
    public static String sendSSLPostToWx(String url, Map<String, String> form) {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : form.entrySet()) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, Charset.forName("UTF-8"));
        httpPost.setEntity(urlEncodedFormEntity);
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String xmlStr = EntityUtils.toString(entity, "UTF-8");
            return xmlStr;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public static void main(String[] args){
//        List<RouteEntity> entity = SFUtil.routeService("802051116469","7557258112",
//                "7XwQlB4WSsNqPWeactE6XpFa7f0cKBtx","http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService");
        SfRouteServiceResponseEntity entity = SFUtil.routeService("444072971585","SZQHDS",
                "uJKzw7yjMvCYTeLk","http://218.17.248.244:11080/bsp-oisp/sfexpressService");
        if(entity.getHead().equalsIgnoreCase("OK")){
            if(entity.getBody() != null){
                RouteResponseEntity routeResponseEntity =  entity.getBody().getRouteResponse().get(0);
                if(routeResponseEntity != null){
                    List<RouteEntity> entityList = routeResponseEntity.getRouteResponse();
                    for (RouteEntity route : entityList) {
                        System.out.println(route.getAccept_time());
                        System.out.println(route.getRemark());
                        System.out.println(route.getAccept_address());
                    }
                }
            }
        }else{

        }
    }

}
