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.utils.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.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.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.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.*;

/*
 * @author chengfengluo
 * @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;


    //@Autowired
    //private ZnptSignUtils znptSignUtils;

    /*
     * 单宽下单公共类
     *
     * @param order hhr_order map类型
     */

    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);
            }
            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元";
                System.out.println("------" + productName);
                schoolMap = setPriceIndex(schoolMap, orderMap, ORDERAMOUNT);


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


                //	4、查询智能订单是否存在
                String orderNum = submitOrderJsonObject.getBody();
                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", 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.setMsg(submitOrderJsonObject.getBody());
                    orderMapper.update(updateOrder, orderWrapper);
                }
            } else {
                log.info(
                        "---单宽支付接口推送---"
                                + ORDERSEQ
                                + "---"
                                + UPTRANSEQ
                                + "---"
                                + ORDERAMOUNT
                                + "---"
                                + ORDERREQTRANSEQ);
                log.info("重复订单");
            }
        } catch (Exception e) {
            log.info("单宽下单失败");
            e.printStackTrace();
        }
    }


    /*
     * @param schoolMap
     * @param orderMap
     * @param currentTimeStr
     * @param ORDERSEQ
     * @param UPTRANSEQ
     * @param ORDERAMOUNT
     * @param ORDERREQTRANSEQ
     * @param count
     * @return 新单宽下单接口调用
     * @throws Exception
     */

    private ResponseEntity<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 = "测试";
        }

        //schoolMap.get()


        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("客户证件号码", (String) orderViewMap.get("orderNumber"));
        customerInformation.put("客户证件姓名", (String) orderViewMap.get("customerName"));
        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 == 3) {
            order_data.put("办理类型", "新宽旧移"); //新宽新移 ,新宽旧移,旧宽新移,旧宽旧移
        } else if (businessType == 5) {
            order_data.put("办理类型", "新宽新移"); //新宽新移 ,新宽旧移,旧宽新移,旧宽旧移
        } else if (businessType == 10) {
            order_data.put("办理类型", "旧宽旧移"); //新宽新移 ,新宽旧移,旧宽新移,旧宽旧移
        }
        order_data.put("付费类型", "预付费"); //预付费、后付费、其他  选填


        School school = new School();
        school.setLzgh(landId);
        school = schoolMapper.selectOne(school);
        Map<String, Object> packageInformation = new HashMap<>();   //揽装信息
        packageInformation.put("揽装姓名", school.getLzUser());
        //packageInformation.put("三级机构", "");
        //packageInformation.put("一级机构", "");
        //packageInformation.put("企微号码", "");
        //packageInformation.put("揽装人联系电话", "");
        packageInformation.put("机构ID", addressID);
        //packageInformation.put("四级机构", "");
        //packageInformation.put("二级机构", "");
        packageInformation.put("揽装工号", /*landId*/"44100621");
        //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("付费类型", "预付费");

        // 属性列表
        AttributeList roadbandRate = new AttributeList();
        roadbandRate.setName("宽带速率");
        String setMeal = null;
        if (businessType == 3) {
            setMeal = (String) schoolMap.get("speed");
        } else if (businessType == 5) {
            setMeal = (String) orderViewMap.get("orderSetMeal");
        } else {
            setMeal = (String) schoolMap.get("expenses");
        }
        if (StringUtils.isNotBlank(setMeal)) {
            setMeal = setMeal.replace("包月", "");
            setMeal = setMeal.replace("包年", "");
        }

        if (businessType == 5) {
            if (setMeal.equals("20M")) {
                roadbandRate.setValue("20M下行速率/4M上行速率");
            } else if (setMeal.equals("2M")) {
                roadbandRate.setValue("2M下行速率/512K上行速率");
            } else if (setMeal.equals("50M")) {
                roadbandRate.setValue("50M下行速率/10M上行速率");
            } else {
                roadbandRate.setValue(setMeal);
            }
        } else if (businessType == 3) {
            roadbandRate.setValue(setMeal);
        } else if (businessType == 10) {
            roadbandRate.setName("宽带提速速率");
            roadbandRate.setValue(setMeal);
        }

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

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

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

        AttributeList schoolName = new AttributeList();
        schoolName.setName("学校名称");
        schoolName.setValue((String) orderViewMap.get("orderUniversityName"));

        AttributeList handlingNumber = new AttributeList();
        if (businessType == 3 || businessType == 10) {
            handlingNumber.setName("办理号码");
            handlingNumber.setValue((String) orderViewMap.get("orderPhone"));
        }

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

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

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

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

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

        AttributeList customerPwd = new AttributeList();
        customerPwd.setName("多媒体账号密码");
        customerPwd.setValue((String) orderViewMap.get("orderCustomerPwd"));

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

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

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

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

        AttributeList chargeMode = new AttributeList();
        chargeMode.setName("宽带首月费用类型");
        chargeMode.setValue(universityChargeMode);

        if (handlingNumber.getValue() == null) {
            AttributeList[] attributeList = new AttributeList[]{roadbandRate, AddressID, internetType, userCategory,
                    schoolName, studentID, userType, monthlyRentType, billingAttributes, customerAccount, customerPwd,
                    onlineNumber, oneManTerminal, isFtthHub, exteriorLines, chargeMode};  //属性列表
            orderingProducts.put("属性列表", attributeList);
        } else {
            AttributeList[] attributeList = new AttributeList[]{roadbandRate, AddressID, internetType, userCategory, handlingNumber,
                    schoolName, studentID, userType, monthlyRentType, billingAttributes, customerAccount, customerPwd,
                    onlineNumber, oneManTerminal, isFtthHub, exteriorLines, chargeMode};  //属性列表
            orderingProducts.put("属性列表", attributeList);
        }
        if (businessType == 5) {
            orderingProducts.put("AI编码", "DQ_ADSL_CAMPUS");
        } else {
            orderingProducts.put("AI编码", "4B90FBDD2A1A43EE8A4C963115C52F14");
        }
        order_data.put("订购产品", orderingProducts);

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

        HashMap<String, Object> broadbandInstalledCapacity = new HashMap<>();   //宽带装机
        broadbandInstalledCapacity.put("装机详细地址", address);
        broadbandInstalledCapacity.put("省", "广东省");
        broadbandInstalledCapacity.put("市", "广州市");
        broadbandInstalledCapacity.put("区", addressDistrict);
        broadbandInstalledCapacity.put("装机地址ID", addressID);
        order_data.put("宽带装机", broadbandInstalledCapacity);

        HashMap<Object, Object> monthlyFeeItems = new HashMap<>();   //月租费用项
        List<HashMap<String, Object>> expenseItemsList = new ArrayList<>(); //费用项列表
        HashMap<String, Object> expenseItemsMap = new HashMap<>();
        expenseItemsMap.put("费用项名称", productName);
        expenseItemsMap.put("费用项金额", ORDERAMOUNT + ".0000");
        if (universityMonthlyRentType.contains("包月")) {
            expenseItemsMap.put("费用项类型", "月租");
        } else if (universityMonthlyRentType.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("缴费方式", "穗易付");
            expenseItemsMap.put("穗易付订单号", ORDERREQTRANSEQ);
            String payPlatform = (String) orderViewMap.get("ipay");
            if (StringUtils.isNotBlank(payPlatform)) {
                if ("1".equals(payPlatform)) {
                    expenseItemsMap.put("穗易付支付平台", "支付宝"); // 支付平台，缴费方式为“穗易付”时必填
                } else {
                    expenseItemsMap.put("穗易付支付平台", "微信"); // 支付平台，缴费方式为“穗易付”时必填
                }
            } else {
                expenseItemsMap.put("穗易付支付平台", "穗易付"); // 支付平台，缴费方式为“穗易付”时必填
            }
            expenseItemsMap.put("穗易付支付金额", ORDERAMOUNT);
            expenseItemsMap.put("穗易付支付流水号", UPTRANSEQ);
        }
        expenseItemsList.add(expenseItemsMap);
        monthlyFeeItems.put("费用项列表", expenseItemsList);
        order_data.put("月租费用项", monthlyFeeItems);

        order_data.put("一次性费用项", "");

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

        //String data = "{\"order_data\":{\"代理商账号\":\"代理商账号\",\"使用人姓名\":\"使用人姓名\",\"使用人证件号\":\"使用人证件号\",\"客户信息\":{\"联系人\":\"伍思炜\",\"客户证件号码\":\"44128319990817359X\",\"联系电话\":\"13727264296\",\"客户证件地址\":\"\",\"装机联系电话\":\"13727264296\",\"装机联系人\":\"伍思炜\",\"客户证件类型\":\"身份证\",\"通讯地址\":\"广州市黄埔区九龙镇九龙大道206号206号广州商学院思政楼1楼机房\"},\"装机详细地址\":\"广州市黄埔区九龙镇九龙大道206号206号广州商学院思政楼1楼机房\",\"订单来源单号\":\"r5bso7k9vgasfgs29tf8\",\"订单备注\":\"\",\"付费类型\":\"\",\"揽装信息\":{\"揽装人联系电话\":\"\",\"揽装姓名\":\"\",\"机构ID\":\"441020000000001023017324\",\"四级机构\":\"\",\"三级机构\":\"\",\"二级机构\":\"\",\"揽装工号\":\"06684262\",\"协销工号\":\"\",\"一级机构\":\"\",\"企微号码\":\"\",\"五级机构\":\"\"},\"发票信息\":{\"发票抬头\":\"\",\"发票投递方式\":\"不需要\",\"电子邮箱\":\"\"},\"接口下单账号\":\"xyzx\",\"订购产品\":{\"产品SKU\":\"\",\"产品名称\":\"校园宽带300元\",\"受理内容\":\"\",\"付费类型\":\"\",\"AI编码\":\"DQ_ADSL_CAMPUS\",\"属性列表\":[{\"属性值\":\"4M\",\"属性名\":\"宽带速率\"},{\"属性值\":\"441020000000001023017324\",\"属性名\":\"地址ID\"},{\"属性值\":\"PC+手机\",\"属性名\":\"允许上网终端类型\"},{\"属性值\":\"学生\",\"属性名\":\"用户类别\"},{},{\"属性值\":\"广州康大教育园\",\"属性名\":\"学校名称\"},{\"属性值\":\"1804050432\",\"属性名\":\"学生证号\"},{\"属性值\":\"校园天翼宽带用户\",\"属性名\":\"用户类型\"},{\"属性值\":\"包月30元\",\"属性名\":\"月租类型\"},{\"属性值\":\"普通\",\"属性名\":\"计费属性\"},{\"属性值\":\"13727264296@SCNUZC.GZ\",\"属性名\":\"多媒体账号\"},{\"属性值\":\"a12345678\",\"属性名\":\"多媒体账号密码\"},{\"属性值\":\"1\",\"属性名\":\"最大在线数\"},{\"属性值\":\"否\",\"属性名\":\"一人一号多终端\"},{\"属性值\":\"否\",\"属性名\":\"是否FTTH+HUB\"},{\"属性值\":\"(FTTB)光缆大楼\",\"属性名\":\"外线方式\"},{\"属性值\":\"首月按天收费\",\"属性名\":\"宽带首月费用类型\"}],\"业务类型\":\"单宽业务\",\"宽带装机\":{\"装机详细地址\":\"广州市黄埔区九龙镇九龙大道206号206号广州商学院思政楼1楼机房\",\"省\":\"广东省\",\"市\":\"广州市\",\"区\":\"黄埔区\",\"装机地址ID\":\"441020000000001023017324\"},\"月租费用项\":{\"费用项列表\":[{\"费用项名称\":\"校园宽带300元\",\"费用项金额\":\"300.0000\",\"费用项类型\":\"月租\"}]},\"缴费方式\":\"现金支付\"}}}";
        // 获得md5串
        String sign = MD5Util.MD5Encode(order_dataJSON, "Utf-8");
        // 获得小写md5串
        sign = sign.toLowerCase();
        System.out.println(sign);
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        System.out.println("签名：" + sign);
        //去除换行
        sign = sign.replaceAll("\\r|\\n", "");
        System.out.println("签名2  ：" + sign);
        log.info("宽带下单接口中的携带的签名：" + sign);


        ResponseEntity<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<>(order_dataJSON, headers);
            RestTemplate restTemplate = new RestTemplate();
            log.info("提交参数:" + order_dataJSON);
            Constant.trustEveryone();
            //responese = restTemplate.postForEntity("https://applet.mini189.cn/dev/generate", httpEntity, String.class);
            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 {
                log.error("单宽带(预付费、移动、融合、续约、增值)下单接口异常尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            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;
    }

    private JSONObject getQueryOrderInfo(
            String orderNum, String currentTimeStr, int count) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        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);

        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;
    }

    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 order        hhr_order 表的map数据
     * @param rightNowSend 是否马上下单，是则无视融合时间，不是则判断融合时间是否当天
     */

    public void integrateSendOrder(Order order, boolean rightNowSend) throws Exception {
        Map<String, Object> orderMap = JSONObject.parseObject(JSONObject.toJSONString(order));
        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;
            }
        }

        String ORDERSEQ = (String) orderMap.get("kdOrderId");
        Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
        orderViewWrapper.eq("orderSeq", order.getKdOrderId());
        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("错误记录：" + JSONObject.toJSONString(order));
            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, orderMap, ORDERAMOUNT);

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

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

            String orderNum = (String) body.get("orderNumber");

            JSONObject queryOrderJsonObject = null;

            /*String orderNum = (String) body.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) body.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 orderNum 智能平台订单号
     * @param need      判断查询到的订单状态（1:完成/作废；2：审核中）
     * @return
     * @throws Exception
     */
    public String queryStatus(String orderNum,int need) throws Exception {
        ObjectMapper OBJECT_MAPPER = new ObjectMapper();

        Map<String, Object> body = new HashMap<>();
        body.put("Timestamp", "");
        Map<String, Object> values = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> value = new HashMap<>();
        value.put("route", "代理商订单信息查询");
        value.put("代理商账号", "");
        value.put("订单编码", orderNum);
        value.put("使用人证件号", "");
        value.put("使用人姓名", "");
        data.add(value);
        values.put("data", data);
        body.put("values", values);
        String bodyJson = JSONObject.toJSONString(body);
        //MD5加密
        String sign = MD5Util.MD5Encode(bodyJson, "Utf-8");
        // 获得小写md5串
        sign = sign.toLowerCase();
        log.info("md5签名:" + sign);
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        log.info("RSA签名：" + sign);

        ResponseEntity<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<>(bodyJson, headers);
            RestTemplate restTemplate = new RestTemplate();
            log.info("提交参数:" + bodyJson);
            Constant.trustEveryone();
            responese = restTemplate.postForEntity("http://132.97.20.21/function/applet-query-order-info.dev-fn", httpEntity, String.class);
            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 (need==1 && "0".equals(orderStatus.get("订单状态ID"))) {
                return responese.getBody();
            }else if (need == 2 && StringUtils.isEmpty((String) orderStatus.get("订单状态ID"))){
                return responese.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    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"; // 待受理(未受理、未受理【待跟进】、待疑难支撑审核、待分局审核、待分销商审核)
        }
    }
}
