package com.iformall.utils.car;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iformall.common.ErrorCode;
import com.iformall.exception.MallinkException;
import com.iformall.utils.DateUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 尚安停车
 */
public class ShangAnUtil {
    private final static Logger logger = LoggerFactory.getLogger(ShangAnUtil.class);

    public static final String SHANGAN_URL = "url";
    public static final String SHANGAN_KEY = "key";
    public static final String SHANGAN_PARK_NUMBER = "parkNumber";

    public static final String KEY = "NzMFFDDJDIFACACCM2zAezDz";

    public static final String PARK_NUMBER = "p190829183435";

    public static final String URL = "http://www.p-share.com/shangan-yhq/web/api/outcoupon";

    public static final String SHANGAN_STATUS = "status";
    public static final String SHANGAN_SUCCESS = "success";
    public static final String SHANGAN_FAIL = "fail";
    public static final String SHANGAN_ERROR_CODE = "errorCode";


    public static final SimpleDateFormat dateInFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    public static void main(String[] args) throws Exception {
        String carNumber = "京XAZMF1";
        Date myDate = DateUtils.getHourTimeAfter(1, new Date());

        String result = couponSend(URL, KEY, PARK_NUMBER, "1", myDate, carNumber, "1500");

        JSONObject obj = JSON.parseObject(result);
    }

    /**
     * md5算法
     * @param data
     * @return
     * @throws NoSuchAlgorithmException
     */

    public static String md5(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(data.getBytes());
        StringBuilder buf = new StringBuilder();
        byte[] bits = md.digest();
        for(int i=0;i<bits.length;i++){
            int a = bits[i];
            if(a<0) a+=256;
            if(a<16) buf.append("0");
            buf.append(Integer.toHexString(a));
        }
        return buf.toString();
    }

    /**
     * 签名
     * @param key
     * @param parkNumber
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getSign(String key, String parkNumber) throws NoSuchAlgorithmException {
        String signValue = md5(key + parkNumber).toUpperCase();
        logger.debug("sign: " + signValue);
        return signValue;
    }

    public static boolean checkRespFailed(String resp) {
        if(resp.startsWith("<html>") || resp.startsWith("<!DOCTYPE html>")) {
            return true;
        }
        return false;
    }

    public static String couponSend(String url, String key, String parkNumber, String couponModelId, Date expireTime, String plate, String position) {
        Map<String, String> params = new HashMap<>();
        params.put("parkNum", parkNumber);
        params.put("couponModeId", couponModelId);
        params.put("endTime", dateInFormat.format(expireTime));
        params.put("plate", plate);
        params.put("position", position);
        try {
            String result = Proc(url, key, parkNumber, params);
            if(result == null) {
                throw new MallinkException(ErrorCode.CAR_CMD_FAIL);
            }
            if(checkRespFailed(result)) {
                throw new MallinkException(ErrorCode.CAR_CMD_FAIL);
            }
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    private static String Proc(String url, String key, String parkNumber, Map<String, String> paramMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Accept-Encoding", "UTF-8");

        String sign = null;
        try{
            sign = getSign(key, parkNumber);
            httpPost.addHeader("sign", sign);
        }catch(NoSuchAlgorithmException e) {
            logger.error(e.getLocalizedMessage());
        }

        String jsonstr = JSON.toJSONString(paramMap);
        logger.info(jsonstr);

        try {
            StringEntity se = new StringEntity(jsonstr, Consts.UTF_8);
            se.setContentType("application/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));
            httpPost.setEntity(se);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
        }

        String result = null;

        //打印StatusLine
        logger.debug("StatusLine: " + response.getStatusLine());
        try{
            //获取实体
            HttpEntity httpEntity= response.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
            logger.debug(result);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
        }

        try {                //关闭流并释放资源
            httpClient.close();
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
        }

        return result;
    }




}

