package com.winsun.TimingTask;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.bean.Order;
import com.winsun.bean.OrderView;
import com.winsun.bean.UniversityInfo;
import com.winsun.constant.Constant;
import com.winsun.mapper.*;
import com.winsun.utils.BeanUtil;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@Configuration
@EnableScheduling
public class RhZhiNenTask {

    @Autowired
    private UniversityInfoMapper universityInfoMapper;
    @Autowired
    private OrderViewMapper orderViewMapper;
    @Autowired
    private OrderMapper orderMapper;


    //@Scheduled(cron = "0 0 0 * * ? ")
    @Scheduled(cron = "0/5 * * * * ? ")
    //@Scheduled(fixedRate=1000*60)
    @PostMapping("/rhZhiNenTask")
    public void general() throws Exception {

        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("order_status","未下单");
        List<Map<String, Object>> orders = orderMapper.selectMaps(wrapper);
        for (Map<String, Object> order  :orders){
            if(StringUtils.isNotBlank(order.get("rhTime").toString())){
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date rhTime=simpleDateFormat1.parse(order.get("rhTime").toString());
                Date date=new Date();
                if(rhTime.getTime() <= date.getTime()){
                    Wrapper<OrderView> wrapperOV = new EntityWrapper<>();
                    wrapperOV.eq("orderSeq",order.get("kdOrderId").toString());
                    Map<String, Object> orderMap = orderViewMapper.selectMaps(wrapperOV).get(0);
                    Wrapper<UniversityInfo> wrapperUI = new EntityWrapper<>();
                    wrapperUI.eq("university_name",(String) orderMap.get("orderUniversityName"));
                    wrapperUI.eq("university_region", (String) orderMap.get("orderRegion"));
                    // 根据学校名称，获取该学校信息
                    List<Map<String, Object>> list1 = universityInfoMapper.selectMaps(wrapperUI);
                    Map<String, Object> schoolMap = list1.get(0);
                    if (orderMap.get("orderUniversityName").toString().equals("广州华立科技职业学院")) {
                        if ("中国电信校园高速宽带".equals(orderMap.get("productName").toString())) {
                            schoolMap.put("universityPackageNumber", "56119011");
                        } else {
                            schoolMap.put("universityPackageNumber", "56119015");
                        }
                    }else if(orderMap.get("orderUniversityName").toString().equals("广州大学华软软件学院")){
                        if ("中国电信校园高速宽带".equals(orderMap.get("productName").toString())) {
                            schoolMap.put("university_package_number", "16001253");
                        } else {
                            schoolMap.put("university_package_number", "16001405");
                        }
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String currentTimeStr = simpleDateFormat.format(new Date());
                    String UPTRANSEQ = "";
                    if(orderMap.get("uptranseq")!=null){
                        UPTRANSEQ =  orderMap.get("uptranseq").toString();
                    }
                    // 穗易付平台，支付流水号
                    String ORDERAMOUNT = "";
                    if(orderMap.get("webOrderAmount").toString().equals("0")){
                        ORDERAMOUNT =  "0元";
                    }else {
                        ORDERAMOUNT =  orderMap.get("webOrderAmount").toString();
                    }
                    String ORDERREQTRANSEQ = "";
                    if(orderMap.get("orderReqtranSeq")!=null){
                        ORDERREQTRANSEQ =  orderMap.get("orderReqtranSeq").toString();    // 穗易付订单号
                    }
                    String productId = "1329";
                    //单宽带
                    String saleId1 = "4907";
                    //提速包
                    String saleId2 = null;
                    if(!orderMap.get("webOrderAmount").toString().equals("0")){
                        JSONObject saleJsonObject = getSaleId(productId, currentTimeStr);
                        if (saleJsonObject.toString().indexOf("list") == -1) {
                            return;
                        }
                        String prices = orderMap.get("webOrderAmount").toString();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 下单产品
                    Map<String, Object> productMap = new HashMap<String, Object>();
// 产品(一个订单只能有一种产品且数量为1)
                    productMap.put("productId", productId);// 产品id,必填，请通过产品列表接口获取

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

                    //单宽带
                    Map<String, Object> paymentListMap2 = new HashMap<String, Object>();
                    paymentListMap2.put("id", saleId1);// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
                    paymentListMap2.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
                    if(orderMap.get("webOrderAmount").toString().equals("0")){
                        paymentListMap2.put("payType", "2");
                    }else {
                        paymentListMap2.put("payType", "4");// 缴费方式，必填（例：payType：3）3：代理商打款4：穗易付7：货到付款
                    }
                    paymentListMap2.put("payAmount", ORDERAMOUNT);// 打款金额（支付金额），若选择代理商打款、者穗易付、货到付款，此项必填

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

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

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

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

                    productMap.put("inpProperties", inPropertyList);


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

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

                    Map<String, Object> propertyMap10 = new HashMap<String, Object>();
                    propertyMap10.put("name", "多媒体账号");
                    propertyMap10.put("value", (String) orderMap.get("orderCustomerAccount"));
                    Map<String, Object> propertyMap11 = new HashMap<String, Object>();
                    propertyMap11.put("name", "多媒体账号密码");
                    propertyMap11.put("value", (String) orderMap.get("orderCustomerPwd"));
                    Map<String, Object> propertyMap12 = new HashMap<String, Object>();
                    propertyMap12.put("name", "学生证号");
                    propertyMap12.put("value", (String) orderMap.get("orderCustomerStudentId"));
                    Map<String, Object> propertyMap13 = new HashMap<String, Object>();
                    propertyMap13.put("name", "宽带首月费用类型");
                    propertyMap13.put("value", universityChargeMode);
                    Map<String, Object> propertyMap14 = new HashMap<String, Object>();
                    propertyMap14.put("name", "最大在线数");
                    propertyMap14.put("value", universityOnlineNumber);
                    Map<String, Object> propertyMap15 = new HashMap<String, Object>();
                    propertyMap15.put("name", "地址ID");
                    propertyMap15.put("value", addressID);

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

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

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

                    for (String key : keys) {
                        value = signMap.get(key);
                        plaintext = plaintext.concat(value);
                    }
                    plaintext = plaintext.concat(Constant.ZHANGSHIKEY);
                    log.info("---------plaintext---------:" + plaintext);
                    qParams.add(new BasicNameValuePair("sign", MD5Utils.md5(plaintext).toUpperCase()));//签名，必填
                    log.info("---------sign---------:" +MD5Utils.md5(plaintext).toUpperCase());
                    net.sf.json.JSONObject resultDataJson = null;
                    try {
                        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
                        httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
                        log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
                        HttpResponse response = httpclient.execute(httpPost);
                        entity = response.getEntity();
                        String httpResult = EntityUtils.toString(entity, "UTF-8");
                        log.info("融合下单接口，返回信息:" + httpResult);
                        resultDataJson = net.sf.json.JSONObject.fromObject(httpResult);
                    } catch (Exception e) {
                        System.out.println("融合下单接口接口异常");
                        e.printStackTrace();
                    } finally {
                        httpPost.releaseConnection();
                    }
                    net.sf.json.JSONObject queryOrderJsonObject = null;
                    String orderNum = (String) resultDataJson.get("orderNumber");
                    if(orderMap.get("webOrderAmount").toString().equals("0")){
                        if (StringUtils.isNotBlank(orderNum)) {
                            queryOrderJsonObject = getQueryOrderInfo(orderNum, currentTimeStr);
                            log.info("----------调用查询智能订单接口并返回参数信息:" + queryOrderJsonObject);
                            /*	5、插入数据到数据库   */
                            String state = queryOrderJsonObject.getString("state");
                            String order_id = queryOrderJsonObject.getString("bizEntity");
                            String th_status = queryOrderJsonObject.getString("stateName");
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("th_status",th_status);
                            hashMap.put("order_id",order_id);
                            hashMap.put("order_status","待审核");
                            Wrapper<Order> wrapperO = new EntityWrapper<>();
                            wrapperO.eq("kd_order_id",orderMap.get("orderSeq").toString());
                            orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(hashMap),wrapperO);
                            if (StringUtils.isNotBlank(state)) {
                                HashMap<String, Object> hashMap1 = new HashMap<>();
                                hashMap1.put("status",QueOrderNum(state));
                                hashMap1.put("orderSeqTHD",orderNum);
                                orderViewMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(hashMap1),wrapperOV);
                                return ;    // 成功
                            } else {
                                log.info("----------将智能订单状态更新至数据库error：" + state);
                            }
                        }
                    }else {
                        if (StringUtils.isNotBlank(orderNum)) {
                            queryOrderJsonObject = getQueryOrderInfo(orderNum, currentTimeStr);
                            log.info("----------调用查询智能订单接口并返回参数信息:" + queryOrderJsonObject);
                            /*	5、更新数据库   */
                            String state = queryOrderJsonObject.getString("state");
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("order_id",orderNum);
                            hashMap.put("order_status","待审核");
                            Wrapper<Order> wrapperO = new EntityWrapper<>();
                            wrapperO.eq("kd_order_id",orderMap.get("orderSeq").toString());
                            orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(hashMap),wrapperO);
                            if (StringUtils.isNotBlank(state)) {
                                HashMap<String, Object> hashMap1 = new HashMap<>();
                                hashMap1.put("status",QueOrderNum(state));
                                hashMap1.put("orderSeqTHD",orderNum);
                                orderViewMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(hashMap1),wrapperOV);
                                log.info("----------将智能订单状态更新至数据库success：" + state);
                            } else {
                                log.info("----------将智能订单状态更新至数据库error：" + state);
                            }
                        }
                    }


                }

    }
        }
        }

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

    }

    private net.sf.json.JSONObject getQueryOrderInfo(String orderNum, String currentTimeStr) 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",MD5Utils.md5(plaintext).toUpperCase()));//签名，必填
        net.sf.json.JSONObject resultDataJson = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            System.out.println("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            resultDataJson = net.sf.json.JSONObject.fromObject(httpResult);
        } catch (Exception e) {
            System.out.println("接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }

    private static JSONObject getSaleId(String productId, String currentTimeStr) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>();//待签名参数
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();

        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "query.action");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpPost.setConfig(requestConfig);
        qParams.add(new BasicNameValuePair("service", "sale.query"));//api标识，必填
        signMap.put("service", "sale.query");
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON));//用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        qParams.add(new BasicNameValuePair("timeStamp", currentTimeStr));
        signMap.put("timeStamp", currentTimeStr);
        if (StringUtils.isNotBlank(productId)) {
            qParams.add(new BasicNameValuePair("productId", productId));//产品ID
            signMap.put("productId", productId);
        }
        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());
        Collections.sort(keys);//key按字符串升序
        String value, plaintext = "";
        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }
        plaintext = plaintext.concat(Constant.ZHANGSHIKEY);
        String sign = MD5Utils.md5(plaintext).toUpperCase();//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填
        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"));
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            log.info("返回信息:" + httpResult);
            resultDataJson = JSONObject.parseObject(httpResult);
        } catch (Exception e) {
            log.info("---接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }


}
