package com.winsun.outSideSystem;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winsun.auth.core.util.DateUtil;
import com.winsun.bean.Order;
import com.winsun.bean.OrderHistory;
import com.winsun.bean.OrderView;
import com.winsun.bean.UniversityInfo;
import com.winsun.constant.Constant;
import com.winsun.mapper.*;
import com.winsun.utils.BeanUtil;
import com.winsun.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLHandshakeException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author chengfengluo
 * @date 2021-01-28 15:36
 */
@Slf4j
@Component
public class IntelligenceSendOrder {

    @Autowired
    private UniversityInfoMapper universityInfoMapper;

    @Autowired
    private OrderViewMapper orderViewMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private OrderHistoryMapper orderHistoryMapper;

    /**
     * 单宽下单公共类
     * @param order hhr_order map类型
     */
    public void singleBroadSendOrder(Map<String, Object> order) {
        try {
            // 初始化下单支付参数
            String ORDERSEQ = "", ORDERAMOUNT = "", ORDERREQTRANSEQ = "", UPTRANSEQ = "";

            if (order.get("kd_order_id") == null) {
                log.info("kd_order_id为空。");
                return;
            }
            Map<String, Object> orderMap = null;
            Map<String, Object> schoolMap = null;
            List<Map<String, Object>> list1 = new ArrayList<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String currentTimeStr = "";
            ORDERSEQ = order.get("kd_order_id").toString();
            currentTimeStr = simpleDateFormat.format(new Date());
            Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
            orderViewWrapper.eq("orderSeq", ORDERSEQ);
            List<Map<String, Object>> orderViewMaps = orderViewMapper.selectMaps(orderViewWrapper);
            if (orderViewMaps != null && orderViewMaps.size() > 0) {
                orderMap = orderViewMaps.get(0);
            }
            if (orderMap == null) {
                log.info("错误记录：" + JSONObject.toJSONString(order));
                log.info("订单号：" + ORDERSEQ + "，在order_view表中无记录，无法进行智能平台下单");
                return;
            }
            ORDERAMOUNT = orderMap.get("webOrderAmount") != null ? orderMap.get("webOrderAmount").toString() : "0";
            ORDERREQTRANSEQ = orderMap.get("orderReqtranSeq") != null ? orderMap.get("orderReqtranSeq").toString() : "";
            UPTRANSEQ = orderMap.get("uptranseq") != null ? orderMap.get("uptranseq").toString() : "";

            // 根据学校名称，获取该学校信息
            List<Map<String, Object>> hehuoren_id =
                    universityInfoMapper.selectProductManager(order.get("hehuoren_id").toString());
            if (hehuoren_id.size() > 0 && hehuoren_id.get(0).get("university_id") != null) {
                Wrapper<UniversityInfo> universityInfoWrapper = new EntityWrapper<>();
                universityInfoWrapper.eq("university_id", hehuoren_id.get(0).get("university_id").toString());
                List<Map<String, Object>> findUniversityById = universityInfoMapper.selectMaps(universityInfoWrapper);
                schoolMap = findUniversityById.get(0);
            } else {

                Wrapper<UniversityInfo> universityInfoWrapper = new EntityWrapper<>();
                universityInfoWrapper.eq("university_name", orderMap.get("orderUniversityName"));
                universityInfoWrapper.eq("university_region", orderMap.get("orderRegion"));
                list1 = universityInfoMapper.selectMaps(universityInfoWrapper);

                schoolMap = list1.get(0);
            }

            if (orderMap.get("orderSeqThd") == null || "".equals(orderMap.get("orderSeqThd"))) {
                //	1、获取产品ID
                JSONObject productJsonObject = getProductId(currentTimeStr, 0);
                log.info("----------调用智能平台的产品接口返回参数：" + productJsonObject);
                //	2、获取销售品ID
                if (productJsonObject.toString().indexOf("list") == -1) {
                    return;
                }
                JSONArray list = productJsonObject.getJSONArray("list");
                String productId = null; // 产品id
                ORDERAMOUNT = ORDERAMOUNT.replace("元", "");
                ORDERAMOUNT = ORDERAMOUNT.replace(".00", "");

                String productName = "校园宽带" + ORDERAMOUNT + "元";

                if (ORDERAMOUNT.contains("0.01")) {
                    productName = "校园宽带30元";
                } else if (ORDERAMOUNT.contains("0.02")) {
                    productName = "校园宽带300元";
                }

                if(productName.equals("校园宽带0元")){
                    productName = "校园宽带（免月租）";
                    ORDERAMOUNT = "0";
                    ORDERREQTRANSEQ = "00000";
                    UPTRANSEQ = "00000";
                }
                System.out.println("------" + productName);
                //		productName = "校园宽带30元";
                for (int i = 0; i < list.size(); i++) {
                    net.sf.json.JSONObject itmeJson = net.sf.json.JSONObject.fromObject(list.get(i));
                    // 判断获取的全部产品与订单产品符合的拿取对应的ID
                    if (itmeJson.getString("name").indexOf(productName) != -1) {
                        productId = itmeJson.getString("id"); // 获取对应产品ID
                        break;
                    }
                }
                log.info("----------根据返回参数获取产品ID：" + productId);
                String saleId = null; // 销售id
                JSONObject saleJsonObject = getSaleId(productId, currentTimeStr, 0); // 获取销售ID
                log.info("----------调用智能平台的获取销售品接口返回值：" + saleJsonObject);
                JSONArray saleList = saleJsonObject.getJSONArray("list");
                net.sf.json.JSONObject itmeJson = net.sf.json.JSONObject.fromObject(saleList.get(0));
                saleId = itmeJson.getString("saleId");

                setPriceIndex(schoolMap, orderMap, ORDERAMOUNT);


                //	3、提交订单到智能平台
                JSONObject submitOrderJsonObject =
                        getOrderInfo(
                                schoolMap,
                                orderMap,
                                currentTimeStr,
                                productId,
                                saleId,
                                ORDERSEQ,
                                UPTRANSEQ,
                                ORDERAMOUNT,
                                ORDERREQTRANSEQ,
                                0);
                log.info(
                        "----------调用单宽带接口（提交订单至智能平台）并返回参数信息---status:"
                                + submitOrderJsonObject.get("status")
                                + " msg:"
                                + submitOrderJsonObject.get("msg")
                                + " orderNum:"
                                + submitOrderJsonObject.get("orderNumber"));

                //	4、查询智能订单是否存在
                String orderNum = (String) submitOrderJsonObject.get("orderNumber");
                JSONObject queryOrderJsonObject = null;
                if (StringUtils.isNotBlank(orderNum)) {
                    queryOrderJsonObject = getQueryOrderInfo(orderNum, currentTimeStr, 0);
                    log.info("----------调用查询智能订单接口并返回参数信息:" + queryOrderJsonObject);
                    /*	5、更新数据库   */
                    String state = queryOrderJsonObject.getString("state");
                    // 更新hhr_order
                    Wrapper<Order> orderWrapper = new EntityWrapper<>();
                    orderWrapper.eq("kd_order_id", order.get("kd_order_id"));
                    Order updateOrder = new Order();
                    updateOrder.setOrderId(orderNum);
                    updateOrder.setOrderStatus("审核中");
                    orderMapper.update(updateOrder, orderWrapper);

                    log.info("支付成功后更新订单状态");
                    OrderView updateOrderView = new OrderView();
                    updateOrderView.setStatus(QueOrderNum(state));
                    updateOrderView.setOrderseqThd(orderNum);
                    Wrapper<OrderView> wrapperOrderView = new EntityWrapper<>();
                    wrapperOrderView.eq("orderSeq", order.get("kd_order_id").toString());
                    orderViewMapper.update(updateOrderView, wrapperOrderView);
                    log.info("----------将智能订单状态更新至数据库success：" + state);
                }else{
                    // 报错更新提示
                    Wrapper<Order> orderWrapper = new EntityWrapper<>();
                    orderWrapper.eq("kd_order_id", order.get("kd_order_id"));
                    Order updateOrder = new Order();
                    updateOrder.setMsg(submitOrderJsonObject.getString("msg"));
                    orderMapper.update(updateOrder, orderWrapper);
                }
            } else {
                log.info(
                        "---单宽支付接口推送---"
                                + ORDERSEQ
                                + "---"
                                + UPTRANSEQ
                                + "---"
                                + ORDERAMOUNT
                                + "---"
                                + ORDERREQTRANSEQ);
                log.info("重复订单");
            }
        }catch (Exception e){
            log.info("单宽下单失败");
            e.printStackTrace();
        }
    }

    private void setPriceIndex(Map<String, Object> schoolMap, Map<String, Object> orderMap, String ORDERAMOUNT) {
        try {
            // 获取金额下标
            if (schoolMap.get("universityMonthlyRentType") != null && orderMap.get("setMealIndex") != null) {
                Integer index = 0;
                String setMealIndex = orderMap.get("setMealIndex").toString();
                if ("".equals(setMealIndex) || !setMealIndex.matches("[0-9]*")) {
                    if(ORDERAMOUNT.equals("50元")&&orderMap.get("orderSetMeal").equals("20M包月")){
                        schoolMap.put("universityMonthlyRentType","包月50元");
                    }
                }else {
                    index = Integer.parseInt(setMealIndex);
                    String[] university_monthly_rent_type = schoolMap.get("universityMonthlyRentType").toString().split(",");
                    if (university_monthly_rent_type.length > index) {
                        schoolMap.put("universityMonthlyRentType", university_monthly_rent_type[index]);
                    }else {
                        schoolMap.put("universityMonthlyRentType", university_monthly_rent_type[0]);
                    }
                }
            }else{
                if(ORDERAMOUNT.equals("50元")&&orderMap.get("order_set_meal").equals("20M包月")){
                    schoolMap.put("universityMonthlyRentType","包月50元");
                }
            }
        }catch( Exception e) {
            log.info(e.toString());
            e.printStackTrace();
        }
    }

    private JSONObject getQueryOrderInfo(
            String orderNum, String currentTimeStr, int count) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig =
                RequestConfig.custom()
                        .setSocketTimeout(50000)
                        .setConnectTimeout(50000)
                        .setConnectionRequestTimeout(50000)
//                        .setProxy(proxy)
                        .build();
        CloseableHttpClient httpclient =
                HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "query.action");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

        Map<String, String> signMap = new HashMap<String, String>(); // 待签名参数
        qParams.add(new BasicNameValuePair("service", "query.order.status")); // api标识，必填
        signMap.put("service", "query.order.status");
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON)); // 用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        qParams.add(new BasicNameValuePair("timeStamp", currentTimeStr)); // 时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", currentTimeStr);
        qParams.add(new BasicNameValuePair("orderNumber", orderNum)); // 智能平台订单编号，非必填
        signMap.put("outOrderNum", orderNum);
        //		qParams.add(new BasicNameValuePair("outOrderNum","13888888888"));//外部订单编号，非必填
        //		signMap.put("outOrderNum","13888888888");
        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(Constant.ZHANGSHIKEY);
        qParams.add(
                new BasicNameValuePair(
                        "sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)))); // 签名，必填
        JSONObject resultDataJson = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
            Constant.trustEveryone();
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            resultDataJson = JSONObject.parseObject(httpResult);
        } catch (SSLHandshakeException s) {
            count++;
            if (count < 20) {
                resultDataJson = getQueryOrderInfo(orderNum, currentTimeStr, count);
            } else {
                log.error("单宽下单接口尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.error("接口异常   " + e.getMessage());
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }

    /**
     * 	获取订单信息
     * @param schoolMap
     * @param orderMap
     * @param currentTimeStr
     * @param productId
     * @param saleId
     * @param ORDERSEQ
     * @param UPTRANSEQ
     * @param ORDERAMOUNT
     * @param ORDERREQTRANSEQ
     * @param count
     * @return
     * @throws Exception
     */
    private JSONObject getOrderInfo(
            Map<String, Object> schoolMap,
            Map<String, Object> orderMap,
            String currentTimeStr,
            String productId,
            String saleId,
            String ORDERSEQ,
            String UPTRANSEQ,
            String ORDERAMOUNT,
            String ORDERREQTRANSEQ,
            int count)
            throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig =
                RequestConfig.custom()
                        .setSocketTimeout(50000)
                        .setConnectTimeout(50000)
                        .setConnectionRequestTimeout(50000)
//                        .setProxy(proxy)
                        .build();
        CloseableHttpClient httpclient =
                HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "create-order.action");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);

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

        qParams.add(new BasicNameValuePair("service", "order.broadband.create")); // api标识，必填
        signMap.put("service", "order.broadband.create"); // api标识，必填
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON)); // 用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        qParams.add(new BasicNameValuePair("timeStamp", currentTimeStr)); // 时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", currentTimeStr);
        qParams.add(new BasicNameValuePair("productCategory", "单宽带")); // 业务类型 ，必填
        signMap.put("productCategory", "单宽带");
        qParams.add(new BasicNameValuePair("customerType", "2")); // 客户类型 （1：已有固话，未有宽带 2：未有固话和宽带），必填
        signMap.put("customerType", "2");
        qParams.add(new BasicNameValuePair("fixedPhoneNum", "")); // 客户类型为1时，固话号码，必填
        signMap.put("fixedPhoneNum", "");
        qParams.add(new BasicNameValuePair("govEntCustomer", "0")); // 是否政企客户下单 0：否 1：是，必填
        signMap.put("govEntCustomer", "0");
        qParams.add(new BasicNameValuePair("agentName", "")); // 若是政企客户下单，代办人姓名，必填
        signMap.put("agentName", "");
        qParams.add(new BasicNameValuePair("agentCardNum", "")); // 若是政企客户下单，代办人身份证号码，必填
        signMap.put("agentCardNum", "");
        qParams.add(
                new BasicNameValuePair("customerName", (String) orderMap.get("orderName"))); // 客户姓名，必填
        signMap.put("customerName", (String) orderMap.get("orderName"));
        qParams.add(
                new BasicNameValuePair("customerPhone", (String) orderMap.get("orderPhone"))); // 客户电话，必填
        signMap.put("customerPhone", (String) orderMap.get("orderPhone"));
        qParams.add(new BasicNameValuePair("customerCardType", "身份证")); // 证件类型，必填
        signMap.put("customerCardType", "身份证");
        qParams.add(
                new BasicNameValuePair("customerCardNum", (String) orderMap.get("orderNumber"))); // 证件号码，必填
        signMap.put("customerCardNum", (String) orderMap.get("orderNumber"));
        qParams.add(new BasicNameValuePair("addressProvince", "广东省")); // 报装地址省份，必填
        signMap.put("addressProvince", "广东省");
        qParams.add(new BasicNameValuePair("addressCity", "广州市")); // 报装地址城市，必填
        signMap.put("addressCity", "广州市");

        qParams.add(new BasicNameValuePair("deliveryProvince", "广东省")); // 配送地址-省，必填
        signMap.put("deliveryProvince", "广东省");

        qParams.add(new BasicNameValuePair("deliveryCity", "广州市")); // 配送地址-市，必填
        signMap.put("deliveryCity", "广州市");

        String addressDistrict = null;
        String address = null;
        String addressID = null;
        String landId = null;
        String universityTerminalType = null;
        String universityUserCategory = null;
        String universityUserType = null;
        String universityMonthlyRentType = null;
        String universityChargingAttribute = null;
        String universityOnlineNumber = null;
        String universityOneManTerminal = null;
        String universityIsFtthHub = null;
        String universityExteriorLines = null;
        String universityChargeMode = null;
        if (BeanUtil.isNotBlank(schoolMap)) {
            addressDistrict = (String) schoolMap.get("universityRegion");
            address = (String) schoolMap.get("universityInstalledAddress");
            addressID = (String) schoolMap.get("universityInstalledAddressId");
            landId = (String) schoolMap.get("universityPackageNumber");
            universityTerminalType = (String) schoolMap.get("universityTerminalType");
            universityUserCategory = (String) schoolMap.get("universityUserCategory");
            universityUserType = (String) schoolMap.get("universityUserType");
            universityMonthlyRentType = (String) schoolMap.get("universityMonthlyRentType");
            universityChargingAttribute = (String) schoolMap.get("universityChargingAttribute");
            universityOnlineNumber = (String) schoolMap.get("universityOnlineNumber");
            universityOneManTerminal = (String) schoolMap.get("universityOneManTerminal");
            universityIsFtthHub = (String) schoolMap.get("universityIsFtthHub");
            universityExteriorLines = (String) schoolMap.get("universityExteriorLines");
            universityChargeMode = (String) schoolMap.get("universityChargeMode");
        } else {
            addressDistrict = "测试区";
            address = "广东省广州市测试区测试街道1号";
            addressID = "00000";
            landId = "20180621";
            universityTerminalType = "测试";
            universityUserCategory = "测试";
            universityUserType = "测试";
            universityMonthlyRentType = "测试";
            universityChargingAttribute = "测试";
            universityOnlineNumber = "0";
            universityOneManTerminal = "否";
            universityIsFtthHub = "否";
            universityExteriorLines = "测试";
            universityChargeMode = "测试";
        }
        qParams.add(new BasicNameValuePair("addressDistrict", addressDistrict)); // 报装地址区域，必填
        signMap.put("addressDistrict", addressDistrict);
        qParams.add(new BasicNameValuePair("address", address)); // 报装详细地址，必填
        signMap.put("address", address);

        qParams.add(new BasicNameValuePair("deliveryDistrict", addressDistrict)); // 配送地址-区，必填
        signMap.put("deliveryDistrict", addressDistrict);
        qParams.add(new BasicNameValuePair("deliveryAddress", address)); // 配送地址-详细地址，必填
        signMap.put("deliveryAddress", address);

        qParams.add(
                new BasicNameValuePair("deliveryContact", (String) orderMap.get("orderName"))); // 报装联系人，必填
        signMap.put("deliveryContact", (String) orderMap.get("orderName"));
        qParams.add(
                new BasicNameValuePair(
                        "deliveryContactPhone", (String) orderMap.get("orderPhone"))); // 报装联系电话，必填
        signMap.put("deliveryContactPhone", (String) orderMap.get("orderPhone"));

        qParams.add(new BasicNameValuePair("invoiced", "0")); // 是否需要发票 0：否 1：是，必填
        signMap.put("invoiced", "0");
        qParams.add(new BasicNameValuePair("invoiceTitle", "")); // 若需要发票，发票抬头，必填
        signMap.put("invoiceTitle", "");
        qParams.add(new BasicNameValuePair("invoiceDeliveryAddress", "")); // 若需要发票，发票电子邮箱，必填
        signMap.put("invoiceDeliveryAddress", "");
        qParams.add(new BasicNameValuePair("landId", landId)); // 揽装工号，必填
        signMap.put("landId", landId);
        qParams.add(new BasicNameValuePair("groupLanId", "")); // 集团揽装工号，选填
        signMap.put("groupLanId", "");
        qParams.add(new BasicNameValuePair("comarketingLanId", "")); // 协销工号，选填
        signMap.put("comarketingLanId", "");
        qParams.add(new BasicNameValuePair("groupComarketingLanId", "")); // 集团协销工号，选填
        signMap.put("groupComarketingLanId", "");
        qParams.add(
                new BasicNameValuePair(
                        "orderOutNum",
                        (String)
                                orderMap.get(
                                        "orderSeq"))); // 外部订单编号，选填!；通过API接口下单，必须传入一个外部接入商的订单编号,该编号与智能营销系统编号一一对应
        signMap.put("orderOutNum", (String) orderMap.get("orderSeq"));
        qParams.add(new BasicNameValuePair("orderSource", "校园宽带自助受理")); // 订单来源 ，选填
        signMap.put("orderSource", "校园宽带自助受理");
        qParams.add(
                new BasicNameValuePair(
                        "orderSourceNum",
                        (String) orderMap.get("orderSeq"))); // 订单来源单号，选填； 与订单来源对应，用于业务上记录订单的来源订单编号
        signMap.put("orderSourceNum", (String) orderMap.get("orderSeq"));
        qParams.add(new BasicNameValuePair("salePointCode", "")); // 销售点编码，选填
        signMap.put("salePointCode", "");
        qParams.add(new BasicNameValuePair("personCode", "")); // 人员编码，选填
        signMap.put("personCode", "");
        qParams.add(new BasicNameValuePair("distributorSmsReceive", "")); // 分销商短信接收号码，选填
        signMap.put("distributorSmsReceive", "");
        qParams.add(new BasicNameValuePair("agent", "")); // 代理商推荐人，选填
        signMap.put("agent", "");
        qParams.add(new BasicNameValuePair("copyied", "0")); // 是否收取复印件(0:否 1:是),必填
        signMap.put("copyied", "0");
        qParams.add(
                new BasicNameValuePair(
                        "deliveryContactPhone", (String) orderMap.get("orderPhone"))); // 联系人电话 ，必填
        signMap.put("deliveryContactPhone", (String) orderMap.get("orderPhone"));
        qParams.add(new BasicNameValuePair("deliveryContactPhone2", "")); // 联系人电话2，选填
        signMap.put("deliveryContactPhone2", "");

        qParams.add(new BasicNameValuePair("addressId", addressID)); // 地址Id，客户类型为2时，必填
        signMap.put("addressId", addressID);

        List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>(); // 下单产品列表
        List<Map<String, String>> paymentList = new ArrayList<Map<String, String>>(); // 收费项列表
        List<Map<String, String>> propertyList = new ArrayList<Map<String, String>>(); // 产品自定义属性列表
        // 下单产品
        Map<String, Object> productMap = new HashMap<String, Object>();
        // 收费项；智能平台3.0产品设计中收费项可由用户自主选择（至少选择一个），可根据需要创建paymentMap对象；注意：每个收费项可独立选择缴费方式
        Map<String, String> paymentMap = new HashMap<String, String>();
        paymentMap.put("id", saleId); // 收费项ID，必填；请通过销售品列表接口获取
        paymentMap.put("payAmount", ORDERAMOUNT); // 缴费金额（打款金额），缴费方式为“代理商打款”或“穗易付”时必填
        if (ORDERAMOUNT.equals("0.01") || ORDERAMOUNT.equals("0.02")) {
            paymentMap.put("payType", "2");
        } else {
            paymentMap.put(
                    "payType", "4"); // 缴费方式，必填（例：payType：1）；1：银行划账2：现金支付3：代理商打款4：穗易付5：原套餐缴费方式6：支付宝划扣8：装维上门收取
        }

        if("xjzf".equals(orderMap.get("customerId"))) {
            paymentMap.put("payType", "2");
        }

        paymentMap.put("tag", ""); // 费用项标识，选填
        paymentMap.put(
                "bank",
                ""); // 缴费银行，缴费方式为“银行划账”时必填
        // ：[中国银行|中国工商银行|中国农业银行|民生银行|招商银行|中信银行|商业银行|广东发展银行|光大银行|华夏银行|兴业银行|浦发银行|广州农村商业银行|广州银行|深圳发展银行|交通银行|中国建设银行|邮政储蓄]
        paymentMap.put("bankNumber", ""); // 银行账号，缴费方式为“银行划账”时必填
        paymentMap.put("bankOwner", ""); // //银行账号持有人，缴费方式为“银行划账”时必填
        String payPlatform = (String) orderMap.get("ipay");
        if (StringUtils.isNotBlank(payPlatform)) {
            if ("1".equals(payPlatform)) {
                paymentMap.put("payPlatform", "支付宝"); // 支付平台，缴费方式为“穗易付”时必填
            } else {
                paymentMap.put("payPlatform", "微信"); // 支付平台，缴费方式为“穗易付”时必填
            }
        } else {
            paymentMap.put("payPlatform", "穗易付"); // 支付平台，缴费方式为“穗易付”时必填
        }

        paymentMap.put("electronicPayNumber", UPTRANSEQ); // 支付流水号，缴费方式为“穗易付”时必填
        paymentMap.put("payOrderNumber", ORDERREQTRANSEQ); // 穗易付订单号，若选择穗易付，此项必填
        paymentMap.put("alipayUserid", ""); // 用户ID，缴费方式为“支付宝支付”时必填
        paymentMap.put("alipayNumber", ""); // 支付宝账号，缴费方式为“支付宝支付”时必填
        paymentMap.put("alipayAuthNumber", ""); // 授权协议号，缴费方式为“支付宝支付”时必填

        paymentList.add(paymentMap);

        // 产品自定义属性；暂时默认属性名称只能传“日租卡号码”
        Map<String, String> propertyMap = new HashMap<String, String>();
        propertyMap.put("name", "宽带速率");
        String setMeal = (String) orderMap.get("orderSetMeal");
        if (StringUtils.isNotBlank(setMeal)) {
            setMeal = setMeal.replace("包月", "");
            setMeal = setMeal.replace("包年", "");
        }

        //contains --> equals 原contains识别12M 误入2M
        if (setMeal.equals("20M")) {
            setMeal = "20M下行速率/4M上行速率";
        } else if (setMeal.equals("2M")) {
            setMeal = "2M下行速率/512K上行速率";
        } else if (setMeal.equals("50M")) {
            setMeal = "50M下行速率/10M上行速率";
        }
        propertyMap.put("value", setMeal);
        Map<String, String> propertyMap1 = new HashMap<String, String>();
        propertyMap1.put("name", "学校名称");
        propertyMap1.put("value", (String) orderMap.get("orderUniversityName"));
        Map<String, String> propertyMap2 = new HashMap<String, String>();
        propertyMap2.put("name", "允许上网终端类型");
        propertyMap2.put("value", universityTerminalType);
        Map<String, String> propertyMap3 = new HashMap<String, String>();
        propertyMap3.put("name", "用户类别");
        propertyMap3.put("value", universityUserCategory);
        Map<String, String> propertyMap4 = new HashMap<String, String>();
        propertyMap4.put("name", "用户类型");
        propertyMap4.put("value", universityUserType);
        Map<String, String> propertyMap5 = new HashMap<String, String>();

        propertyMap5.put("name", "月租类型");
        propertyMap5.put("value", universityMonthlyRentType);

        Map<String, String> propertyMap6 = new HashMap<String, String>();
        propertyMap6.put("name", "计费属性");
        propertyMap6.put("value", universityChargingAttribute);
        Map<String, String> propertyMap7 = new HashMap<String, String>();
        propertyMap7.put("name", "一人一号多终端");
        propertyMap7.put("value", universityOneManTerminal);
        Map<String, String> propertyMap8 = new HashMap<String, String>();
        propertyMap8.put("name", "外线方式");
        propertyMap8.put("value", universityExteriorLines);
        Map<String, String> propertyMap9 = new HashMap<String, String>();
        propertyMap9.put("name", "是否FTTH+HUB");
        propertyMap9.put("value", universityIsFtthHub);
        Map<String, String> propertyMap10 = new HashMap<String, String>();
        propertyMap10.put("name", "多媒体账号");
        propertyMap10.put("value", (String) orderMap.get("orderCustomerAccount"));
        Map<String, String> propertyMap11 = new HashMap<String, String>();
        propertyMap11.put("name", "多媒体账号密码");
        propertyMap11.put("value", (String) orderMap.get("orderCustomerPwd"));
        Map<String, String> propertyMap12 = new HashMap<String, String>();
        propertyMap12.put("name", "学生证号");
        propertyMap12.put("value", (String) orderMap.get("orderCustomerStudentId"));
        Map<String, String> propertyMap13 = new HashMap<String, String>();
        propertyMap13.put("name", "宽带首月费用类型");
        propertyMap13.put("value", universityChargeMode);
        Map<String, String> propertyMap14 = new HashMap<String, String>();
        propertyMap14.put("name", "最大在线数");
        propertyMap14.put("value", universityOnlineNumber);
        Map<String, String> propertyMap15 = new HashMap<String, String>();
        propertyMap15.put("name", "地址ID");
        propertyMap15.put("value", addressID);

        propertyList.add(propertyMap15);
        propertyList.add(propertyMap2);
        propertyList.add(propertyMap1);
        propertyList.add(propertyMap3);
        propertyList.add(propertyMap12);
        propertyList.add(propertyMap);
        propertyList.add(propertyMap4);
        propertyList.add(propertyMap5);
        propertyList.add(propertyMap6);
        propertyList.add(propertyMap10);
        propertyList.add(propertyMap11);
        propertyList.add(propertyMap14);
        propertyList.add(propertyMap7);
        propertyList.add(propertyMap9);
        propertyList.add(propertyMap8);
        propertyList.add(propertyMap13);

        productMap.put("productId", productId); // 产品ID，请通过产品列表接口获取
        productMap.put("payment", paymentList); // 收费项列表
        productMap.put("addProperties", propertyList); // 产品自定义属性列表
        productList.add(productMap);
        // 将对象装换为json字符串
        String productJson = JSONArray.toJSONString(productList);
        qParams.add(
                new BasicNameValuePair("productJson", URLEncoder.encode(productJson, "UTF-8"))); // 产品信息，必填
        signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));

        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(Constant.ZHANGSHIKEY);
        log.info("---------plaintext---------:" + plaintext);
        qParams.add(
                new BasicNameValuePair(
                        "sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)))); // 签名，必填
        log.info(
                "---------sign---------:" + SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)));
        JSONObject resultDataJson = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
            Constant.trustEveryone();
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            log.info("单宽带下单接口，返回信息:" + httpResult);
            resultDataJson = JSONObject.parseObject(httpResult);
        } catch (SSLHandshakeException s) {
            count++;
            if (count < 20) {
                resultDataJson =
                        getOrderInfo(
                                schoolMap,
                                orderMap,
                                currentTimeStr,
                                productId,
                                saleId,
                                ORDERSEQ,
                                UPTRANSEQ,
                                ORDERAMOUNT,
                                ORDERREQTRANSEQ,
                                count);
            } else {
                log.error("查询单宽带(预付费、移动、融合、续约、增值)产品接口异常尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.info("单宽带下单接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }

    private JSONObject getProductId(String currentTimeStr, int count) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>(); // 待签名参数
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig =
                RequestConfig.custom()
                        .setSocketTimeout(50000)
                        .setConnectTimeout(50000)
                        .setConnectionRequestTimeout(50000)
//                        .setProxy(proxy)
                        .build();
        CloseableHttpClient httpclient =
                HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "query.action");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);
        qParams.add(new BasicNameValuePair("service", "product.broadband.query")); // api标识，必填
        signMap.put("service", "product.broadband.query");
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON)); // 用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        qParams.add(new BasicNameValuePair("timeStamp", currentTimeStr)); // 时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", currentTimeStr);
        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(Constant.ZHANGSHIKEY);
        qParams.add(
                new BasicNameValuePair(
                        "sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)))); // 签名，必填
        JSONObject resultDataJson = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
            Constant.trustEveryone();
            Constant.trustEveryone();
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            resultDataJson = JSONObject.parseObject(httpResult);
        } catch (SSLHandshakeException s) {
            count++;
            if (count < 20) {
                resultDataJson = getProductId(currentTimeStr, count);
            } else {
                log.error("查询单宽带(预付费、移动、融合、续约、增值)产品接口异常尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.info("查询单宽带(预付费、移动、融合、续约、增值)产品接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }

    private String QueOrderNum(String orderNum) {
        if (orderNum.equals("12")) {
            return "1"; // 待提交
        } else if (orderNum.equals("11")) {
            return "4"; // 归档
        } else if (orderNum.equals("13") || orderNum.equals("18")) {
            return "5"; // 作废(作废、分销商作废)
        } else if (orderNum.equals("9")) {
            return "3"; // 	受理成功【待收费】
        } else if (orderNum.equals("10")) {
            return "9"; // 已收费【待竣工】
        } else if (orderNum.equals("14")) {
            return "10"; // 	受理异常
        } else {
            return "2"; // 待受理(未受理、未受理【待跟进】、待疑难支撑审核、待分局审核、待分销商审核)
        }
    }

    private JSONObject getSaleId(String productId, String currentTimeStr, int count)
            throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>(); // 待签名参数
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig =
                RequestConfig.custom()
                        .setSocketTimeout(500000)
                        .setConnectTimeout(500000)
                        .setConnectionRequestTimeout(500000)
//                        .setProxy(proxy)
                        .build();
        CloseableHttpClient httpclient =
                HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "query.action");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);
        qParams.add(new BasicNameValuePair("service", "sale.query")); // api标识，必填
        signMap.put("service", "sale.query");
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON)); // 用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        qParams.add(new BasicNameValuePair("timeStamp", currentTimeStr));
        signMap.put("timeStamp", currentTimeStr);
        if (StringUtils.isNotBlank(productId)) {
            qParams.add(new BasicNameValuePair("productId", productId)); // 产品ID
            signMap.put("productId", productId);
        }
        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(Constant.ZHANGSHIKEY);
        qParams.add(
                new BasicNameValuePair(
                        "sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)))); // 签名，必填
        JSONObject resultDataJson = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
            Constant.trustEveryone();
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            log.info("返回信息:" + httpResult);
            resultDataJson = JSONObject.parseObject(httpResult);
        } catch (SSLHandshakeException s) {
            count++;
            if (count < 20) {
                resultDataJson = getSaleId(productId, currentTimeStr, count);
            } else {
                log.error("查询单宽带(预付费、移动、融合、续约、增值)产品接口异常尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.info("---接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }

    /**
     * 融合下单公共方法
     * @param order hhr_order 表的map数据
     * @param rightNowSend 是否马上下单，是则无视融合时间，不是则判断融合时间是否当天
     */
    public void integrateSendOrder(Order order, boolean rightNowSend) throws Exception {

        if (order == null) {
            log.info("融合下单数据为空！");
            return;
        }

        if (!rightNowSend) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date rhTime = null;
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date today = calendar.getTime();
            calendar.add(Calendar.DATE, 1);
            if (order.getRhTime() == null) {
                log.info("当前订单无融合时间，无法进行下单：" + JSONObject.toJSONString(order));
                return;
            }
            try {
                rhTime = order.getRhTime();
            }catch(Exception e) {
                log.error("融合日期转换错误" + JSONObject.toJSONString(order));
                return;
            }
            // 融合时间小于当前时间
            if(today.getTime() > rhTime.getTime()) {
                log.info("融合日期小于当前日期，改为待受理状态" + JSONObject.toJSONString(order));
                Wrapper<Order> wrapper = new EntityWrapper<>();
                wrapper.eq("id", order.getId());
                Order updateOrder = new Order();
                updateOrder.setUpdateTime(new Date());
                updateOrder.setOrderStatus("待受理");
                orderMapper.update(updateOrder, wrapper);
                return;
            }
            // 融合时间大于等于 当前时间的第二天的0点
            if (rhTime.getTime() >= calendar.getTime().getTime()) {
                log.info("融合日期超过当前时间，不下单：" + JSONObject.toJSONString(order));
                return;
            }
        }

        Map<String, Object> orderMap = null;
        Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
        orderViewWrapper.eq("orderSeq", order.getKdOrderId());
        List<Map<String, Object>> orderViewMaps = orderViewMapper.selectMaps(orderViewWrapper);
        if (orderViewMaps != null && orderViewMaps.size() > 0) {
            orderMap = orderViewMaps.get(0);
        }
        // 根据学校名称，获取该学校信息
        Map<String, Object> schoolMap = new HashMap<>();
        List<Map<String, Object>> list1 = new ArrayList<>();

        List<Map<String, Object>> hehuoren_id =
                universityInfoMapper.selectProductManager(order.getHehuorenId());
        if (hehuoren_id.size() > 0 && hehuoren_id.get(0).get("university_id") != null) {
            Wrapper<UniversityInfo> universityInfoWrapper = new EntityWrapper<>();
            universityInfoWrapper.eq("university_id", hehuoren_id.get(0).get("university_id").toString());
            List<Map<String, Object>> findUniversityById = universityInfoMapper.selectMaps(universityInfoWrapper);
            schoolMap = findUniversityById.get(0);
        } else {
            Wrapper<UniversityInfo> universityInfoWrapper = new EntityWrapper<>();
            universityInfoWrapper.eq("university_name", orderMap.get("orderUniversityName"));
            universityInfoWrapper.eq("university_region", orderMap.get("orderRegion"));
            list1 = universityInfoMapper.selectMaps(universityInfoWrapper);

            schoolMap = list1.get(0);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTimeStr = simpleDateFormat.format(new Date());
        if (order.getUserType().toString().equals("3")) {
            String UPTRANSEQ = "";
            if (orderMap.get("uptranseq") != null) {
                UPTRANSEQ = orderMap.get("uptranseq").toString();
            }
            // 穗易付平台，支付流水号
            String ORDERAMOUNT = "";
            if (orderMap.get("webOrderAmount").toString().equals("0")) {
                ORDERAMOUNT = "0元";
            } else {
                ORDERAMOUNT = orderMap.get("webOrderAmount").toString();
            }

            setPriceIndex(schoolMap, orderMap, ORDERAMOUNT);

            String ORDERREQTRANSEQ = "";
            if (orderMap.get("orderReqtranSeq") != null) {
                ORDERREQTRANSEQ = orderMap.get("orderReqtranSeq").toString(); // 穗易付订单号
            }
            String productId = "1329";
            String saleId1 = "4907";
            // 提速包
            String saleId2 = null;

            if (!orderMap.get("webOrderAmount").toString().equals("0")) {

                JSONObject saleJsonObject = getSaleId(productId, currentTimeStr, 0);
                if (saleJsonObject.toString().indexOf("list") == -1) {
                    return;
                }
                String prices = orderMap.get("webOrderAmount").toString();
                if (prices.equals("0.01")) {
                    prices = "30";
                } else if (prices.equals("0.02")) {
                    prices = "300";
                }

                prices = prices.replace(".00", "").replace("元", "") + ".000";

                String expenses = "";
                if (schoolMap.get("identifying") != null) {
                    expenses = schoolMap.get("identifying").toString();
                }
                log.info("----expenses---prices---：" + expenses + "------" + prices);
                JSONArray saleList = saleJsonObject.getJSONArray("list");
                log.info("----saleList---：" + saleList);
                for (int i = 0; i < saleList.size(); i++) {
                    net.sf.json.JSONObject itmeJson =
                            net.sf.json.JSONObject.fromObject(saleList.get(i));
                    // 判断获取的全部产品与订单产品符合的拿取对应的ID
                    if (itmeJson.getString("propertyName").indexOf("单宽带") != -1) {
                        if (itmeJson.getString("price").equals(prices)) {
                            // 获取对应产品ID
                            saleId1 = itmeJson.getString("saleId");
                        }
                    } else if (itmeJson.getString("propertyName").indexOf("提速包") != -1) {
                        if (itmeJson.getString("name").equals(expenses)) {
                            // 获取对应产品ID
                            saleId2 = itmeJson.getString("saleId");
                        }
                    } else if (itmeJson.getString("propertyName").indexOf("增值业务") != -1) {
                        if (itmeJson.getString("name").equals(expenses)) {
                            // 获取对应产品ID
                            saleId2 = itmeJson.getString("saleId");
                        }
                    }
                }
            } else {
                JSONObject saleJsonObject =
                        getSaleId(productId, currentTimeStr, 0); // 获取销售ID
                log.info("----------调用智能平台的获取销售品接口返回值：" + saleJsonObject);
                System.out.println("----111--" + (saleJsonObject.toString().indexOf("list") == -1));
                if (saleJsonObject.toString().indexOf("list") == -1) {
                    return;
                }
                String expenses = "";
                if (schoolMap.get("identifying") != null) {
                    expenses = schoolMap.get("identifying").toString();
                }

                JSONArray saleList = saleJsonObject.getJSONArray("list");
                System.out.println("----saleList---：" + saleList);
                for (int i = 0; i < saleList.size(); i++) {
                    net.sf.json.JSONObject itmeJson =
                            net.sf.json.JSONObject.fromObject(saleList.get(i));
                    // 判断获取的全部产品与订单产品符合的拿取对应的ID
                    if (itmeJson.getString("propertyName").indexOf("提速包") != -1) {
                        if (itmeJson.getString("name").equals(expenses)) {
                            // 获取对应产品ID
                            saleId2 = itmeJson.getString("saleId");
                        }
                    } else if (itmeJson.getString("propertyName").indexOf("增值业务") != -1) {
                        if (itmeJson.getString("name").equals(expenses)) {
                            // 获取对应产品ID
                            saleId2 = itmeJson.getString("saleId");
                        }
                    }
                }
            }
            List<NameValuePair> qParams = new ArrayList<NameValuePair>();
//            HttpHost proxy = new HttpHost("172.18.101.170", 3128);
            RequestConfig defaultRequestConfig =
                    RequestConfig.custom()
                            .setSocketTimeout(500000)
                            .setConnectTimeout(500000)
                            .setConnectionRequestTimeout(500000)
//                            .setProxy(proxy)
                            .build();
            CloseableHttpClient httpclient =
                    HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            HttpEntity entity = null;
            HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "create-order.action");
            RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
            httpPost.setConfig(requestConfig);
            Map<String, String> signMap = new HashMap<String, String>();

            qParams.add(new BasicNameValuePair("service", "order.combined.create")); // api标识，必填且唯一
            signMap.put("service", "order.combined.create");

            qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON)); // 用户名，必填
            signMap.put("userName", Constant.ZHENGSHIAUCCON);

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

            qParams.add(new BasicNameValuePair("productCategory", "融合产品")); // 业务类型，必填且唯一
            signMap.put("productCategory", "融合产品");

            qParams.add(
                    new BasicNameValuePair("transactType", "新宽旧移")); // 办理类型，必填[新宽新移][新宽旧移][旧宽新移][旧宽旧移]
            signMap.put("transactType", "新宽旧移");

            if (orderMap.get("webOrderAmount").toString().equals("0")) {
                qParams.add(
                        new BasicNameValuePair(
                                "ctNumber",
                                order.getBusinessNumber())); // 电信号码，办理类型，若选择[新宽旧移]或[旧宽旧移]，此项必填
                signMap.put("ctNumber", order.getBusinessNumber());

            } else {
                qParams.add(
                        new BasicNameValuePair(
                                "ctNumber",
                                (String)
                                        orderMap.get(
                                                "orderCustomerRemarks"))); // 电信号码，办理类型，若选择[新宽旧移]或[旧宽旧移]，此项必填
                signMap.put("ctNumber", (String) orderMap.get("orderCustomerRemarks"));
            }
            qParams.add(
                    new BasicNameValuePair(
                            "addressProvince", "广东省")); // 报装地址-省  办理类型，若选择[新宽新移][新宽旧移]，此项必填
            signMap.put("addressProvince", "广东省");

            qParams.add(
                    new BasicNameValuePair("addressCity", "广州市")); // 报装地址-市  办理类型，若选择[新宽新移][新宽旧移]，此项必填
            signMap.put("addressCity", "广州市");

            String addressDistrict = null;
            String address = null;
            String addressID = null;
            String landId = null;
            String universityTerminalType = null;
            String universityUserCategory = null;
            String universityUserType = null;
            String universityMonthlyRentType = null;
            String universityChargingAttribute = null;
            String universityOnlineNumber = null;
            String universityOneManTerminal = null;
            String universityIsFtthHub = null;
            String universityExteriorLines = null;
            String universityChargeMode = null;
            if (BeanUtil.isNotBlank(schoolMap)) {
                addressDistrict = (String) schoolMap.get("universityRegion");
                address = (String) schoolMap.get("universityInstalledAddress");
                addressID = (String) schoolMap.get("universityInstalledAddressId");
                landId = (String) schoolMap.get("universityPackageNumber");
                universityTerminalType = (String) schoolMap.get("universityTerminalType");
                universityUserCategory = (String) schoolMap.get("universityUserCategory");
                universityUserType = (String) schoolMap.get("universityUserType");
                universityMonthlyRentType = (String) schoolMap.get("universityMonthlyRentType");
                universityChargingAttribute = (String) schoolMap.get("universityChargingAttribute");
                universityOnlineNumber = (String) schoolMap.get("universityOnlineNumber");
                universityOneManTerminal = (String) schoolMap.get("universityOneManTerminal");
                universityIsFtthHub = (String) schoolMap.get("universityIsFtthHub");
                universityExteriorLines = (String) schoolMap.get("universityExteriorLines");
                universityChargeMode = (String) schoolMap.get("universityChargeMode");
            } else {
                addressDistrict = "测试区";
                address = "广东省广州市测试区测试街道1号";
                addressID = "00000";
                landId = "20180621";
                universityTerminalType = "测试";
                universityUserCategory = "测试";
                universityUserType = "测试";
                universityMonthlyRentType = "测试";
                universityChargingAttribute = "测试";
                universityOnlineNumber = "0";
                universityOneManTerminal = "否";
                universityIsFtthHub = "否";
                universityExteriorLines = "测试";
                universityChargeMode = "测试";
            }

            qParams.add(
                    new BasicNameValuePair(
                            "addressDistrict", addressDistrict)); // 报装地址-区  办理类型，若选择[新宽新移][新宽旧移]，此项必填
            signMap.put("addressDistrict", addressDistrict);

            qParams.add(
                    new BasicNameValuePair("address", address)); // 报装地址-详细地址  办理类型，若选择[新宽新移][新宽旧移]，此项必填
            signMap.put("address", address);

            qParams.add(new BasicNameValuePair("addressId", addressID)); // 报装地址-地址ID，选填
            signMap.put("addressId", addressID);

            qParams.add(new BasicNameValuePair("govEntCustomer", "0")); // 是否政企客户下单 0：否 1：是，必填
            signMap.put("govEntCustomer", "0");

            qParams.add(new BasicNameValuePair("agentName", "")); // 若是政企客户下单，代办人姓名，必填
            signMap.put("agentName", "");

            qParams.add(new BasicNameValuePair("agentCardNum", "")); // 若是政企客户下单，代办人身份证号码，必填
            signMap.put("agentCardNum", "");

            qParams.add(
                    new BasicNameValuePair(
                            "customerName", (String) orderMap.get("orderName"))); // 客户姓名，必填
            signMap.put("customerName", (String) orderMap.get("orderName"));

            qParams.add(
                    new BasicNameValuePair(
                            "customerPhone", (String) orderMap.get("orderPhone"))); // 客户电话|代办人电话，必填
            signMap.put("customerPhone", (String) orderMap.get("orderPhone"));

            qParams.add(new BasicNameValuePair("customerCardType", "身份证")); // 证件类型，必填且只能为身份证
            signMap.put("customerCardType", "身份证");

            qParams.add(
                    new BasicNameValuePair(
                            "customerCardNum", (String) orderMap.get("orderNumber"))); // 证件号码，必填
            signMap.put("customerCardNum", (String) orderMap.get("orderNumber"));

            qParams.add(new BasicNameValuePair("landId", landId)); // 揽装工号，必填
            signMap.put("landId", landId);

            qParams.add(new BasicNameValuePair("comarketingLanId", "")); // 协销工号，选填
            signMap.put("comarketingLanId", "");

            qParams.add(new BasicNameValuePair("groupComarketingLanId", "")); // 集团协销工号，选填
            signMap.put("groupComarketingLanId", "");

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

            qParams.add(new BasicNameValuePair("orderSource", "校园宽带自助受理")); // 订单来源 ，选填
            signMap.put("orderSource", "校园宽带自助受理");

            qParams.add(
                    new BasicNameValuePair(
                            "orderSourceNum",
                            (String) orderMap.get("orderSeq"))); // 订单来源单号，选填；与订单来源对应，用于业务上记录订单的来源订单编号
            signMap.put("orderSourceNum", (String) orderMap.get("orderSeq"));

            qParams.add(new BasicNameValuePair("salePointCode", "")); // 销售点编码，选填
            signMap.put("salePointCode", "");

            qParams.add(new BasicNameValuePair("personCode", "")); // 人员编码，必填
            signMap.put("personCode", "");

            qParams.add(new BasicNameValuePair("deliveryProvince", "广东省")); // 配送地址-省，必填
            signMap.put("deliveryProvince", "广东省");

            qParams.add(new BasicNameValuePair("deliveryCity", "广州市")); // 配送地址-市，必填
            signMap.put("deliveryCity", "广州市");

            qParams.add(new BasicNameValuePair("deliveryDistrict", addressDistrict)); // 配送地址-区，必填
            signMap.put("deliveryDistrict", addressDistrict);

            qParams.add(new BasicNameValuePair("deliveryAddress", address)); // 配送地址-详细地址，必填
            signMap.put("deliveryAddress", address);

            qParams.add(
                    new BasicNameValuePair(
                            "deliveryContact", (String) orderMap.get("orderName"))); // 联系人，必填
            signMap.put("deliveryContact", (String) orderMap.get("orderName"));

            qParams.add(
                    new BasicNameValuePair(
                            "deliveryContactPhone", (String) orderMap.get("orderPhone"))); // 联系电话，必填
            signMap.put("deliveryContactPhone", (String) orderMap.get("orderPhone"));

            qParams.add(new BasicNameValuePair("deliveryContactPhone2", "")); // 联系电话2，选填
            signMap.put("deliveryContactPhone2", "");

            qParams.add(new BasicNameValuePair("invoiced", "0")); // 是否需要发票，必填
            // 0:不需要；1:一次性发票；2:分月发票
            signMap.put("invoiced", "0");

            qParams.add(new BasicNameValuePair("invoiceTitle", "")); // 发票抬头，若需要发票必填
            signMap.put("invoiceTitle", "");

            qParams.add(new BasicNameValuePair("invoiceDeliveryAddress", "")); // 电子邮箱，若需要发票必填
            signMap.put("invoiceDeliveryAddress", "");

            qParams.add(
                    new BasicNameValuePair("deliveryType", "不需配送")); // 发货类型，必填，填写[同德仓发货][不需配送][代理商自行发货]
            signMap.put("deliveryType", "不需配送");

            qParams.add(
                    new BasicNameValuePair(
                            "deliveryCompany", "")); // 配送公司，选填，同德仓发货必填；填写只能填顺丰速运或者如风达或者京东快递或者EMS
            signMap.put("deliveryCompany", "");

            qParams.add(new BasicNameValuePair("gift", "")); // 礼品，选填，请通过礼品列表接口获取
            signMap.put("gift", "");

            qParams.add(new BasicNameValuePair("giftNum", "")); // 礼品数量，选填，若礼品填写则必填且为正整数
            signMap.put("giftNum", "");

            qParams.add(new BasicNameValuePair("acceptPriority", "7")); // 受理优先级  为0-10范围内的整数! 选填
            signMap.put("acceptPriority", "7");

            List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>(); // 产品信息
            List<Map<String, Object>> inPropertyList = new ArrayList<Map<String, Object>>(); // 产品属性
            List<Map<String, Object>> paymentList =
                    new ArrayList<Map<String, Object>>(); // 销售品信息(费用项)
            List<Map<String, Object>> addPropertyList =
                    new ArrayList<Map<String, Object>>(); // 自定义产品属性
            // 下单产品
            Map<String, Object> productMap = new HashMap<String, Object>();
            // 产品(一个订单只能有一种产品且数量为1)
            productMap.put("productId", productId); // 产品id,必填，请通过产品列表接口获取

            // 产品都必须传一个产品对应的唯一的收费项
            Map<String, Object> paymentListMap = new HashMap<String, Object>();
            paymentListMap.put("id", "4455"); // 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
            paymentListMap.put("saleName", "校园融合套餐"); // 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
            paymentListMap.put("payType", "2"); // 缴费方式，
            // 必填（例：payType：3）1：银行划账2：现金支付3：代理商打款4：穗易付6：支付宝划扣7：货到付款8：装维上门收取9:第三方托收11：代理商代扣

            // 单宽带
            Map<String, Object> paymentListMap2 = new HashMap<String, Object>();
            paymentListMap2.put("id", saleId1); // 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
            paymentListMap2.put("saleName", ""); // 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
            paymentListMap2.put("payAmount", ORDERAMOUNT); // 打款金额（支付金额），若选择代理商打款、者穗易付、货到付款，此项必填

            if (orderMap.get("webOrderAmount").toString().equals("0")
                    || ORDERAMOUNT.equals("0.01")
                    || ORDERAMOUNT.equals("0.02")) {
                paymentListMap2.put("payType", "2");
            } else if (orderMap.get("customerId").toString().equals("xjzf")) {
                paymentListMap2.put("payType", "2");
            } else {
                paymentListMap2.put("payType", "4"); // 缴费方式，必填（例：payType：3）3：代理商打款4：穗易付7：货到付款
            }

            String payPlatform = (String) orderMap.get("ipay");
            if (StringUtils.isNotBlank(payPlatform)) {
                if ("1".equals(payPlatform)) {
                    paymentListMap2.put("payPlatform", "支付宝"); // 支付平台，缴费方式为“穗易付”时必填
                } else {
                    paymentListMap2.put("payPlatform", "微信"); // 支付平台，缴费方式为“穗易付”时必填
                }
            } else {
                paymentListMap2.put("payPlatform", "穗易付"); // 支付平台，缴费方式为“穗易付”时必填
            }
            paymentListMap2.put("electronicPayNumber", UPTRANSEQ); // 支付流水号，若选择穗易付，此项必填
            paymentListMap2.put("payOrderNumber", ORDERREQTRANSEQ); // 穗易付订单号，若选择穗易付，此项必填

            // 提速包
            Map<String, Object> paymentListMap3 = new HashMap<String, Object>();
            paymentListMap3.put("id", saleId2); // 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
            paymentListMap3.put("saleName", ""); // 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
            paymentListMap3.put("saleAmount", ""); // 售价，选填
            paymentListMap3.put("payType", "2"); // 缴费方式，必填（例：payType：3）3：代理商打款4：穗易付7：货到付款
            paymentListMap3.put("payAmount", "0"); // 打款金额（支付金额），若选择代理商打款、者穗易付、货到付款，此项必填

            paymentList.add(paymentListMap);
            paymentList.add(paymentListMap2);
            if(StringUtils.isNotBlank(saleId2)){
                paymentList.add(paymentListMap3);
            }
            productMap.put("payment", paymentList);

            // 产品属性 必填主卡号码属性,name=主卡号码,value=11位数字或者随机；
            Map<String, Object> inPropertyListMap = new HashMap<String, Object>();
            inPropertyListMap.put("name", "主卡号码");
            if (orderMap.get("webOrderAmount").toString().equals("0")) {
                inPropertyListMap.put("value", order.getBusinessNumber());
            } else {
                inPropertyListMap.put("value", orderMap.get("orderCustomerRemarks"));
            }
            inPropertyList.add(inPropertyListMap);

            productMap.put("inpProperties", inPropertyList);
            // 产品附加扩展属性 选填(若有购买终端，请填写在此:name:终端型号1；value：终端值)
            //		Map<String, Object> appendPropertyListMap1 = new HashMap<String, Object>();
            //		appendPropertyListMap1.put("name", "终端型号1");
            //		appendPropertyListMap1.put("value", "华为荣耀5A全网通白色");
            //		appendPropertyList.add(appendPropertyListMap1);
            //		Map<String, Object> appendPropertyListMap2 = new HashMap<String, Object>();
            //		appendPropertyListMap2.put("name", "终端型号2");
            //		appendPropertyListMap2.put("value", "华为P9全网通32G金色");
            //		appendPropertyList.add(appendPropertyListMap2);
            //		Map<String, Object> appendPropertyListMap3 = new HashMap<String, Object>();
            //		appendPropertyListMap3.put("name", "终端型号3");
            //		appendPropertyListMap3.put("value", "华为P9全网通32G金色");
            //		appendPropertyList.add(appendPropertyListMap3);
            //
            //		productMap.put("appendProperties", appendPropertyList);
            // 产品自定义属性；选填,没有则为null
            // 注：若填写请属性名和属性值都填写，若只填写其中一项则无效
            // 产品自定义属性；暂时默认属性名称只能传“日租卡号码”
            Map<String, Object> propertyMap = new HashMap<String, Object>();
            propertyMap.put("name", "宽带速率");
            String setMeal = (String) schoolMap.get("speed");
            if (StringUtils.isNotBlank(setMeal)) {
                setMeal = setMeal.replace("包月", "");
                setMeal = setMeal.replace("包年", "");
            }
            propertyMap.put("value", setMeal);
            Map<String, Object> propertyMap1 = new HashMap<String, Object>();
            propertyMap1.put("name", "学校名称");
            propertyMap1.put("value", (String) orderMap.get("orderUniversityName"));
            Map<String, Object> propertyMap2 = new HashMap<String, Object>();
            propertyMap2.put("name", "允许上网终端类型");
            propertyMap2.put("value", universityTerminalType);
            Map<String, Object> propertyMap3 = new HashMap<String, Object>();
            propertyMap3.put("name", "用户类别");
            propertyMap3.put("value", universityUserCategory);
            Map<String, Object> propertyMap4 = new HashMap<String, Object>();
            propertyMap4.put("name", "用户类型");
            propertyMap4.put("value", universityUserType);
            Map<String, Object> propertyMap5 = new HashMap<String, Object>();

            propertyMap5.put("name", "月租类型");
            propertyMap5.put("value", universityMonthlyRentType);

            Map<String, Object> propertyMap6 = new HashMap<String, Object>();
            propertyMap6.put("name", "计费属性");
            propertyMap6.put("value", universityChargingAttribute);
            Map<String, Object> propertyMap7 = new HashMap<String, Object>();
            propertyMap7.put("name", "一人一号多终端");
            propertyMap7.put("value", universityOneManTerminal);
            Map<String, Object> propertyMap8 = new HashMap<String, Object>();
            propertyMap8.put("name", "外线方式");
            propertyMap8.put("value", universityExteriorLines);
            Map<String, Object> propertyMap9 = new HashMap<String, Object>();
            propertyMap9.put("name", "是否FTTH+HUB");
            propertyMap9.put("value", universityIsFtthHub);

            Map<String, Object> propertyMap16 = new HashMap<String, Object>();
            propertyMap16.put("name", "宽带提速速率");
            propertyMap16.put("value", schoolMap.get("expenses"));

            Map<String, Object> propertyMap10 = new HashMap<String, Object>();
            propertyMap10.put("name", "多媒体账号");
            propertyMap10.put("value", (String) orderMap.get("orderCustomerAccount"));
            Map<String, Object> propertyMap11 = new HashMap<String, Object>();
            propertyMap11.put("name", "多媒体账号密码");
            propertyMap11.put("value", (String) orderMap.get("orderCustomerPwd"));
            Map<String, Object> propertyMap12 = new HashMap<String, Object>();
            propertyMap12.put("name", "学生证号");
            propertyMap12.put("value", (String) orderMap.get("orderCustomerStudentId"));
            Map<String, Object> propertyMap13 = new HashMap<String, Object>();
            propertyMap13.put("name", "宽带首月费用类型");
            propertyMap13.put("value", universityChargeMode);
            Map<String, Object> propertyMap14 = new HashMap<String, Object>();
            propertyMap14.put("name", "最大在线数");
            propertyMap14.put("value", universityOnlineNumber);
            Map<String, Object> propertyMap15 = new HashMap<String, Object>();
            propertyMap15.put("name", "地址ID");
            propertyMap15.put("value", addressID);
            Map<String, Object> propertyMap17 = new HashMap<String, Object>();
            propertyMap17.put("name", "关联移动号码");
            if (orderMap.get("webOrderAmount").toString().equals("0")) {
                propertyMap17.put("value", order.getBusinessNumber());
            } else {
                propertyMap17.put("value", orderMap.get("orderCustomerRemarks"));
            }

            addPropertyList.add(propertyMap15);
            addPropertyList.add(propertyMap2);
            addPropertyList.add(propertyMap1);
            addPropertyList.add(propertyMap3);
            addPropertyList.add(propertyMap12);
            addPropertyList.add(propertyMap);
            addPropertyList.add(propertyMap16);
            addPropertyList.add(propertyMap4);
            addPropertyList.add(propertyMap17);
            addPropertyList.add(propertyMap5);
            addPropertyList.add(propertyMap6);
            addPropertyList.add(propertyMap10);
            addPropertyList.add(propertyMap11);
            addPropertyList.add(propertyMap14);
            addPropertyList.add(propertyMap7);
            addPropertyList.add(propertyMap9);
            addPropertyList.add(propertyMap8);
            addPropertyList.add(propertyMap13);

            productMap.put("addProperties", addPropertyList);
            productList.add(productMap);
            // 将对象装换为json字符串
            String productJson = net.sf.json.JSONArray.fromObject(productList).toString();

            try {
                qParams.add(
                        new BasicNameValuePair(
                                "productJson", URLEncoder.encode(productJson, "UTF-8"))); // 产品信息，必填
                signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            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(Constant.ZHANGSHIKEY);
            log.info("---------plaintext---------:" + plaintext);
            qParams.add(
                    new BasicNameValuePair(
                            "sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)))); // 签名，必填
            log.info(
                    "---------sign---------:"
                            + SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)));
            net.sf.json.JSONObject resultDataJson = null;
            try {
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
                httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
                log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
                Constant.trustEveryone();
                HttpResponse response = httpclient.execute(httpPost);
                entity = response.getEntity();
                String httpResult = EntityUtils.toString(entity, "UTF-8");

                log.info("订单编号：" + order.getKdOrderId() +"；融合下单接口，返回信息:" + httpResult);
                resultDataJson = net.sf.json.JSONObject.fromObject(httpResult);
            } catch (SSLHandshakeException s) {
                HttpResponse response = httpclient.execute(httpPost);
                entity = response.getEntity();
                String httpResult = EntityUtils.toString(entity, "UTF-8");
                log.info("订单编号：" + order.getKdOrderId()+"；融合下单接口，返回信息:" + httpResult);
                resultDataJson = net.sf.json.JSONObject.fromObject(httpResult);
            } catch (Exception e) {
                System.out.println("融合下单接口接口异常");
                e.printStackTrace();
            } finally {
                httpPost.releaseConnection();
            }
            String orderNum = (String) resultDataJson.get("orderNumber");

            JSONObject queryOrderJsonObject = null;

            if (StringUtils.isNotBlank(orderNum)) {
                queryOrderJsonObject = getQueryOrderInfo(orderNum, currentTimeStr, 0);
                log.info("----------调用查询智能订单接口并返回参数信息:" + queryOrderJsonObject);
                /*	5、更新数据库   */
                String state = queryOrderJsonObject.getString("state");

                Wrapper<Order> orderWrapper = new EntityWrapper<>();
                orderWrapper.eq("kd_order_id", orderMap.get("orderSeq").toString());
                Order updateOrder = new Order();
                updateOrder.setOrderId(orderNum);
                updateOrder.setOrderStatus("审核中");
                orderMapper.update(updateOrder, orderWrapper);

                if (StringUtils.isNotBlank(state)) {
                    log.info("支付成功后更新订单状态");
                    OrderView updateOrderView = new OrderView();
                    updateOrderView.setStatus(QueOrderNum(state));
                    updateOrderView.setOrderseqThd(orderNum);
                    Wrapper<OrderView> wrapperOrderView = new EntityWrapper<>();
                    wrapperOrderView.eq("orderSeq", orderMap.get("orderSeq").toString());
                    orderViewMapper.update(updateOrderView, wrapperOrderView);
                } else {
                    log.info("----------将智能订单状态更新至数据库error：" + state);
                }
            } else {
                String msg = (String) resultDataJson.get("msg");
                if (StringUtils.isNotBlank(msg) && !msg.equals("订单来源单号已存在，请勿重复下单")) {
                    Wrapper<Order> wrapper = new EntityWrapper<>();
                    wrapper.eq("id", order.getId());
                    Order updateOrder = new Order();
                    updateOrder.setOrderStatus("异常单");
                    updateOrder.setMsg(msg);
                    orderMapper.update(updateOrder, wrapper);
                }
            }
        } else if (order.getUserType().toString().equals("10")) {

            String productId = "1329"; // 产品id
            String saleId = null; // 销售id
            JSONObject saleJsonObject =
                    getSaleId(productId, currentTimeStr, 0); // 获取销售ID
            log.info("----------调用智能平台的获取销售品接口返回值：" + saleJsonObject);
            String expenses = null;
            if (schoolMap.get("identifying") != null) {
                expenses = schoolMap.get("identifying").toString();
            }

            JSONArray saleList = saleJsonObject.getJSONArray("list");
            System.out.println("----saleList---：" + saleList);

            for (int i = 0; i < saleList.size(); i++) {
                net.sf.json.JSONObject itmeJson = net.sf.json.JSONObject.fromObject(saleList.get(i));
                // 判断获取的全部产品与订单产品符合的拿取对应的ID
                if (itmeJson.getString("propertyName").indexOf("提速包") != -1) {
                    if (itmeJson.getString("name").equals(expenses)) {
                        // 获取对应产品ID
                        saleId = itmeJson.getString("saleId");
                    }
                } else if (itmeJson.getString("propertyName").indexOf("增值业务") != -1) {
                    if (itmeJson.getString("name").equals(expenses)) {
                        // 获取对应产品ID
                        saleId = itmeJson.getString("saleId");
                    }
                }
            }
            //        	3、提交订单到智能平台
            List<NameValuePair> qParams = new ArrayList<NameValuePair>();
//            HttpHost proxy = new HttpHost("172.18.101.170", 3128);
            RequestConfig defaultRequestConfig =
                    RequestConfig.custom()
                            .setSocketTimeout(500000)
                            .setConnectTimeout(500000)
                            .setConnectionRequestTimeout(500000)
//                          .setProxy(proxy)
                            .build();
            CloseableHttpClient httpclient =
                    HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            HttpEntity entity = null;
            // https://icloud.mini189.cn/api/create-order.action
            HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "create-order.action");
            RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
            httpPost.setConfig(requestConfig);

            Map<String, String> signMap = new HashMap<String, String>();

            qParams.add(new BasicNameValuePair("service", "order.combined.create")); // api标识，必填且唯一
            signMap.put("service", "order.combined.create");

            qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON)); // 用户名，必填
            signMap.put("userName", Constant.ZHENGSHIAUCCON);

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

            qParams.add(new BasicNameValuePair("productCategory", "融合产品")); // 业务类型，必填且唯一
            signMap.put("productCategory", "融合产品");

            qParams.add(
                    new BasicNameValuePair("transactType", "旧宽旧移")); // 办理类型，必填[新宽新移][新宽旧移][旧宽新移][旧宽旧移]
            signMap.put("transactType", "旧宽旧移");

            qParams.add(
                    new BasicNameValuePair(
                            "broadbandAccess",
                            order.getDmtNumber())); // 宽带接入号，办理类型，若选择[旧宽新移]或[旧宽旧移]，此项必填
            signMap.put("broadbandAccess", order.getDmtNumber());

            qParams.add(
                    new BasicNameValuePair(
                            "ctNumber",
                            order.getBusinessNumber())); // 电信号码，办理类型，若选择[新宽旧移]或[旧宽旧移]，此项必填
            signMap.put("ctNumber", order.getBusinessNumber());

            String addressID = null;
            String landId = null;
            if (BeanUtil.isNotBlank(schoolMap)) {
                addressID = (String) schoolMap.get("universityInstalledAddressId");
                landId = (String) schoolMap.get("universityPackageNumber");
            } else {
                addressID = "00000";
                landId = "20180621";
            }

            qParams.add(new BasicNameValuePair("addressId", addressID)); // 报装地址-地址ID，选填
            signMap.put("addressId", addressID);

            qParams.add(new BasicNameValuePair("govEntCustomer", "0")); // 是否政企客户下单 0：否 1：是，必填
            signMap.put("govEntCustomer", "0");

            qParams.add(new BasicNameValuePair("agentName", "")); // 若是政企客户下单，代办人姓名，必填
            signMap.put("agentName", "");

            qParams.add(new BasicNameValuePair("agentCardNum", "")); // 若是政企客户下单，代办人身份证号码，必填
            signMap.put("agentCardNum", "");

            qParams.add(
                    new BasicNameValuePair(
                            "customerName", order.getCustomerName())); // 客户姓名，必填
            signMap.put("customerName", order.getCustomerName());

            qParams.add(
                    new BasicNameValuePair(
                            "customerPhone", order.getContactNumber())); // 客户电话|代办人电话，必填
            signMap.put("customerPhone", order.getContactNumber());

            qParams.add(new BasicNameValuePair("customerCardType", "身份证")); // 证件类型，必填且只能为身份证
            signMap.put("customerCardType", "身份证");

            qParams.add(
                    new BasicNameValuePair(
                            "customerCardNum", order.getIdCard())); // 证件号码，必填
            signMap.put("customerCardNum", order.getIdCard());

            qParams.add(new BasicNameValuePair("landId", landId)); // 揽装工号，必填
            signMap.put("landId", landId);

            qParams.add(new BasicNameValuePair("comarketingLanId", "")); // 协销工号，选填
            signMap.put("comarketingLanId", "");

            qParams.add(new BasicNameValuePair("groupComarketingLanId", "")); // 集团协销工号，选填
            signMap.put("groupComarketingLanId", "");

            qParams.add(
                    new BasicNameValuePair(
                            "orderOutNum", order.getKdOrderId())); // 外部订单编号，选填!；
            //		通过API接口下单，必须传入一个外部接入商的订单编号,该编号与智能营销系统编号一一对应
            signMap.put("orderOutNum", order.getKdOrderId());

            qParams.add(new BasicNameValuePair("orderSource", "校园宽带自助受理")); // 订单来源 ，选填
            signMap.put("orderSource", "校园宽带自助受理");

            qParams.add(
                    new BasicNameValuePair(
                            "orderSourceNum",
                            order.getKdOrderId())); // 订单来源单号，选填；与订单来源对应，用于业务上记录订单的来源订单编号
            signMap.put("orderSourceNum", order.getKdOrderId());

            qParams.add(new BasicNameValuePair("salePointCode", "")); // 销售点编码，选填
            signMap.put("salePointCode", "");

            qParams.add(new BasicNameValuePair("personCode", "")); // 人员编码，必填
            signMap.put("personCode", "");

            qParams.add(
                    new BasicNameValuePair(
                            "deliveryContact", order.getCustomerName())); // 联系人，必填
            signMap.put("deliveryContact", order.getCustomerName());

            qParams.add(
                    new BasicNameValuePair(
                            "deliveryContactPhone", order.getContactNumber())); // 联系电话，必填
            signMap.put("deliveryContactPhone", order.getContactNumber());

            qParams.add(new BasicNameValuePair("deliveryContactPhone2", "")); // 联系电话2，选填
            signMap.put("deliveryContactPhone2", "");

            qParams.add(new BasicNameValuePair("invoiced", "0")); // 是否需要发票，必填
            // 0:不需要；1:一次性发票；2:分月发票
            signMap.put("invoiced", "0");

            qParams.add(new BasicNameValuePair("invoiceTitle", "")); // 发票抬头，若需要发票必填
            signMap.put("invoiceTitle", "");

            qParams.add(new BasicNameValuePair("invoiceDeliveryAddress", "")); // 电子邮箱，若需要发票必填
            signMap.put("invoiceDeliveryAddress", "");

            qParams.add(
                    new BasicNameValuePair("deliveryType", "不需配送")); // 发货类型，必填，填写[同德仓发货][不需配送][代理商自行发货]
            signMap.put("deliveryType", "不需配送");

            qParams.add(
                    new BasicNameValuePair(
                            "deliveryCompany", "")); // 配送公司，选填，同德仓发货必填；填写只能填顺丰速运或者如风达或者京东快递或者EMS
            signMap.put("deliveryCompany", "");

            qParams.add(new BasicNameValuePair("gift", "")); // 礼品，选填，请通过礼品列表接口获取
            signMap.put("gift", "");

            qParams.add(new BasicNameValuePair("giftNum", "")); // 礼品数量，选填，若礼品填写则必填且为正整数
            signMap.put("giftNum", "");

            qParams.add(new BasicNameValuePair("acceptPriority", "7")); // 受理优先级  为0-10范围内的整数! 选填
            signMap.put("acceptPriority", "7");

            List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>(); // 产品信息
            List<Map<String, Object>> paymentList =
                    new ArrayList<Map<String, Object>>(); // 销售品信息(费用项)
            List<Map<String, Object>> addPropertyList =
                    new ArrayList<Map<String, Object>>(); // 自定义产品属性

            // 下单产品
            Map<String, Object> productMap = new HashMap<String, Object>();
            // 产品(一个订单只能有一种产品且数量为1)
            productMap.put("productId", productId); // 产品id,必填，请通过产品列表接口获取
            //
            //// 产品都必须传一个产品对应的唯一的收费项
            Map<String, Object> paymentListMap = new HashMap<String, Object>();
            paymentListMap.put("id", "4455"); // 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
            paymentListMap.put("saleName", "校园融合套餐"); // 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
            paymentListMap.put("payType", "2"); // 缴费方式，
            // 必填（例：payType：3）1：银行划账2：现金支付3：代理商打款4：穗易付6：支付宝划扣7：货到付款8：装维上门收取9:第三方托收11：代理商代扣

            //单宽带
            Map<String, Object> paymentListMap2 = new HashMap<String, Object>();
            paymentListMap2.put("id", saleId); // 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
            paymentListMap2.put("saleName", ""); // 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
            paymentListMap2.put("payType", "2");
            paymentListMap2.put("saleAmount", "");
            paymentListMap2.put("payAmount", "0");

            paymentList.add(paymentListMap);
            paymentList.add(paymentListMap2);
            productMap.put("payment", paymentList);

            Map<String, Object> propertyMap1 = new HashMap<String, Object>();
            propertyMap1.put("name", "学校名称");
            propertyMap1.put("value", (String) orderMap.get("orderUniversityName"));

            Map<String, Object> propertyMap17 = new HashMap<String, Object>();
            propertyMap17.put("name", "关联移动号码");
            propertyMap17.put("value", order.getBusinessNumber());

            Map<String, Object> propertyMap18 = new HashMap<String, Object>();
            propertyMap18.put("name", "宽带接入号");
            propertyMap18.put("value", order.getDmtNumber());

            Map<String, Object> propertyMap16 = new HashMap<String, Object>();
            propertyMap16.put("name", "宽带提速速率");
            propertyMap16.put("value", schoolMap.get("expenses"));

            addPropertyList.add(propertyMap1);
            addPropertyList.add(propertyMap17);
            addPropertyList.add(propertyMap18);
            addPropertyList.add(propertyMap16);

            productMap.put("addProperties", addPropertyList);
            productList.add(productMap);
            // 将对象装换为json字符串
            String productJson = net.sf.json.JSONArray.fromObject(productList).toString();
            try {
                qParams.add(
                        new BasicNameValuePair(
                                "productJson", URLEncoder.encode(productJson, "UTF-8"))); // 产品信息，必填
                signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            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(Constant.ZHANGSHIKEY);
            qParams.add(
                    new BasicNameValuePair(
                            "sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)))); // 签名，必填
            net.sf.json.JSONObject resultDataJson = null;
            try {
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
                httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
                log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
                Constant.trustEveryone();
                HttpResponse response = httpclient.execute(httpPost);
                entity = response.getEntity();
                String httpResult = EntityUtils.toString(entity, "UTF-8");
                log.info("宽叠移下单接口，返回信息:" + httpResult);
                resultDataJson = net.sf.json.JSONObject.fromObject(httpResult);
            } catch (SSLHandshakeException s) {
                HttpResponse response = httpclient.execute(httpPost);
                entity = response.getEntity();
                String httpResult = EntityUtils.toString(entity, "UTF-8");
                log.info("宽叠移下单接口，返回信息:" + httpResult);
                resultDataJson = net.sf.json.JSONObject.fromObject(httpResult);
            } catch (Exception e) {
                log.info("宽叠移下单接口异常");
                e.printStackTrace();
            } finally {
                httpPost.releaseConnection();
            }
            String orderNum = (String) resultDataJson.get("orderNumber");
            net.sf.json.JSONObject queryOrderJsonObject = null;
            if (StringUtils.isNotBlank(orderNum)) {
                /*	5、更新数据库   */
                Wrapper<Order> wrapper = new EntityWrapper<>();
                wrapper.eq("id", order.getId());
                Order updateOrder = new Order();
                updateOrder.setOrderStatus("审核中");
                updateOrder.setOrderId(orderNum);
                orderMapper.update(updateOrder, wrapper);

                OrderHistory orderHistory = new OrderHistory();
                orderHistory.setOrderId(order.getId());
                orderHistory.setCreateDate(new Date());
                orderHistory.setStatus("智能平台下单成功" + orderNum);
                orderHistoryMapper.insert(orderHistory);
            } else {
                String msg = (String) resultDataJson.get("msg");
                if (StringUtils.isNotBlank(msg)&& !msg.equals("订单来源单号已存在，请勿重复下单")) {
                    Wrapper<Order> wrapper = new EntityWrapper<>();
                    wrapper.eq("id", order.getId());
                    Order updateOrder = new Order();
                    updateOrder.setOrderStatus("异常单");
                    updateOrder.setMsg(msg);
                    orderMapper.update(updateOrder, wrapper);
                }

                OrderHistory orderHistory = new OrderHistory();
                orderHistory.setOrderId(order.getId());
                orderHistory.setCreateDate(new Date());
                orderHistory.setStatus("智能平台下单失败" + orderNum);
                orderHistoryMapper.insert(orderHistory);
            }
        }
    }

    /**
     * 查询智能平台状态（两个参数只要填写一个，默认填写系统订单号即可）
     *
     * @param systemOrderNum 系统订单号
     * @param orderNum 智能平台订单号
     * @return 返回结果为json字符串，若错误则返回空字符串
     * {
     *   msg=订单查询成功,
     *   wayBillNumber=,
     *   sourceBizEntity=1eue64bp0d5xl1jdkgms,
     *   stateName=收费【人工处理】,
     *   outBizEntity=1eue64bp0d5xl1jdkgms,
     *   orderStatus=受理成功【待收费】,
     *   remark=,
     *   state=48,
     *   bizEntity=THD20210110004759,
     *   deliveryNumber=,
     *   status=000001
     * }
     */
    public String queryStatus(String systemOrderNum, String orderNum) {
        ObjectMapper OBJECT_MAPPER = new ObjectMapper();
        List<BasicNameValuePair> qParams = new ArrayList<>();
        Map<String, Object> signMap = new HashMap<>();//待签名参数
        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(Constant.ZHANGSHIURL + "query.action");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);
        qParams.add(new BasicNameValuePair("service", "query.order.status"));//api标识，必填
        signMap.put("service","query.order.status");
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON));//用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        String timeStamp = DateUtil.format(new Date(), DateUtil.yyyyMMddHHmmss);
        qParams.add(new BasicNameValuePair("timeStamp", timeStamp));
        signMap.put("timeStamp",timeStamp);

        if(StringUtils.isNotBlank(orderNum)) {
           qParams.add(new BasicNameValuePair("orderNumber", orderNum));//智能平台订单编号，非必填
           signMap.put("orderNumber", orderNum);
        }
        if (StringUtils.isNotBlank(systemOrderNum)) {
            qParams.add(new BasicNameValuePair("outOrderNum",systemOrderNum));//外部订单编号，非必填
            signMap.put("outOrderNum", systemOrderNum);
        }

        try{
            List<String> keys = new ArrayList<>();
            keys.addAll(signMap.keySet());
            Collections.sort(keys);//key按字符串升序
            String value,plaintext = "";
            for(String key : keys){
                value = signMap.get(key).toString();
                plaintext = plaintext.concat(value);
            }
            plaintext = plaintext.concat(Constant.ZHANGSHIKEY);

            System.out.println(plaintext);
            //        				plaintext = plaintext.concat("ef6f0b823b5cecc9972dee2bf9fb9936");
            String sign = DigestUtil.md5Hex(plaintext).toUpperCase();
            qParams.add(new BasicNameValuePair("sign",sign));//签名，必填
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            // 请求返回结果
            String httpResult = EntityUtils.toString(response.getEntity());
            // String 转化为 Map格式结果
            HashMap<String, Object> mapData = new HashMap<>();
            mapData.putAll(OBJECT_MAPPER.readValue(httpResult, mapData.getClass()));
            log.info("智能平台请求状态返回数据：" + mapData);
            if ("000001".equals(mapData.get("status"))) {
                return JSONObject.toJSONString(mapData);
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return "";
    }
}
