package com.winsun.outSideSystem;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
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.netflix.ribbon.proxy.annotation.Http;
import com.winsun.auth.core.util.DateUtil;
import com.winsun.bean.*;
import com.winsun.constant.Constant;
import com.winsun.mapper.*;
import com.winsun.smsUtils.StringUtil;
import com.winsun.utils.*;

import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLHandshakeException;
import java.io.DataInput;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 *
 * @date 2021-01-28 15:36
 */

@Slf4j
@Component
public class IntelligenceSendOrders {
    final String publicKey =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAok8DnvM2OBwtzNoJb4nA" +
                    "jn4lgCkSxLyRw5lLiUfsi+40h00CGAC1arvbinTTbtrSnm4YDYlaJwveiOeDKdk0" +
                    "f2Yglb/8loEbNTqb1OqNxUeM1wYLRBXvAkkZ5fZllajWzFMkoNU/JQ4+T8sMATxm" +
                    "1d1XRcgM6zlgVwX6siDoLZ5Dm23CTS7SXhyMLtS9cgLefHcOckPQyXoB/IJqb0K1" +
                    "P0Sk0PE1OSRzpsI9JVzhsSW164fwYpxEbygj9O9JAmAszixwItt2j5zLJ6zRnK3R" +
                    "OrcAVMN/vpXTN2dCLGZXQrsTK9sAWASzIWTiQRzmnwxsQY7y4u2h+k41n8Z5tw03" +
                    "wwIDAQAB";

    @Autowired
    private UniversityInfoMapper universityInfoMapper;

    @Autowired
    private OrderViewMapper orderViewMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private OrderHistoryMapper orderHistoryMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    private static List<String> shoolNames = new ArrayList<>();

    {
        shoolNames.add("广东省民政职业技术学校(wifi)");
        shoolNames.add("广东省海洋工程职业技术学校（纯wifi）");
        shoolNames.add("广州华夏职业学院（纯wifi）");
        shoolNames.add("广东司法警官职业学院");
        shoolNames.add("广州土地房产管理职业技术学校");
        shoolNames.add("广州航海高等专科学校（纯wifi）");
        shoolNames.add("广州城市职业学院滨江鹭江校区（纯wifi）");
        shoolNames.add("广东岭南职业技术学院");
        shoolNames.add("广东省高新技术技工学校");
        shoolNames.add("广州中医药大学南校区");
        shoolNames.add("中山大学（大学城）");
        shoolNames.add("广州市土地房产管理职业学校（纯wifi）");
        shoolNames.add("广东水利电力职业技术学院（纯wifi）");
        shoolNames.add("广州南洋理工职业学院（纯wifi）");
        shoolNames.add("广州工程技术职业学院（纯wifi）");
        shoolNames.add("从化清北职业培训学校");
    }


    //@Autowired
    //private ZnptSignUtils znptSignUtils;


    /**
     * 单宽下单公共类
     *
     * @param orderMap
     */
    public void singleBroadSendOrder(Map<String, Object> orderMap) {
        try {

            // 初始化下单支付参数
            String ORDERSEQ = "", ORDERAMOUNT = "", ORDERREQTRANSEQ = "", UPTRANSEQ = "";

            if (orderMap.get("kd_order_id") == null) {
                log.info("kd_order_id为空。");
                return;
            }
            Map<String, Object> orderViewMap = null;
            Map<String, Object> schoolMap = null;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String currentTimeStr = "";
            ORDERSEQ = orderMap.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) {
                orderViewMap = orderViewMaps.get(0);
                orderViewMap.put("", orderMap.get("hehouren_name"));
            }
            if (orderViewMap == null) {
                log.info("错误记录：" + JSONObject.toJSONString(orderMap));
                log.info("订单号：" + ORDERSEQ + "，在order_view表中无记录，无法进行智能平台下单");
                return;
            }

            //产品价格
            ORDERAMOUNT = orderViewMap.get("webOrderAmount") != null ? orderViewMap.get("webOrderAmount").toString() : "0";
            //穗易付订单号
            ORDERREQTRANSEQ = orderViewMap.get("orderReqtranSeq") != null ? orderViewMap.get("orderReqtranSeq").toString() : "";
            //支付平台流水号
            UPTRANSEQ = orderViewMap.get("uptranseq") != null ? orderViewMap.get("uptranseq").toString() : "";

            // 根据学校名称，获取该学校信息
            schoolMap = setSchoolMap(orderMap, orderViewMap, schoolMap);


            if (orderMap.get("orderSeqThd") == null || "".equals(orderMap.get("orderSeqThd"))) {
                ORDERAMOUNT = ORDERAMOUNT.replace("元", "");
                ORDERAMOUNT = ORDERAMOUNT.replace(".00", "");
                String productName = "校园宽带" + ORDERAMOUNT + "元";
                if (ORDERAMOUNT.contains("0.01")) {
                    productName = "校园宽带30元";
                    ORDERAMOUNT = "30";
                } else if (ORDERAMOUNT.contains("0.02")) {
                    productName = "校园宽带300元";
                    ORDERAMOUNT = "300";
                }
                if (productName.equals("校园宽带0元")) {
                    productName = "校园宽带（免月租）";
                    ORDERAMOUNT = "0";
                    ORDERREQTRANSEQ = "00000";
                    UPTRANSEQ = "00000";
                }
                //例：	productName = "校园宽带30元";
                schoolMap = setPriceIndex(schoolMap, orderViewMap, ORDERAMOUNT);


                //	3、提交订单到智能平台
                kong.unirest.HttpResponse<String> submitOrderJsonObject =
                        getOrderInfo(
                                schoolMap,          //宽带订单对应的学校信息
                                orderViewMap,           //宽带订单信息
                                currentTimeStr,     //当前时间
                                productName,        //产品名称
                                ORDERSEQ,           //kd_order_id 宽带ID
                                UPTRANSEQ,          //支付平台流水号
                                ORDERAMOUNT,        //产品价格
                                ORDERREQTRANSEQ,    //穗易付订单号
                                5,            //下单类型(3：融合业务；5：单宽业务；10：单宽进融)
                                0);
                log.info(
                        "----------调用单宽带接口（提交订单至智能平台）并返回参数信息---status:"
                                + submitOrderJsonObject.getStatus()
                                + " msg:"
                                + submitOrderJsonObject.getParsingError()
                                + " orderNum:"
                                + submitOrderJsonObject.getBody());

                if (submitOrderJsonObject.getStatus() != 200) {
                    Wrapper<Order> orderWrapper = new EntityWrapper<>();
                    orderWrapper.eq("kd_order_id", orderMap.get("kd_order_id"));
                    Order updateOrder = new Order();
                    updateOrder.setOrderStatus("待处理");
                    updateOrder.setMsg("下单异常");
//                    updateOrder.setCheckFail(submitOrderJsonObject.getParsingError().toString());
                    orderMapper.update(updateOrder, orderWrapper);
                    return;
                }

                //	4、查询智能订单是否存在
                String orderNum = submitOrderJsonObject.getBody();
                JSONObject queryOrderJsonObject = getQueryOrderInfo(orderNum, 1);
                Map<String, Object> map = JSONObject.parseObject(queryOrderJsonObject.getString("data"));
                List<Object> list = (List<Object>) map.get("q");
                Map<String, Object> q = (Map<String, Object>) list.get(0);
                Map<String, Object> orderStatus = (Map<String, Object>) q.get("订单当前状态");
                if (!orderStatus.containsKey("订单当前状态|状态备注")) {
                    //5、更新数据库
                    String state = (String) orderStatus.get("订单状态名称");
                    // 更新hhr_order
                    Wrapper<Order> orderWrapper = new EntityWrapper<>();
                    orderWrapper.eq("kd_order_id", orderMap.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", orderMap.get("kd_order_id").toString());
                    orderViewMapper.update(updateOrderView, wrapperOrderView);
                    log.info("----------将智能订单状态更新至数据库success：" + state);
                } else {
                    // 报错更新提示
                    Wrapper<Order> orderWrapper = new EntityWrapper<>();
                    orderWrapper.eq("kd_order_id", orderMap.get("kd_order_id"));
                    Order updateOrder = new Order();
                    updateOrder.setOrderId(orderNum);
                    updateOrder.setThStatus((String) orderStatus.get("订单状态名称"));
                    updateOrder.setOrderStatus("待处理");
                    if (orderStatus.get("订单当前状态|状态备注").toString().contains("停机") || orderStatus.get("订单当前状态|状态备注").toString().contains("欠费")) {
                        updateOrder.setMsg("停机/名下欠费");
                    } else if (orderStatus.get("订单当前状态|状态备注").toString().contains("黑名单")) {
                        updateOrder.setMsg("身份证黑名单");
                    }
                    orderMapper.update(updateOrder, orderWrapper);
                }
            } else {
                log.info(
                        "---单宽支付接口推送---"
                                + ORDERSEQ
                                + "---"
                                + UPTRANSEQ
                                + "---"
                                + ORDERAMOUNT
                                + "---"
                                + ORDERREQTRANSEQ);
                log.info("重复订单");
            }
        } catch (Exception e) {
            log.info("单宽下单失败");
            e.printStackTrace();
        }
    }


    /**
     * @param schoolMap
     * @param orderViewMap
     * @param currentTimeStr
     * @param productName
     * @param ORDERSEQ
     * @param UPTRANSEQ
     * @param ORDERAMOUNT
     * @param ORDERREQTRANSEQ
     * @param businessType
     * @param count
     * @return 新单宽下单接口调用
     * @throws Exception
     */
    private kong.unirest.HttpResponse<String> getOrderInfo(
            Map<String, Object> schoolMap,  //宽带订单对应的学校信息
            Map<String, Object> orderViewMap,   //宽带订单信息
            String currentTimeStr,          //当前时间
            String productName,             //产品名称
            String ORDERSEQ,                //kd_order_id 宽带ID
            String UPTRANSEQ,               //支付平台流水号
            String ORDERAMOUNT,             //产品价格
            String ORDERREQTRANSEQ,         //穗易付订单号
            int businessType,             //业务类型
            int count)                      //0
            throws Exception {
        String addressDistrict = null;                  //所在区域
        String address = null;                          //装机地址
        String addressID = null;                        //地址ID
        String landId = null;                           //揽装工号
        String universityTerminalType = null;           //允许上网终端类型
        String universityUserCategory = null;           //用户类别
        String universityUserType = null;               //用户类型
        String universityMonthlyRentType = null;        //月租类型
        String universityChargingAttribute = null;      //计费属性
        String universityOnlineNumber = null;           //最大在线数
        String universityOneManTerminal = null;         //一人一号多终端:0否  1是
        String universityIsFtthHub = null;              //是否FTTH+HUB:0否  1是
        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 = "测试";
        }


        Map<String, Map<String, String>> map = new HashMap<>();
        Map<String, String> return_data = new HashMap<>();
        return_data.put("code", "");
        return_data.put("route", "提交订单"); //[提交下单] [订单保存] [提交审核] 默认为提交下单
        return_data.put("微信openId", "");
        return_data.put("微信appId", "");
        map.put("return_data", return_data);

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

        /*Map<String, Object> attachment = new HashMap<>(); // 附件
        attachment.put("订单底单", "");
        order_data.put("附件", attachment);*/

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

        Map<String, Object> customerInformation = new HashMap<>(); //客户信息
        customerInformation.put("联系人", (String) orderViewMap.get("orderName"));
        customerInformation.put("客户类型", "普通客户");
        customerInformation.put("客户证件号码", (String) orderViewMap.get("orderNumber"));
        customerInformation.put("客户证件姓名", (String) orderViewMap.get("orderName"));
        customerInformation.put("联系电话", (String) orderViewMap.get("orderPhone"));
        //customerInformation.put("客户证件地址", "");
        customerInformation.put("装机联系电话", (String) orderViewMap.get("orderPhone"));
        customerInformation.put("装机联系人", (String) orderViewMap.get("orderName"));
        customerInformation.put("客户证件类型", "身份证");
        customerInformation.put("通讯地址", address);
        order_data.put("客户信息", customerInformation);

        order_data.put("装机详细地址", address);
        order_data.put("订单来源单号", (String) orderViewMap.get("orderSeq")); // 订单来源单号，必填； 与订单来源对应，用于业务上记录订单的来源订单编号
        order_data.put("订单备注", "");
        if (businessType == 5) {
            order_data.put("办理类型", "新宽新移"); //新宽新移 ,新宽旧移,旧宽新移,旧宽旧移
            order_data.put("付费类型", "预付费"); //预付费、后付费、其他  选填
        } else if (businessType == 10) {
            order_data.put("办理类型", "旧宽旧移"); //新宽新移 ,新宽旧移,旧宽新移,旧宽旧移
            order_data.put("付费类型", "预付费"); //预付费、后付费、其他  选填
        }


        Map<String, String> school = schoolMapper.selectByHeHuorenId(String.valueOf(orderViewMap.get("hehuorenId")));
        Map<String, Object> packageInformation = new HashMap<>();   //揽装信息
        packageInformation.put("揽装姓名", school.get("lz_user"));
        packageInformation.put("三级机构", "");
        packageInformation.put("一级机构", "");
        packageInformation.put("企微号码", "");
        packageInformation.put("揽装人联系电话", "");
        packageInformation.put("机构ID", addressID);
        packageInformation.put("四级机构", "");
        packageInformation.put("二级机构", "");
        packageInformation.put("揽装工号", landId);
        packageInformation.put("协销工号", "");
        packageInformation.put("五级机构", "");
        order_data.put("揽装信息", packageInformation);

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

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

        HashMap<String, Object> orderingProducts = new HashMap<>();  //订购产品
        //orderingProducts.put("产品SKU", "");
        orderingProducts.put("产品名称", productName);
        orderingProducts.put("受理内容", "");
        orderingProducts.put("付费类型", "预付费");

        // 属性列表
        List<AttributeList> attributeList = new ArrayList();

        AttributeList roadbandRate = new AttributeList();
        roadbandRate.setName("宽带速率");
        String speed = (String) schoolMap.get("speed");
        /*if (StringUtils.isNotBlank(setMeal)) {
            setMeal = setMeal.replace("包月", "");
            setMeal = setMeal.replace("包年", "");
        }*/
        if (businessType == 5) {
            if (speed.equals("20M")) {
                roadbandRate.setValue("20M下行速率/4M上行速率");
            } else if (speed.equals("2M")) {
                roadbandRate.setValue("2M下行速率/512K上行速率");
            } else if (speed.equals("50M")) {
                roadbandRate.setValue("50M下行速率/10M上行速率");
            } else {
                roadbandRate.setValue(speed);
            }
        } else if (businessType == 3) {
            roadbandRate.setValue(speed);
        } else if (businessType == 10) {
            roadbandRate.setName("宽带提速速率");
            String expenses = (String) schoolMap.get("expenses");
            roadbandRate.setValue(expenses);
        }
        attributeList.add(roadbandRate);

        if (businessType == 3 || businessType == 10) {
            AttributeList roadbandExperienceRate = new AttributeList();
            roadbandExperienceRate.setName("宽带体验速率");
            String expenses = (String) schoolMap.get("expenses");
            roadbandExperienceRate.setValue(expenses);
            attributeList.add(roadbandExperienceRate);

            AttributeList speedBag = new AttributeList();
            speedBag.setName("提速包");
            speedBag.setValue(schoolMap.get("identifying").toString());
            attributeList.add(speedBag);
        }

        AttributeList broadbandProperties = new AttributeList();
        if (businessType == 5) {
            broadbandProperties.setName("宽带类型");
            if ("0".equals(ORDERAMOUNT)) {
                broadbandProperties.setValue(ORDERAMOUNT + "元");
                attributeList.add(broadbandProperties);
            } else if (((String) orderViewMap.get("orderSetMeal")).contains("包月")) {
                broadbandProperties.setValue(ORDERAMOUNT + "元/月");
                attributeList.add(broadbandProperties);
            } else {
                broadbandProperties.setValue(ORDERAMOUNT + "元/年");
                attributeList.add(broadbandProperties);
            }
        }

        AttributeList AddressID = new AttributeList();
        AddressID.setName("地址ID");
        AddressID.setValue(addressID);
        attributeList.add(AddressID);


        if (businessType == 3) {
            AttributeList type = new AttributeList();
            type.setName("单宽带");
            if (shoolNames.contains(orderViewMap.get("orderUniversityName"))) {
                type.setValue("校园宽带（免月租）.");
            } else if (((String) orderViewMap.get("orderSetMeal")).contains("包年")) {
                type.setValue("校园宽带300元/年.");
            } else if (((String) orderViewMap.get("orderSetMeal")).contains("包月")) {
                type.setValue("校园宽带30元/月.");
            }
            attributeList.add(type);
        }


        AttributeList internetType = new AttributeList();
        internetType.setName("允许上网终端类型");
        internetType.setValue(universityTerminalType);
        attributeList.add(internetType);

        AttributeList userCategory = new AttributeList();
        userCategory.setName("用户类别");
        userCategory.setValue(universityUserCategory);
        attributeList.add(userCategory);

        AttributeList schoolName = new AttributeList();
        schoolName.setName("学校名称");
        schoolName.setValue((String) orderViewMap.get("orderUniversityName").toString().replace(" ", ""));
        attributeList.add(schoolName);

        AttributeList handlingNumber = new AttributeList();
        //AttributeList handleNumber = new AttributeList();
        if (businessType == 3 || businessType == 10) {
            /*handleNumber.setName("关联第三方账户接入号");
            handleNumber.setValue((String) orderViewMap.get("orderPhone"));*/
            handlingNumber.setName("关联移动号码");
            handlingNumber.setValue((String) orderViewMap.get("orderCustomerRemarks"));
            attributeList.add(handlingNumber);
        }

        AttributeList studentID = new AttributeList();
        studentID.setName("学生证号");
        studentID.setValue((String) orderViewMap.get("orderCustomerStudentId"));
        attributeList.add(studentID);

        AttributeList userType = new AttributeList();
        userType.setName("用户类型");
        userType.setValue(universityUserType);
        attributeList.add(userType);

        AttributeList monthlyRentType = new AttributeList();
        monthlyRentType.setName("月租类型");
        monthlyRentType.setValue(universityMonthlyRentType);
        attributeList.add(monthlyRentType);

        AttributeList billingAttributes = new AttributeList();
        billingAttributes.setName("计费属性");
        billingAttributes.setValue(universityChargingAttribute);
        attributeList.add(billingAttributes);

        AttributeList customerAccount = new AttributeList();
        customerAccount.setName("多媒体账号");
        customerAccount.setValue((String) orderViewMap.get("orderCustomerAccount"));
        attributeList.add(customerAccount);

        if (businessType != 10) {
            AttributeList customerPwd = new AttributeList();
            customerPwd.setName("多媒体账号密码");
            customerPwd.setValue((String) orderViewMap.get("orderCustomerPwd"));
            attributeList.add(customerPwd);
        }

        if (businessType == 10) {
            AttributeList rhSpend = new AttributeList();
            rhSpend.setName("融合宽带提速");
            rhSpend.setValue(schoolMap.get("identifying").toString());
            attributeList.add(rhSpend);
        }

        AttributeList onlineNumber = new AttributeList();
        onlineNumber.setName("最大在线数");
        onlineNumber.setValue(universityOnlineNumber);
        attributeList.add(onlineNumber);

        AttributeList oneManTerminal = new AttributeList();
        oneManTerminal.setName("一人一号多终端");
        oneManTerminal.setValue(universityOneManTerminal);
        attributeList.add(oneManTerminal);

        AttributeList isFtthHub = new AttributeList();
        isFtthHub.setName("是否FTTH+HUB");
        isFtthHub.setValue(universityIsFtthHub);
        attributeList.add(isFtthHub);

        AttributeList exteriorLines = new AttributeList();
        exteriorLines.setName("外线方式");
        exteriorLines.setValue(universityExteriorLines);
        attributeList.add(exteriorLines);

        AttributeList chargeMode = new AttributeList();
        chargeMode.setName("宽带首月费用类型");
        chargeMode.setValue(universityChargeMode);
        attributeList.add(chargeMode);
        orderingProducts.put("属性列表", attributeList);

        if (businessType == 5) {
            orderingProducts.put("AI编码", "DQ_ADSL_CAMPUS");
        } else if (businessType == 3) {
            orderingProducts.put("AI编码", "4B90FBDD2A1A43EE8A4C963115C52F14");
        } else if (businessType == 10) {
            orderingProducts.put("AI编码", "46102E5199DE4B089AC46CBE9B22F9EB");
        }
        order_data.put("订购产品", orderingProducts);


        if (businessType == 3) {
            order_data.put("业务类型", "融合业务");  //业务类型
        } else if (businessType == 5) {
            order_data.put("业务类型", "单宽业务");  //业务类型
        } else if (businessType == 10) {
            order_data.put("业务类型", "增值业务");  //业务类型
        }

        if (businessType == 3 || businessType == 10) {
            List<HashMap<String, Object>> mobileAccessList = new ArrayList<>();
            HashMap<String, Object> mobileAccess = new HashMap<>();  //移动接入
            mobileAccess.put("订购类型", "已有");
            mobileAccess.put("移动接入号", (String) orderViewMap.get("orderPhone"));
            mobileAccess.put("号码类型", "主卡");
            mobileAccessList.add(mobileAccess);
            order_data.put("移动接入", mobileAccessList);
        }

        HashMap<String, Object> broadbandInstalledCapacity = new HashMap<>();   //宽带装机
        broadbandInstalledCapacity.put("装机详细地址", address);
        broadbandInstalledCapacity.put("省", "广东省");
        broadbandInstalledCapacity.put("市", "广州市");
        broadbandInstalledCapacity.put("区", addressDistrict);
        broadbandInstalledCapacity.put("装机地址ID", addressID);
        broadbandInstalledCapacity.put("宽带接入号", "新装");
        broadbandInstalledCapacity.put("订购类型", "新装");
        if (businessType == 10) {
            broadbandInstalledCapacity.put("宽带接入号", orderViewMap.get("dmt_number"));
            broadbandInstalledCapacity.put("订购类型", "已有");
        }
        order_data.put("宽带装机", broadbandInstalledCapacity);

        if (businessType != 10) {
            HashMap<Object, Object> monthlyFeeItems = new HashMap<>();   //月租费用项
            List<HashMap<String, Object>> expenseItemsList = new ArrayList<>(); //费用项列表
//        List<HashMap<String, Object>> suipayPayment = new ArrayList<>(); //穗易付支付
            HashMap<String, Object> expenseItemsMap = new HashMap<>();
//        HashMap<String, Object> suipayPaymentMap = new HashMap<>();
            expenseItemsMap.put("费用项名称", productName);
            expenseItemsMap.put("费用项金额", "00.0000");
            if (((String) orderViewMap.get("orderSetMeal")).contains("包月")) {
                expenseItemsMap.put("费用项类型", "月租");
            } else if (((String) orderViewMap.get("orderSetMeal")).contains("包年")) {
                expenseItemsMap.put("费用项类型", "年租");
            }
            ORDERAMOUNT = ORDERAMOUNT.replace("元", "");
            if (ORDERAMOUNT.equals("0.01") || ORDERAMOUNT.equals("0.02")) {
                monthlyFeeItems.put("缴费方式", "现金支付");  // 缴费方式，必填（例：payType：1）；1：银行划账2：现金支付3：代理商打款4：穗易付5：原套餐缴费方式6：支付宝划扣8：装维上门收取
            } else if ("xjzf".equals(orderViewMap.get("customerId"))) {
                monthlyFeeItems.put("缴费方式", "现金支付");
            } else {
                monthlyFeeItems.put("缴费方式", "原套餐缴费方式");
            }
            expenseItemsList.add(expenseItemsMap);
            monthlyFeeItems.put("费用项列表", expenseItemsList);
            order_data.put("月租费用项", monthlyFeeItems);


            HashMap<Object, Object> OneExpenseItems = new HashMap<>();   //一次性费用项
            List<HashMap<String, Object>> OneExpenseItemsList = new ArrayList<>(); //费用项列表
            List<HashMap<String, Object>> OneSuipayPayment = new ArrayList<>(); //穗易付支付
            HashMap<String, Object> OneExpenseItemsMap = new HashMap<>();
            HashMap<String, Object> OneSuipayPaymentMap = new HashMap<>();
            OneExpenseItemsMap.put("费用项名称", productName);
            OneExpenseItemsMap.put("费用项金额", ORDERAMOUNT + ".0000");
            if (((String) orderViewMap.get("orderSetMeal")).contains("包月")) {
                OneExpenseItemsMap.put("费用项类型", "月租");
            } else if (((String) orderViewMap.get("orderSetMeal")).contains("包年")) {
                OneExpenseItemsMap.put("费用项类型", "年租");
            }
            ORDERAMOUNT = ORDERAMOUNT.replace("元", "");
            if (ORDERAMOUNT.equals("0.01") || ORDERAMOUNT.equals("0.02") || "0".equals(orderViewMap.get("webOrderAmount").toString())) {
                OneExpenseItems.put("缴费方式", "现金支付");  // 缴费方式，必填（例：payType：1）；1：银行划账2：现金支付3：代理商打款4：穗易付5：原套餐缴费方式6：支付宝划扣8：装维上门收取
            } else if ("xjzf".equals(orderViewMap.get("customerId"))) {
                OneExpenseItems.put("缴费方式", "现金支付");
            } else {
                OneExpenseItems.put("缴费方式", "穗易付");
                EasyPay easyPay = new EasyPay();
                easyPay.set穗易付订单号(ORDERREQTRANSEQ);
                String payPlatform = (String) orderViewMap.get("iPay");
                if (StringUtils.isNotBlank(payPlatform)) {
                    if ("1".equals(payPlatform)) {
                        easyPay.set穗易付支付平台("支付宝"); // 支付平台，缴费方式为“穗易付”时必填
                    } else {
                        easyPay.set穗易付支付平台("微信"); // 支付平台，缴费方式为“穗易付”时必填
                    }
                } else {
                    easyPay.set穗易付支付平台("翼支付"); // 支付平台，缴费方式为“穗易付”时必填
                }
                easyPay.set穗易付支付金额(ORDERAMOUNT);
                easyPay.set穗易付支付流水号(UPTRANSEQ);
                OneExpenseItems.put("穗易付支付", easyPay);
            }
            OneExpenseItemsList.add(OneExpenseItemsMap);
            OneExpenseItems.put("费用项列表", OneExpenseItemsList);
            order_data.put("一次性费用项", OneExpenseItems);
        }

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

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


        kong.unirest.HttpResponse<String> responese = null;
        try {
            log.info("提交参数:" + order_dataJSON);
            Constant.trustEveryone();
            responese = Unirest.put("http://132.97.20.20/function/id-generator-snowflake.prod-fn?turbo=1")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("X-Sign", sign)
                    .body(order_dataJSON)
                    .asString();
            if (businessType == 5) {
                log.info("单宽带下单接口，返回信息:" + responese.getBody());
            } else {
                log.info("融合下单接口，返回信息:" + responese.getBody());
            }
        } catch (ResourceAccessException e) {
            count++;
            if (count < 20) {
                responese =
                        getOrderInfo(
                                schoolMap,          //宽带订单对应的学校信息
                                orderViewMap,           //宽带订单信息
                                currentTimeStr,     //当前时间
                                productName,        //产品名称
                                ORDERSEQ,           //kd_order_id 宽带ID
                                UPTRANSEQ,          //支付平台流水号
                                ORDERAMOUNT,        //产品价格
                                ORDERREQTRANSEQ,    //穗易付订单号
                                businessType,       //业务类型
                                count);
            } else {
                if (businessType == 5) {
                    log.info("单宽带下单接口，返回信息:" + responese.getBody());
                } else {
                    log.info("融合下单接口，返回信息:" + responese.getBody());
                }
            }
        } catch (Exception e) {
            if (businessType == 5) {
                log.info("单宽带下单接口异常");
            } else {
                log.info("融合下单接口异常");
            }
            e.printStackTrace();
        }
        return responese;
    }

    private Map<String, Object> 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元");
                    }
                    return schoolMap;
                } 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]);
                    }
                    return schoolMap;
                }
            } else {
                if (ORDERAMOUNT.equals("50元") && orderMap.get("order_set_meal").equals("20M包月")) {
                    schoolMap.put("universityMonthlyRentType", "包月50元");
                }
                return schoolMap;
            }
        } catch (Exception e) {
            log.info(e.toString());
            e.printStackTrace();
        }
        return schoolMap;
    }

    public JSONObject getQueryOrderInfo(String orderNum, int count) throws Exception {
        ObjectMapper OBJECT_MAPPER = new ObjectMapper();

        Map<String, Object> data = new HashMap<>();
        data.put("route", "代理商订单信息查询");
        data.put("代理商账号", "hyoujian");
        data.put("订单编码", orderNum);
        data.put("使用人证件号", "440802199006080830");
        data.put("使用人姓名", "黄友健");
        String bodyJson = JSONObject.toJSONString(data);

        String eurl_data = URLEncoder.encode(bodyJson, "UTF-8");
        String url_data = "data=" + eurl_data;
        // 获得md5串
        String sign = MD5Utils.md5(url_data);
        // 获得小写md5串
        sign = sign.toLowerCase();
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        log.info("签名：" + sign);
        //去除换行
        sign = sign.replaceAll("\\r|\\n", "");
        log.info("签名2  ：" + sign);

        JSONObject jsonObject = null;
        try {
            log.info("提交参数:" + data);
            Constant.trustEveryone();
            kong.unirest.HttpResponse<String> responese = Unirest.get("http://132.97.20.21/query/query-order-info?" + url_data)
                    //kong.unirest.HttpResponse<String> responese = Unirest.get("https://applet.mini189.cn/prod/query/query-order-info?" + url_data)
                    .header("Content-Type", "application/json")
                    .header("X-Sign", sign)
                    .asString();
            log.info("宽带订单状态查询接口，返回信息:" + responese.getBody());
            String body = responese.getBody();
            jsonObject = JSONObject.parseObject(body);
            Map<String, Object> dataJson = (Map<String, Object>) jsonObject.get("data");
            if (StringUtils.isEmpty(JSON.toJSONString(dataJson.get("q")))) {
                count++;
                if (count < 20) {
                    getQueryOrderInfo(orderNum, count);
                } else {
                    log.error("宽带订单状态查询接口尝试20次未查询到订单。请重新下单或检查下单接口");
                }
            }
        } catch (ResourceAccessException s) {
            count++;
            if (count < 20) {
                getQueryOrderInfo(orderNum, count);
            } else {
                log.error("单宽订单状态查询接口尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.error("接口异常   " + e.getMessage());
            e.printStackTrace();
        }
        return jsonObject;
    }

    public Map<String, Object> setSchoolMap(Map<String, Object> orderMap, Map<String, Object> orderViewMap, Map<String, Object> schoolMap) {
        // 根据学校名称，获取该学校信息
        List<Map<String, Object>> hehuoren_id =
                universityInfoMapper.selectProductManager(orderMap.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", orderViewMap.get("orderUniversityName"));
            universityInfoWrapper.eq("university_region", orderViewMap.get("orderRegion"));
            List<Map<String, Object>> findUniversityById = universityInfoMapper.selectMaps(universityInfoWrapper);
            schoolMap = findUniversityById.get(0);
        }
        return schoolMap;
    }


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

        if (orderMap.isEmpty()) {
            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 (orderMap.get("rh_time") == null) {
                log.info("当前订单无融合时间，无法进行下单：" + orderMap.toString());
                return;
            }
            try {
                rhTime = (Date) orderMap.get("rh_time");
            } catch (Exception e) {
                log.error("融合日期转换错误" + orderMap.toString());
                return;
            }
            // 融合时间小于当前时间
            if (today.getTime() > rhTime.getTime()) {
                log.info("融合日期小于当前日期，改为待受理状态" + orderMap.toString());
                Wrapper<Order> wrapper = new EntityWrapper<>();
                wrapper.eq("id", orderMap.get("id"));
                Order updateOrder = new Order();
                updateOrder.setUpdateTime(new Date());
                updateOrder.setOrderStatus("待受理");
                orderMapper.update(updateOrder, wrapper);
                return;
            }
            // 融合时间大于等于 当前时间的第二天的0点
            if (rhTime.getTime() >= calendar.getTime().getTime()) {
                log.info("融合日期超过当前时间，不下单：" + orderMap.toString());
                return;
            }
        }

        String ORDERSEQ = (String) orderMap.get("kdOrderId");
        Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
        orderViewWrapper.eq("orderSeq", orderMap.get("kd_order_id"));
        List<Map<String, Object>> orderViewMaps = orderViewMapper.selectMaps(orderViewWrapper);
        Map<String, Object> orderViewMap = null;
        if (orderViewMaps != null && orderViewMaps.size() > 0) {
            orderViewMap = orderViewMaps.get(0);
        }
        if (orderViewMap == null) {
            log.info("错误记录：" + orderMap.toString());
            log.info("订单号：" + ORDERSEQ + "，在order_view表中无记录，无法进行智能平台下单");
            return;
        }
        // 根据学校名称，获取该学校信息
        Map<String, Object> schoolMap = new HashMap<>();
        schoolMap = setSchoolMap(orderMap, orderViewMap, schoolMap);

        //产品价格
        String ORDERAMOUNT = orderMap.get("webOrderAmount") != null ? orderMap.get("webOrderAmount").toString() : "0";
        //穗易付订单号
        String ORDERREQTRANSEQ = orderMap.get("orderReqtranSeq") != null ? orderMap.get("orderReqtranSeq").toString() : "";
        //支付平台流水号
        String UPTRANSEQ = orderMap.get("uptranseq") != null ? orderMap.get("uptranseq").toString() : "";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTimeStr = simpleDateFormat.format(new Date());

        schoolMap = setPriceIndex(schoolMap, orderViewMap, ORDERAMOUNT);

        kong.unirest.HttpResponse<String> submitOrderJsonObject = null;

        if (orderMap.get("user_type").equals("3")) {
            String productName = "校园融合套餐";
            //	3、提交订单到智能平台
            submitOrderJsonObject = getOrderInfo(
                    schoolMap,          //宽带订单对应的学校信息
                    orderViewMap,           //宽带订单信息
                    currentTimeStr,     //当前时间
                    productName,        //产品名称
                    ORDERSEQ,           //kd_order_id 宽带ID
                    UPTRANSEQ,          //支付平台流水号
                    ORDERAMOUNT,        //产品价格
                    ORDERREQTRANSEQ,    //穗易付订单号
                    3,            //下单类型(3：融合业务；5：单宽业务；10：单宽进融)
                    0);
        } else if (orderMap.get("user_type").equals("10")) {

            String productName = "校园宽带提速";
            orderViewMap.put("dmt_number",orderMap.get("dmt_number"));
            //	3、提交订单到智能平台
            submitOrderJsonObject = getOrderInfo(
                    schoolMap,          //宽带订单对应的学校信息
                    orderViewMap,           //宽带订单信息
                    currentTimeStr,     //当前时间
                    productName,        //产品名称
                    ORDERSEQ,           //kd_order_id 宽带ID
                    UPTRANSEQ,          //支付平台流水号
                    ORDERAMOUNT,        //产品价格
                    ORDERREQTRANSEQ,    //穗易付订单号
                    10,            //下单类型(3：融合业务；5：单宽业务；10：单宽进融)
                    0);
        }
        log.info(
                "----------调用单宽带接口（提交订单至智能平台）并返回参数信息---status:"
                        + submitOrderJsonObject.getStatus()
                        + " msg:"
                        + submitOrderJsonObject.getParsingError()
                        + " orderNum:"
                        + submitOrderJsonObject.getBody());

        if (submitOrderJsonObject.getStatus() != 200) {
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("kd_order_id", orderMap.get("kd_order_id"));
            Order updateOrder = new Order();
            updateOrder.setOrderStatus("待处理");
            updateOrder.setMsg("下单异常");
//                    updateOrder.setCheckFail(submitOrderJsonObject.getParsingError().toString());
            orderMapper.update(updateOrder, orderWrapper);
            return;
        }

        String orderNum = submitOrderJsonObject.getBody();
        JSONObject queryOrderInfo = getQueryOrderInfo(orderNum, 0);
        Map<String, Object> map = JSONObject.parseObject(queryOrderInfo.getString("data"));
        List<Object> list = (List<Object>) map.get("q");
        Map<String, Object> q = (Map<String, Object>) list.get(0);
        Map<String, Object> orderStatus = (Map<String, Object>) q.get("订单当前状态");
        if (orderStatus.containsKey("订单当前状态|状态备注") && "待下单人修改".equals((String) orderStatus.get("订单状态名称"))) {
            String ztStatus = (String) orderStatus.get("订单状态名称");
            Wrapper<Order> wrapper = new EntityWrapper<>();
            wrapper.eq("id", orderMap.get("id"));
            Order updateOrder = new Order();
            updateOrder.setOrderId(orderNum);
            updateOrder.setThStatus(ztStatus);
            updateOrder.setOrderStatus("异常单");
            if (orderStatus.get("订单当前状态|状态备注").toString().contains("停机") || orderStatus.get("订单当前状态|状态备注").toString().contains("欠费")) {
                updateOrder.setMsg("停机/名下欠费");
            } else if (orderStatus.get("订单当前状态|状态备注").toString().contains("黑名单")) {
                updateOrder.setMsg("身份证黑名单");
            }
            orderMapper.update(updateOrder, wrapper);

            OrderHistory orderHistory = new OrderHistory();
            orderHistory.setOrderId(String.valueOf(orderMap.get("id")));
            orderHistory.setCreateDate(new Date());
            orderHistory.setStatus("智能平台下单失败" + orderNum);
            orderHistoryMapper.insert(orderHistory);
        } else {
            //5、更新数据库
            Wrapper<Order> wrapper = new EntityWrapper<>();
            wrapper.eq("id", orderMap.get("id"));
            Order updateOrder = new Order();
            updateOrder.setOrderStatus("审核中");
            updateOrder.setOrderId(orderNum);
            orderMapper.update(updateOrder, wrapper);

            OrderView updateOrderView = new OrderView();
            String state = String.valueOf(orderStatus.get("订单状态ID"));
            updateOrderView.setStatus(QueOrderNum(state));
            updateOrderView.setOrderseqThd(orderNum);
            Wrapper<OrderView> wrapperOrderView = new EntityWrapper<>();
            wrapperOrderView.eq("orderSeq", orderMap.get("kd_order_id").toString());
            orderViewMapper.update(updateOrderView, wrapperOrderView);

            OrderHistory orderHistory = new OrderHistory();
            orderHistory.setOrderId(String.valueOf(orderMap.get("id")));
            orderHistory.setCreateDate(new Date());
            orderHistory.setStatus("智能平台下单成功" + orderNum);
            orderHistoryMapper.insert(orderHistory);
        }
    }


    /**
     * @param orderNum 智能平台订单号
     * @return
     * @throws Exception
     */
    public String queryStatus(String orderNum) throws Exception {
        ObjectMapper OBJECT_MAPPER = new ObjectMapper();

        Map<String, Object> data = new HashMap<>();
        data.put("route", "代理商订单信息查询");
        data.put("代理商账号", "hyoujian");
        data.put("订单编码", orderNum);
        data.put("使用人证件号", "440802199006080830");
        data.put("使用人姓名", "黄友健");
        String bodyJson = JSONObject.toJSONString(data);

        String eurl_data = URLEncoder.encode(bodyJson, "UTF-8");
        String url_data = "data=" + eurl_data;
        // 获得md5串
        String sign = MD5Utils.md5(url_data);
        // 获得小写md5串
        sign = sign.toLowerCase();
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        log.info("签名：" + sign);
        //去除换行
        sign = sign.replaceAll("\\r|\\n", "");
        log.info("签名2  ：" + sign);

        kong.unirest.HttpResponse<String> responese = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
            //签名
            headers.add("X-Sign", sign);
            org.springframework.http.HttpEntity<Object> httpEntity = new org.springframework.http.HttpEntity<>(data, headers);
            RestTemplate restTemplate = new RestTemplate();
            log.info("提交参数:" + data);
            Constant.trustEveryone();
            responese = Unirest.get("http://132.97.20.21/query/query-order-info?" + url_data)
                    //responese = Unirest.get("https://applet.mini189.cn/prod/query/query-order-info?" + url_data)
                    .header("Content-Type", "application/json")
                    .header("X-Sign", sign)
                    .asString();
            log.info("订单状态查询接口，返回信息:" + responese.getBody());
            JSONObject bodyJsonObject = JSONObject.parseObject(responese.getBody());
            Map<String, Object> map = JSONObject.parseObject(bodyJsonObject.getString("data"));
            List<Object> list = (List<Object>) map.get("q");
            Map<String, Object> map2 = (Map<String, Object>) list.get(0);
            //Map<String, Object> orderStatus = (Map<String, Object>) map2.get("订单当前状态");
            if (!map2.isEmpty()) {
                return responese.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

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