package com.winsun.utils;

import com.winsun.bean.AttributeList;
import com.winsun.constant.Constant;
import com.winsun.constant.FilePath;
import com.winsun.mapper.OrderCardAddressMapper;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import sun.misc.BASE64Encoder;

import javax.net.ssl.SSLHandshakeException;
import java.io.File;
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 {

    @Autowired
    private OrderCardAddressMapper orderCardAddressMapper;

    final String publicKey =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAok8DnvM2OBwtzNoJb4nA" +
                    "jn4lgCkSxLyRw5lLiUfsi+40h00CGAC1arvbinTTbtrSnm4YDYlaJwveiOeDKdk0" +
                    "f2Yglb/8loEbNTqb1OqNxUeM1wYLRBXvAkkZ5fZllajWzFMkoNU/JQ4+T8sMATxm" +
                    "1d1XRcgM6zlgVwX6siDoLZ5Dm23CTS7SXhyMLtS9cgLefHcOckPQyXoB/IJqb0K1" +
                    "P0Sk0PE1OSRzpsI9JVzhsSW164fwYpxEbygj9O9JAmAszixwItt2j5zLJ6zRnK3R" +
                    "OrcAVMN/vpXTN2dCLGZXQrsTK9sAWASzIWTiQRzmnwxsQY7y4u2h+k41n8Z5tw03" +
                    "wwIDAQAB";


    // 预实名接口发起
    public kong.unirest.HttpResponse<String> sendOrder(Map<String, Object> map) {
        //String str = "";
        kong.unirest.HttpResponse<String> stringHttpResponse = null;
        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);
            map.put("orderNum", "XY" + timeStr);
            map.put("imgUrl1", (String) map.get("idCardUrl1"));
            map.put("imgUrl2", (String) map.get("idCardUrl2"));
            map.put("imgUrl3", (String) map.get("idCardUrl3"));
            map.put("imgUrl4", (String) map.get("idCardUrl4"));
            //str = sendAitransOrder(map, 0);
            stringHttpResponse = sendAitransOrder(map, 0);
        } catch (Exception e) {
           log.error("预实名接口发起异常",e.getMessage());
        }

        return stringHttpResponse;
    }

    /**
     * @param map
     * @param count
     * @return
     * @throws Exception
     */
    // 保存卡品认证信息
    public kong.unirest.HttpResponse<String> sendAitransOrder(Map<String, Object> map, int count) throws Exception {
        log.info("移动下单前已有参数：" + JSONObject.fromObject(map).toString());
        Map<String, String> return_data = new HashMap<>();
        return_data.put("code", "");
        return_data.put("route", "提交下单"); //[提交下单] [订单保存] [提交审核] 默认为提交下单
        return_data.put("微信openId", "");
        return_data.put("微信appId", "");
        map.put("return_data", return_data);

        String cardAddress = orderCardAddressMapper.selectByOrderId(map.get("order_id"));

        Map<String, Object> order_data = new HashMap<>();

        Map<String, Object> attachment = new HashMap<>(); // 附件
        attachment.put("身份证照1", map.get("imgUrl1"));
        attachment.put("身份证照2", map.get("imgUrl2"));
        attachment.put("身份证照3", map.get("imgUrl3"));
        attachment.put("身份证照4", map.get("imgUrl4"));
        order_data.put("附件", attachment);

        order_data.put("代理商账号", "hyoujian");
        order_data.put("使用人姓名", "黄友健");
        order_data.put("使用人证件号", "440802199006080830");

        Map<String, Object> customerInformation = new HashMap<>(); //客户信息
        customerInformation.put("联系人", (String) map.get("userName"));
        customerInformation.put("客户证件号码", (String) map.get("idCard"));
        customerInformation.put("客户证件姓名", (String) map.get("userName"));
        customerInformation.put("联系电话", (String) map.get("linkPhone"));
        customerInformation.put("客户证件地址", cardAddress);
        customerInformation.put("客户证件类型", "身份证");
        customerInformation.put("通讯地址", (String) map.get("address"));
        order_data.put("客户信息", customerInformation);


        order_data.put("订单来源单号", (String) map.get("orderNum")); // 订单来源单号，必填； 与订单来源对应，用于业务上记录订单的来源订单编号
        order_data.put("订单备注", "");
        order_data.put("付费类型", "预付费"); //预付费、后付费、其他  选填

        Map<String, Object> packageInformation = new HashMap<>();   //揽装信息
        packageInformation.put("揽装姓名", map.get("lzUser"));
        packageInformation.put("揽装工号", map.get("lzgh"));
        order_data.put("揽装信息", packageInformation);

        HashMap<String, Object> invoiceInformation = new HashMap<>();   //发票信息
        invoiceInformation.put("发票抬头", ""); //若发票投递方式为不需要，可以不填值，但必须有参数
        invoiceInformation.put("发票投递方式", "不需要");    // 必填 一次性发票，分月发票，不需要
        invoiceInformation.put("电子邮箱", ""); //若发票投递方式为不需要，可以不填值，但必须有参数
        order_data.put("发票信息", invoiceInformation);

        order_data.put("接口下单账号", "xiaoyuan");  //接口下单账号

        HashMap<String, Object> orderingProducts = new HashMap<>();  //订购产品
        orderingProducts.put("产品名称", map.get("cardType"));
        orderingProducts.put("付费类型", "预付费");

        // 属性列表
        AttributeList userCategory = new AttributeList();
        userCategory.setName("用户类别");
        userCategory.setValue("学生");

        AttributeList studentID = new AttributeList();
        studentID.setName("学生证号");
        studentID.setValue((String) map.get("idCard"));

        AttributeList userType = new AttributeList();
        userType.setName("用户类型");
        userType.setValue((String) map.get("cardType"));

        AttributeList[] attributeList = new AttributeList[]{userCategory, studentID, userType};  //属性列表
        orderingProducts.put("属性列表", attributeList);
        order_data.put("订购产品", orderingProducts);

        Map<Object, Object> logisticsInformation = new HashMap<>();     //物流信息
        logisticsInformation.put("受理类型", "不受理");
        logisticsInformation.put("发货类型", "代理商自行发货");

        order_data.put("业务类型", "移动业务");  //业务类型
        order_data.put("办理类型", "新装主卡");  //业务类型

        List<Map<String, Object>> mobileAccessList = new ArrayList<>();    //移动接入
        Map<String, Object> mobileAccess = new HashMap<>();
        mobileAccess.put("订购类型", "新装");
        mobileAccess.put("UIM实物串号", map.get("iccId"));
        mobileAccess.put("号码类型", "主卡");
        mobileAccess.put("移动接入号", map.get("orderPhone"));
        mobileAccessList.add(mobileAccess);
        order_data.put("移动接入", mobileAccessList);

        Map<String, Object> realNameInformation = new HashMap<>();      //实名信息
        realNameInformation.put("姓名", "主卡");
        realNameInformation.put("身份证号", map.get("idCard"));
        realNameInformation.put("ICCID", map.get("iccId"));
        realNameInformation.put("证件地址", cardAddress);
        order_data.put("实名信息", realNameInformation);

        Map<String, Object> logistics = new HashMap<>();     //物流信息
        logistics.put("发货类型", "代理商自行发货");
        order_data.put("物流信息", logistics);


        Map<String, Object> map1 = new HashMap<>();
        map1.put("order_data", order_data);
        String order_dataJSON = com.alibaba.fastjson.JSONObject.toJSONString(map1);


        // 获得md5串
        String sign = MD5Util.MD5Encode(order_dataJSON, "Utf-8");
        // 获得小写md5串
        sign = sign.toLowerCase();
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        //去除换行
        sign = sign.replaceAll("\\r|\\n", "");
        log.info("移动下单接口中的携带的签名：" + sign);

        kong.unirest.HttpResponse<String> responese = null;
        try {
            log.info("提交参数:" + order_dataJSON);
            com.winsun.constant.Constant.trustEveryone();
            responese = Unirest.put("http://132.97.20.20/function/id-generator-snowflake.prod-fn?turbo=1")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("X-Sign", sign)
                    .body(order_dataJSON)
                    .asString();
            log.info("移动下单接口，返回信息:" + responese.getBody());
        } catch (ResourceAccessException e) {
            count++;
            if (count < 20) {
                responese = sendAitransOrder(map, count);
            } else {
                log.error("移动(预付费、移动、融合、续约、增值)下单接口异常尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 预付费下单接口异常");
            e.printStackTrace();
        }

        return responese;
    }

    // 保存卡品认证信息
//    public String sendAitransOrder(Map<String, Object> map, int count) throws NoSuchAlgorithmException, UnsupportedEncodingException {
//        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000)
//                .setConnectionRequestTimeout(600000)
//                .build();
//
//        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
//
//        log.info("移动下单前已有参数：" + JSONObject.fromObject(map).toString());
//        String resultStr = "";
//
//        HttpEntity entity = null;
//        //   https://icloud.mini189.cn/api/create-order.action
//        //   https://ismarttest.mini189.cn/api/create-order.action
//        HttpPost httpPost = new HttpPost("https://icloud.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", "", contentType);//
//        //订单来源单号，选填；与订单来源对应，用于业务上记录订单的来源订单编号
//        signMap.put("orderSourceNum", "");
//
//        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();
//
//        log.info("移动下单产品参数：" + productJson);
//
//        try {
//            builder.addTextBody("productJson", URLEncoder.encode(productJson, "UTF-8"), contentType);// 产品信息，必填
//            signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
//
//        //身份证正面，选填
//        File file1 = new File(map.get("imgUrl1").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
//        //身份证背面，选填
//        File file2 = new File(map.get("imgUrl2").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
//        //手持证件，选填
//        File file3 = new File(map.get("imgUrl3").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
//        //手持证件2，选填
//        File file4 = new File(map.get("imgUrl4").toString().replace("manager/ciop", FilePath.BACKGROUNDIMG.getValue()).replace("\\", "/"));
//
//        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 = CommonMd5.encryption(plaintext);// md5加密
//        builder.addTextBody("sign", sign, contentType);// 签名，必填
//
//        log.info("移动智能平台下单参数：" + plaintext);
//
//        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();
//            Constant.trustEveryone();
//            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 (SSLHandshakeException s) {
//            count++;
//            if (count < 20) {
//                resultStr = sendAitransOrder(map, count);
//            } else {
//                log.error("[HTTP] [CREATE_ORDER] 预付费下单接口异常20次");
//            }
//        } 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://icloud.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://icloud.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://icloud.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"));

            HttpResponse response = httpclient.execute(httpPost);

            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");
            httpclient.close();
            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://icloud.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"));

            HttpResponse response = httpclient.execute(httpPost);

            entity = response.getEntity();

            String httpResult = EntityUtils.toString(entity, "UTF-8");
            httpclient.close();
            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");
                    log.info("单宽智能平台订单返回状态码：" + 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;
    }


}
