package com.winsun.utils;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class OrderManage {


    // 预实名接口发起
    public String sendOrder(Map<String, Object> map) {
        String str = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timeStr = simpleDateFormat.format(new Date());
            String cardType = (String) map.get("cardType");

            if (cardType.contains("大王卡")) {
                map.put("productId", "483");
                map.put("salesId", "1185");
            } else if (cardType.contains("天翼学生证")) {
                map.put("productId", "1327");
                map.put("salesId", "4453");
            } else {
                map.put("productId", "727");
                map.put("salesId", "2137");
            }

            map.put("timeStr", timeStr);
            str = sendAitransOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }

    // 保存卡品认证信息
    public String sendAitransOrder(Map<String, Object> map) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000)
                .setConnectionRequestTimeout(600000).build();

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();


        String resultStr = "";

        HttpEntity entity = null;
        //   https://ismart.mini189.cn/api/create-order.action
        //   https://ismarttest.mini189.cn/api/create-order.action
        HttpPost httpPost = new HttpPost("https://ismart.mini189.cn/api/create-order.action");

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        Map<String, String> signMap = new HashMap<String, String>();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Charset.forName("UTF-8"));

        builder.addTextBody("service", "order.prepaidgift.create", contentType);// api标识，必填且唯一
        signMap.put("service", "order.prepaidgift.create");


        builder.addTextBody("userName", (String) map.get("ysmUser"), contentType);// 用户名，必填
        signMap.put("userName", (String) map.get("ysmUser"));


        builder.addTextBody("timeStamp", (String) map.get("timeStr"), contentType);// 时间戳（YYYYMMDDHHMMSS），必填

        signMap.put("timeStamp", (String) map.get("timeStr"));

        builder.addTextBody("productCategory", "预付费礼包", contentType);// 业务类型，必填且唯一

        signMap.put("productCategory", "预付费礼包");

        builder.addTextBody("govEntCustomer", "0", contentType);// 是否政企客户下单:0：否，1：是，必填

        signMap.put("govEntCustomer", "0");

        builder.addTextBody("agentName", "", contentType);// 代办人姓名（若是政企客户下单必填）
        signMap.put("agentName", "");

        builder.addTextBody("agentCardNum", "", contentType);// 代办人身份证号码（若是政企客户下单必填）
        signMap.put("agentCardNum", "");

        builder.addTextBody("customerName", (String) map.get("userName"), contentType);// 客户姓名，必填
        signMap.put("customerName", (String) map.get("userName"));

        builder.addTextBody("customerPhone", (String) map.get("linkPhone"), contentType);// 客户(代办人)电话，必填
        signMap.put("customerPhone", (String) map.get("linkPhone"));

        builder.addTextBody("customerCardType", "身份证", contentType);// 证件类型，必填
        signMap.put("customerCardType", "身份证");

        builder.addTextBody("customerCardNum", (String) map.get("idCard"), contentType);// 证件号码，必填
        signMap.put("customerCardNum", (String) map.get("idCard"));

        builder.addTextBody("landId", "44094951", contentType);// 揽装工号，必填
        signMap.put("landId", "44094951");

        builder.addTextBody("comarketingLanId", "", contentType);// 协销工号，选填
        signMap.put("comarketingLanId", "");

        builder.addTextBody("groupComarketingLanId", "", contentType);//集团协销工号，选填
        signMap.put("groupComarketingLanId", "");

        builder.addTextBody("orderOutNum", (String) map.get("orderNum"), contentType);//外部订单编号，选填!；
        //通过API接口下单，必须传入一个外部接入商的订单编号,该编号与智能营销系统编号一一对应
        signMap.put("orderOutNum", (String) map.get("orderNum"));

        builder.addTextBody("orderSource", "校园合伙人", contentType);// 订单来源 ，选填
        signMap.put("orderSource", "校园合伙人");

        builder.addTextBody("orderSourceNum", (String) map.get("orderNum"), contentType);//
        //订单来源单号，选填；与订单来源对应，用于业务上记录订单的来源订单编号
        signMap.put("orderSourceNum", (String) map.get("orderNum"));

        builder.addTextBody("salePointCode", "", contentType);// 销售点编码，选填
        signMap.put("salePointCode", "");

        builder.addTextBody("personCode", "", contentType);// 人员编码，选填
        signMap.put("personCode", "");

        builder.addTextBody("distributorSmsReceive", "", contentType);// 分销商短信接收号码，选填
        signMap.put("distributorSmsReceive", "");


        builder.addTextBody("batchPickUp", "0", contentType);// 是否批量提货，必填
        // 0：否，1：是
        signMap.put("batchPickUp", "0");

        builder.addTextBody("deliveryProvince", (String) map.get("sheng"), contentType);// 配送地址-省，必填
        signMap.put("deliveryProvince", (String) map.get("sheng"));

        builder.addTextBody("deliveryCity", (String) map.get("shi"), contentType);// 配送地址-市，必填
        signMap.put("deliveryCity", (String) map.get("shi"));

        builder.addTextBody("deliveryDistrict", (String) map.get("xian"), contentType);// 配送地址-区，必填
        signMap.put("deliveryDistrict", (String) map.get("xian"));

        builder.addTextBody("deliveryAddress", (String) map.get("address"), contentType);// 配送地址-详细地址，必填
        signMap.put("deliveryAddress", (String) map.get("address"));

        builder.addTextBody("deliveryContact", (String) map.get("userName"), contentType);// 联系人，必填
        signMap.put("deliveryContact", (String) map.get("userName"));

        builder.addTextBody("deliveryContactPhone", (String) map.get("linkPhone"), contentType);// 联系电话，必填
        signMap.put("deliveryContactPhone", (String) map.get("linkPhone"));

        builder.addTextBody("deliveryContactPhone2", "", contentType);// 联系电话2，选填
        signMap.put("deliveryContactPhone2", "");

        builder.addTextBody("invoiced", "0", contentType);// 是否需要发票，必填 0:不需要；1:一次性发票；2:分月发票

        signMap.put("invoiced", "0");

        builder.addTextBody("invoiceTitle", "", contentType);// 发票抬头，若需要发票必填
        signMap.put("invoiceTitle", "");

        builder.addTextBody("invoiceDeliveryAddress", "", contentType);// 电子邮箱，若需要发票必填
        signMap.put("invoiceDeliveryAddress", "");

        builder.addTextBody("deliveryType", "代理商自行发货", contentType);// 发货类型，必填，填写只能填同德仓发货或者代理商自行发货或者  现场派卡（其它信息的要求与代理商自行发货类似）
        signMap.put("deliveryType", "代理商自行发货");// 若填写代理商自行发货或现场派卡，则下单时有几个产品，就需要填写多少个实物串号

        builder.addTextBody("deliveryCompany", "", contentType);// 配送公司，必填，填写只能填顺丰速运或者如风达或者京东快递或者EMS
        signMap.put("deliveryCompany", "");// 若发货类型选择代理商自行发货，则不用填写(填写也无效)

        builder.addTextBody("collection", "", contentType);// 回收资料，选填，若填写只能填写1(表示身份证复印件)
        signMap.put("collection", "");

        builder.addTextBody("gift", "", contentType);// 礼品，选填，请通过礼品列表接口获取
        signMap.put("gift", "");

        builder.addTextBody("giftNum", "", contentType);// 礼品数量，选填，若礼品填写则必填且为正整数
        signMap.put("giftNum", "");

        List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>();// 产品信息
        List<Map<String, Object>> paymentList = new ArrayList<Map<String, Object>>();// 销售品信息(费用项)
        List<Map<String, Object>> inPropertyList = new ArrayList<Map<String, Object>>();// 产品属性
        List<Map<String, Object>> appendPropertyList = new ArrayList<Map<String, Object>>();// 产品附加扩展属性
        List<Map<String, Object>> addPropertyList = new ArrayList<Map<String, Object>>();// 自定义产品属性
        // 下单产品(如有多个请建立多个map，但产品总数不能超过5个)
        Map<String, Object> productMap = new HashMap<String, Object>();
        // 产品
        productMap.put("productId", map.get("productId"));// 产品id,必填，请通过产品列表接口获取
        productMap.put("count", "");// 产品数量,选填(若不填默认为1)
        // 该数量仅供发货类型为同德仓发货且批量提货为否时填写，若选择代理商自行发货或批量提货为是，则填写无效
        productMap.put("count2", "");// 产品数量,选填(若不填默认为1);该数量仅供批量提货为是时使用
        // 若选择批量提货为否时，则填写无效
        productMap.put("sn", map.get("iccId"));// 实物串号,选填(若选择代理商自行发货，必填;其他情况填写无效)

        // 销售品信息(费用项)必填，若有终端，请将费用项填写在此
        Map<String, Object> paymentListMap = new HashMap<String, Object>();
        paymentListMap.put("id", map.get("salesId"));// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
        paymentListMap.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
        paymentListMap.put("saleAmount", "");// 售价，选填
        paymentListMap.put("payType", "3");// 缴费方式，必填（例：payType：3）3：代理商打款4：穗易付7：货到付款9：第三方托收
        paymentListMap.put("payAmount", "0");// 打款金额（支付金额），若选择代理商打款或者穗易付，此项必填
        paymentListMap.put("saleAmount", "");// 打款金额，若选择货到付款，此项必填
        paymentListMap.put("payPlatform", "");// 支付平台，若选择穗易付，此项必填
        paymentListMap.put("electronicPayNumber", "");// 支付流水号，若选择穗易付，此项必填
        paymentListMap.put("payOrderNumber", "");// 穗易付订单号，若选择穗易付，此项必填
        paymentListMap.put("monthUserid", "");//用户ID，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthPlatform", "");//签约平台，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthFlowno", "");//签约流水号，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthNumber", "");//签约协议号，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthTime", "");//签约时间，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthEffectiveTime", "");//签约生效时间，缴费方式为“第三方托收”时必填
        paymentListMap.put("monthUneffectiveTime", "");//签约失效时间，缴费方式为“第三方托收”时必填

        paymentList.add(paymentListMap);

        productMap.put("payment", paymentList);

        // 产品属性 必填业务号码属性,name=业务号码,value=11位数字或者随机；若还有其他属性可建立多个map添加
        // 若发货类型选择代理商自行发货,则该value值必须填写11位数字
        Map<String, Object> inPropertyListMap = new HashMap<String, Object>();
        inPropertyListMap.put("name", "业务号码");
        inPropertyListMap.put("value", map.get("orderPhone"));
        inPropertyList.add(inPropertyListMap);
        productMap.put("inpProperties", inPropertyList);

        // 产品自定义属性；选填,没有则为null
        // 注：若填写请属性名和属性值都填写，若只填写其中一项则无效
        Map<String, Object> addPropertyListMap = new HashMap<String, Object>();
        addPropertyListMap.put("name", null);
        addPropertyListMap.put("value", null);
        addPropertyList.add(addPropertyListMap);
        productMap.put("addProperties", addPropertyList);

        productList.add(productMap);

        // 将对象装换为json字符串
        String productJson = JSONArray.fromObject(productList).toString();
        try {
            builder.addTextBody("productJson", URLEncoder.encode(productJson, "UTF-8"), contentType);// 产品信息，必填
            signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //身份证正面，选填
        File file1 = new File((String) map.get("imgUrl1"));
        //身份证背面，选填
        File file2 = new File((String) map.get("imgUrl2"));
        //手持证件，选填
        File file3 = new File((String) map.get("imgUrl3"));
        //手持证件2，选填
        File file4 = new File((String) map.get("imgUrl4"));

        if (file1 != null) {
            ContentBody sfzzmFile = new FileBody(file1);
            builder.addPart("sfzzmFile", sfzzmFile);
        }
        if (file2 != null) {
            ContentBody sfzbmFile = new FileBody(file2);
            builder.addPart("sfzbmFile", sfzbmFile);
        }
        if (file3 != null) {
            ContentBody sfzscFile = new FileBody(file3);
            builder.addPart("sfzscFile", sfzscFile);
        }
        if (file4 != null) {
            ContentBody sfzsc2File = new FileBody(file4);
            builder.addPart("sfzsc2File", sfzsc2File);
        }

        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());
        Collections.sort(keys);// key按字符串升序
        String value, plaintext = "";

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }

        plaintext = plaintext.concat((String) map.get("sign"));


        String sign = MD5Utils.md5(plaintext);// md5加密
        builder.addTextBody("sign", sign, contentType);// 签名，必填

        try {

            //httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(builder.build());
            //System.out.println("[CREATE_ORDER]移动产品下单接口，提交参数" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));

            long startTime = System.currentTimeMillis();
            HttpResponse response = httpclient.execute(httpPost);
            long endTime = System.currentTimeMillis();
            log.info("接口调用时间：" + (endTime - startTime) + "ms");


            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");
            resultStr = httpResult;

            log.info("[CREATE_ORDER]预付费下单接口，返回信息:" + httpResult);
            httpclient.close();
            JSONObject resultDataJson = JSONObject.fromObject(httpResult);

            String isSuccess = resultDataJson.getString("status");
            String orderNum = resultDataJson.getString("orderNumber");
            if ("000001".equals(isSuccess)) {
                log.info("[CREATE_ORDER]下单成功,orderNum=" + orderNum);
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 预付费下单接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }

        return resultStr;
    }

    // 查询移互平台产品列表
    public String queryProduct() throws NoSuchAlgorithmException, UnsupportedEncodingException {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>();//待签名参数
        String resultStr = "";

        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = simpleDateFormat.format(new Date());

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost("https://ismart.mini189.cn/api/create-order.action");

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        qParams.add(new BasicNameValuePair("service", "product.prepaid.query"));//api标识，必填
        signMap.put("service", "product.prepaid.query");
        //product.broadband.query为单宽带,product.prepaid.query为预付费,product.mobile.query为移动产品,product.combined.query为融合产品
        //product.kdxy.query为宽带续约,product.zzyw.query为增值业务
        qParams.add(new BasicNameValuePair("userName", "ruany"));//用户名，必填
        signMap.put("userName", "ruany");
        qParams.add(new BasicNameValuePair("timeStamp", timeStr));//时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", timeStr);
        qParams.add(new BasicNameValuePair("business", "预付费礼包"));//产品类型，必填
        signMap.put("business", "预付费礼包");
        //填写单宽带,预付费礼包,移动产品,融合产品,宽带续约,增值业务

        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());

        Collections.sort(keys);//key按字符串升序
        String value, plaintext = "";

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }
        plaintext = plaintext.concat("3df143292455bfea88bc613c53004d36");

        String sign = MD5Utils.md5(plaintext);//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填

        try {

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info("[CREATE_ORDER]单宽带(预付费、移动、融合、续约、增值)下单接口，提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));

            HttpResponse response = httpclient.execute(httpPost);

            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");

            log.info("[CREATE_ORDER]单宽带(预付费、移动、融合、续约、增值)下单接口，返回信息:" + httpResult);

            JSONObject resultDataJson = JSONObject.fromObject(httpResult);
            resultStr = httpResult;

            String isSuccess = resultDataJson.getString("status");
            //JSONArray jsonArray = resultDataJson.getJSONArray("list");
            if ("000001".equals(isSuccess)) {
                log.info("[CREATE_ORDER]查询单宽带(预付费、移动、融合、续约、增值)产品成功,list=" + resultDataJson.toString());
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 查询单宽带(预付费、移动、融合、续约、增值)产品接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }

        return resultStr;
    }

    // 查询移互平台产品销售Id
    public String querySalesId() throws NoSuchAlgorithmException, UnsupportedEncodingException {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>();//待签名参数
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost("https://ismart.mini189.cn/api/create-order.action");

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = simpleDateFormat.format(new Date());

        qParams.add(new BasicNameValuePair("service", "sale.query"));//api标识，必填
        signMap.put("service", "sale.query");
        qParams.add(new BasicNameValuePair("userName", "ruany"));//用户名，必填
        signMap.put("userName", "ruany");
        qParams.add(new BasicNameValuePair("timeStamp", timeStr));//时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", timeStr);
        qParams.add(new BasicNameValuePair("productId", "729"));//产品ID
        signMap.put("productId", "729");

        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());

        Collections.sort(keys);//key按字符串升序
        String value, plaintext = "";
        String result = "";

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }
        plaintext = plaintext.concat("3df143292455bfea88bc613c53004d36");

        String sign = MD5Utils.md5(plaintext);//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填

        try {

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info(
                    "[CREATE_ORDER]获取销售品列表接口，提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));

            HttpResponse response = httpclient.execute(httpPost);

            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");

            log.info("[CREATE_ORDER]获取销售品列表接口，返回信息:" + httpResult);

            JSONObject resultDataJson = JSONObject.fromObject(httpResult);

            String isSuccess = resultDataJson.getString("status");
            JSONArray jsonArray = resultDataJson.getJSONArray("list");
            if ("000001".equals(isSuccess)) {
                log.info("[CREATE_ORDER]获取销售品成功,list=" + jsonArray.toString());
            }

            result = httpResult;
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }

        return result;
    }

    // 智能平台订单查询接口
    public String queryOrder(Map<String, Object> map) throws Exception {
        String result = "";

        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>();//待签名参数

        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost("https://ismart.mini189.cn/api/query.action");

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = simpleDateFormat.format(new Date());
        map.put("timeStr", timeStr);

        qParams.add(new BasicNameValuePair("service", "query.order.status"));//api标识，必填
        signMap.put("service", "query.order.status");

        qParams.add(new BasicNameValuePair("userName", (String) map.get("ysmUser")));//用户名，必填
        signMap.put("userName", (String) map.get("ysmUser"));

        qParams.add(new BasicNameValuePair("timeStamp", (String) map.get("timeStr")));//时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", (String) map.get("timeStr"));

        qParams.add(new BasicNameValuePair("orderNumber", (String) map.get("znOrderNum")));//智能平台订单编号，非必填
        signMap.put("orderNumber", (String) map.get("znOrderNum"));
        qParams.add(new BasicNameValuePair("outOrderNum", ""));//外部订单编号，非必填
        signMap.put("outOrderNum", "");

        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());

        Collections.sort(keys);//key按字符串升序
        String value, plaintext = "";

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }

        plaintext = plaintext.concat((String) map.get("sign"));

        String sign = MD5Utils.md5(plaintext);//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填

        try {

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
//			System.out.println(
//					"[CREATE_ORDER]获取销售品列表接口，提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));

            HttpResponse response = httpclient.execute(httpPost);

            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");
            httpclient.close();
//			System.out.println("[CREATE_ORDER]获取销售品列表接口，返回信息:" + httpResult);
            if (httpResult.equals("\r\n\r\nnull\r\n\r\n")) {

            } else {
                JSONObject resultDataJson = JSONObject.fromObject(httpResult);

                String isSuccess = resultDataJson.getString("status");
                result = httpResult;
                if ("000001".equals(isSuccess)) {
                    log.info("[CREATE_ORDER]获取销售品成功,list=" + resultDataJson.toString());
                    String stateName = resultDataJson.getString("stateName");
                    if (stateName.equals("待配送") || stateName.equals("物流配送中")) {
                        return "1";
                    } else if (stateName.equals("待图片审核") || stateName.equals("作废")) {
                        return "0";
                    }

                }
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();

        }

        return result;
    }

    // 智能平台订单查询接口，定时任务根据智能平台返回的订单号去查询更新 order_view表的订单状态
    public Map<String, Object> queryOrder2(Map<String, Object> map) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = "";
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>();//待签名参数

        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost("https://ismart.mini189.cn/api/query.action");

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = simpleDateFormat.format(new Date());
        map.put("timeStr", timeStr);

        qParams.add(new BasicNameValuePair("service", "query.order.status"));//api标识，必填
        signMap.put("service", "query.order.status");

        qParams.add(new BasicNameValuePair("userName", (String) map.get("ysmUser")));//用户名，必填
        signMap.put("userName", (String) map.get("ysmUser"));

        qParams.add(new BasicNameValuePair("timeStamp", (String) map.get("timeStr")));//时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", (String) map.get("timeStr"));

        qParams.add(new BasicNameValuePair("orderNumber", (String) map.get("znOrderNum")));//智能平台订单编号，非必填
        signMap.put("orderNumber", (String) map.get("znOrderNum"));
        qParams.add(new BasicNameValuePair("outOrderNum", ""));//外部订单编号，非必填
        signMap.put("outOrderNum", "");

        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());

        Collections.sort(keys);//key按字符串升序
        String value, plaintext = "";

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }

        plaintext = plaintext.concat((String) map.get("sign"));

        String sign = MD5Utils.md5(plaintext);//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填

        try {

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
//				System.out.println(
//						"[CREATE_ORDER]获取销售品列表接口，提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));

            HttpResponse response = httpclient.execute(httpPost);

            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");
            httpclient.close();
//				System.out.println("[CREATE_ORDER]获取销售品列表接口，返回信息:" + httpResult);
            if (httpResult.equals("\r\n\r\nnull\r\n\r\n")) {

            } else {
				/*
				 * 状态ID	  状态名称
					1	未受理
					9	受理成功【待收费】
					8	待分销商审核
					11	归档
					12	待提交
					13	作废
					18	分销商作废
					14	受理异常
					25	待疑难支撑审核
					10	已收费【待竣工】
					3	待分局审核
				 */
                JSONObject resultDataJson = JSONObject.fromObject(httpResult);
                String isSuccess = resultDataJson.getString("status");
                result = httpResult;
                resultMap.put("result", result);
                if ("000001".equals(isSuccess)) {
                    log.info("[CREATE_ORDER]获取销售品成功,list=" + resultDataJson.toString());
                    String state = resultDataJson.getString("state");
                    System.out.println("单宽智能平台订单返回状态码：" + state);
                    if ("10".equals(state) || "11".equals(state)) {
                        resultMap.put("type", "已完成");
                        resultMap.put("state", state);
                        return resultMap;
                    } else if ("1".equals(state) || "3".equals(state) || "8".equals(state) || "9".equals(state) || "12".equals(state) || "25".equals(state)) {
                        resultMap.put("type", "办理中");
                        resultMap.put("state", state);
                        return resultMap;
                    } else if ("13".equals(state) || "14".equals(state) || "18".equals(state)) {
                        resultMap.put("type", "异常单");
                        resultMap.put("state", state);
                        return resultMap;
                    }
                }
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();

        }

        return resultMap;
    }


}
