package com.winsun.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.*;
import com.winsun.constant.Constant;
import com.winsun.constant.OrderStatus;
import com.winsun.mapper.*;
import com.winsun.utils.BeanUtil;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.ProduceIdUtil;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 单宽办理接口
 *
 * @Author xuede
 * @Date 2020/3/9 16:52
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/rongHe")
public class RongHeController {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private HhrUserMapper hhrUserMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Autowired
    private AppMapper appMapper;
    @Autowired
    private UniversityInfoMapper universityInfoMapper;
    @Autowired
    private OrderViewMapper orderViewMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderHistoryMapper historyMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 跟据合伙人id查找融合套餐信息
     *
     * @param hhrId
     * @return
     */
    @RequestMapping("/rhData")
    public ResponseData<Map<String, Object>> getRhData(@RequestParam("hhrId") String hhrId, @RequestParam("phone") String phone) {
        //空，直接返回
        if (StringUtils.isEmpty(hhrId)) {
            return ResponseData.error("请输入合伙人id");
        }
        UserSchool userSchool = userSchoolMapper.selectById(hhrId);
        School school = schoolMapper.selectById(userSchool.getSchoolId());

        String bandproductId = school.getBandproductId();
        if (StringUtils.isBlank(bandproductId)) {
            return ResponseData.error("敬请期待");
        }
        Product product = productMapper.selectById(bandproductId);
        UniversityInfo universityInfo = universityInfoMapper.selectById(product.getUniversityId());

        Map<String, Object> objMap = new HashMap<>();
        objMap.put("product", product);
        objMap.put("universityInfo", universityInfo);

        return ResponseData.success(objMap);
    }

    /**
     * 支付平台异步更新后台地址，主要对订单进去保存和提交订单到智能平台上
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/createRongHeOrder")
    public ResponseData<Object> createRongHeOrder(
            @RequestParam("orderName") String orderName, @RequestParam("orderPhone") String orderPhone,
            @RequestParam("orderNumber") String orderNumber, @RequestParam("orderCustomerStudentId") String orderCustomerStudentId,
            @RequestParam("orderCustomerAccount") String orderCustomerAccount, @RequestParam("orderCustomerPwd") String orderCustomerPwd,
            @RequestParam("orderSetMeal") String orderSetMeal, @RequestParam("productId") String productId,
            @RequestParam("webOrderAmount") String webOrderAmount, @RequestParam("partner") String partner,
            @RequestParam("banLiPhone") String banLiPhone, @RequestParam("rhTime") String rhTime) throws Exception {

        Wrapper<OrderView> orderViewWrapper = new EntityWrapper<>();
        orderViewWrapper.eq(StringUtils.isNotBlank(orderNumber), "orderNumber", orderNumber);
        orderViewWrapper.ne("status", OrderStatus.INVALID.getId());
        List<OrderView> orderViews = orderViewMapper.selectList(orderViewWrapper);

        OrderView orderV = new OrderView();
        if (orderViews.size() != 0) {
            if (StringUtils.isNotBlank(orderViews.get(0).getUptranseq())) {
                Wrapper<Order> wrapperO = new EntityWrapper<>();
                wrapperO.eq("order_number", orderViews.get(0).getOrderSeq());
                wrapperO.eq("user_type", "5");
                List<Order> orders = orderMapper.selectList(wrapperO);
                if (orders.size() == 0) {
                    return ResponseData.error("当前身份证号订单异常，请联系客服！");
                }
                orderV.setOrderSeq(orders.get(0).getId());
                orderV.setUptranseq(orderViews.get(0).getUptranseq());
                return ResponseData.error(orderV, "当前身份证号订单已存在并完成支付！");
            }
            if ("0".equals(orderViews.get(0).getWebOrderAmount())) {
                Wrapper<Order> wrapperO = new EntityWrapper<>();
                wrapperO.eq("order_number", orderViews.get(0).getOrderSeq());
                wrapperO.eq("user_type", "5");
                List<Order> orders = orderMapper.selectList(wrapperO);
                if (orders.size() == 0) {
                    return ResponseData.error("当前身份证号订单异常，请联系客服！");
                }
                orderV.setOrderSeq(orders.get(0).getId());
                orderV.setUptranseq(orderViews.get(0).getOrderId().toString());
                return ResponseData.error(orderV, "当前身份证号订单已存在！");
            }
            orderV.setOrderId(orderViews.get(0).getOrderId());
            orderV.setOrderSeq(orderViews.get(0).getOrderSeq());
            return ResponseData.error(orderV, "当前身份证号已有订单存在！");
        }
        String orderSeq = "YRYM" + ProduceIdUtil.getId();
        Product product = productMapper.selectById(productId);
        OrderView orderView = new OrderView();
        orderView.setOrderSeq(orderSeq); // 订单号码
        orderView.setOrderName(orderName); // 姓名
        orderView.setOrderPhone(orderPhone); // 联系电话
        orderView.setOrderNumber(orderNumber); // 身份证号码
        orderView.setOrderCustomerStudentId(orderCustomerStudentId);// 学生证号
        orderView.setOrderCustomerAccount(orderCustomerAccount);// 多媒体账号
        orderView.setOrderCustomerPwd(orderCustomerPwd);// 多媒体密码
        orderView.setOrderSetMeal(orderSetMeal);// 套餐
        orderView.setProductName(product.getProductTitle());// 产品名称
        orderView.setOrderDate(new Date());      // 提交时间
        orderView.setOrderUniversityName(product.getProductUniversity()); // 学校
        orderView.setStatus(OrderStatus.NOTPAID.getId());
        orderView.setOrderRegion(product.getProductRegion()); // 区域
        orderView.setPayType("1");   // 支付方式
        orderView.setOrderRf2(rhTime);
        orderView.setWebOrderAmount(webOrderAmount);  // 产品价格
        if (webOrderAmount.equals("0")) {
            orderView.setIPay("0"); // 支付平台
        } else {
            orderView.setIPay("1"); // 支付平台
        }
        orderView.setCustomerId("xyzxyql");   // 接入商
        orderView.setOrderCustomerType("学生"); // 用户类别
        if (webOrderAmount.equals("0")) {
            ResponseData<Object> res = createOrder(productId, orderView, partner, rhTime);
            if (!res.isSuccess()) {
                return res;
            }
            Order order =(Order) res.getData();
            orderV.setOrderRf2(order.getId());
        }
        Integer insert = orderViewMapper.insert(orderView);
        if (insert == 1) {
            orderV.setOrderId(orderView.getOrderId());
            orderV.setOrderSeq(orderSeq);
            orderV.setWebOrderAmount(webOrderAmount);
            return ResponseData.success(orderV, "订单提交完成！");
        }
        return ResponseData.error("提交失败！");
    }

    public ResponseData<Object> createOrder(String productId, OrderView orderView, String userId, String rhTime) throws Exception {
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        Order order = new Order();
        order.setId(id);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat1.parse(rhTime);
        order.setRhTime(parse);
        order.setOrderNumber(orderView.getOrderSeq());
        order.setOrderStatus(OrderStatus.NOTPAID.getName());
        order.setHehuorenId(userId);
        order.setCustomerName(orderView.getOrderName());
        order.setContactNumber(orderView.getOrderPhone());
        order.setIdCard(orderView.getOrderNumber());
        order.setCreateTime(new Date());
        order.setUserType("5");
        order.setNetNumber(orderView.getOrderCustomerAccount());
        order.setNetPassword(orderView.getOrderCustomerPwd());
        order.setUserSchool(orderView.getOrderUniversityName());
        order.setExpenses(orderView.getOrderSetMeal());
        order.setKdOrderId(orderView.getOrderSeq());
        SysUser sysUser = sysUserMapper.selectById(userId);
        order.setHehuorenPhone(sysUser.getPhone());
        String schoolId = appMapper.selectSchoolId(userId);
        School school = schoolMapper.selectById(schoolId);
        order.setHehuorenSchool(school.getSchoolName());
        order.setHehuorenName(sysUser.getName());
        order.setHehuorenArea(sysUser.getSubstName());
       /* List<String> userId1 = appMapper.selectsupervisorBySchool(schoolId);
        SysUser user = sysUserMapper.selectById(userId1.get(0));
        order.setSupervisorName(user.getName());
        order.setLzgh(school.getLzgh());*/
        // 根据订单号，获取该订单信息
        // 根据学校名称，获取该学校信息
        Product product = productMapper.selectById(productId);
        Wrapper<UniversityInfo> uiWrapper = new EntityWrapper<>();
        uiWrapper.eq("university_id", product.getUniversityId());
        List<Map<String, Object>> list1 = universityInfoMapper.selectMaps(uiWrapper);
        order.setOrderStatus("未下单");
        orderMapper.insert(order);
        appMapper.inserOrderHis(id, "待下单！", new Date(), orderView.getOrderName());
        return ResponseData.success(order, "订单创建成功");
    }

    @RequestMapping(value = "toSubmisOrderPreser", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=UTF-8")
    public void toSubmisOrderPreser(HttpServletRequest request) throws Exception {
        String orderseq = request.getParameter("ORDERSEQ");//orderseq
        String uptranseq = request.getParameter("UPTRANSEQ");    // 穗易付平台，支付流水号uptranseq
        String orderamount = request.getParameter("ORDERAMOUNT");//orderamount  价格
        String orderreqtranseq = request.getParameter("ORDERREQTRANSEQ");    // 穗易付订单号 orderreqtranseq
        /*String	orderseq = "4iz818f1u74kznypf3w81";
        String uptranseq = "2019082922001464810523969803";	// 穗易付平台，支付流水号
        String orderamount = "30";
        String orderreqtranseq = "GZCTPAY20190829384046979";	// 穗易付订单号*/
        log.info("----------异步请求接受参数订单号：" + orderseq);
        log.info("----------异步请求接受参数支付流水号：" + uptranseq);
        log.info("----------异步请求接受参数订单金额：" + orderamount);
        log.info("----------异步请求接受参数穗易付订单号：" + orderreqtranseq);

        Wrapper<OrderView> wrapper = new EntityWrapper<>();
        wrapper.eq("orderSeq", orderseq);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("orderReqtranSeq", orderreqtranseq);
        dataMapping.put("uptranseq", uptranseq);
        dataMapping.put("order_payment_time", new Date());
        dataMapping.put("status", "已支付");
        orderViewMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        Wrapper<Order> objectEntityWrapper = new EntityWrapper<>();
        objectEntityWrapper.eq("order_number", orderseq);
        Map<String, Object> dataMapping2 = new HashMap<>();
        dataMapping2.put("order_status", "未下单");
        orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping2), objectEntityWrapper);
        List<Order> orders = orderMapper.selectList(objectEntityWrapper);
        appMapper.inserOrderHis(orders.get(0).getId(), "支付完成,未下单！", new Date(), orders.get(0).getCustomerName());
    }


    @RequestMapping(value = "orderPay", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String toPaymentPlatformPage(@RequestParam("orderId") String orderId, @RequestParam("ipay") String ipay,
                                        @RequestParam("userId") String userId, HttpServletRequest request,
                                        HttpServletResponse response, @RequestParam("rhTime") String rhTime) throws Exception {
        JsoupMethodZhifu(orderId, ipay, userId, request, response, rhTime);
        return null;
    }

    @RequestMapping("/selectUniversity")
    public ResponseData<UniversityInfo> selectUniversity(@RequestParam("universityId") String universityId) {
        UniversityInfo universityInfo = universityInfoMapper.selectById(universityId);

        return ResponseData.success(universityInfo);
    }

    /**
     * @author ljh
     * @Description:支付请求
     */
    public void JsoupMethodZhifu(String orderId, String ipay, String userId,
                                 HttpServletRequest request, HttpServletResponse response, String rhTime) throws Exception {
        log.info("----------首先发送支付请求接口----------");
        //查询订单信息
        OrderView orderView = orderViewMapper.selectById(orderId);
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        //修改支付方式
        Wrapper<OrderView> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("ipay", ipay);

        Map<String, String> map = new HashMap<String, String>();
        //给MAP数组添加数据
        map.put("CLIENTNUMBER", Constant.CLIENTNUMBER);//商户标识，由穗易付平台统一分配
        map.put("ORDERSEQ", orderView.getOrderSeq());//订单号
        log.info("----------宽带价格prices：" + orderView.getWebOrderAmount());
        if (Constant.PRODUCTSKU479Str.indexOf(orderView.getWebOrderAmount()) != -1) {
            map.put("PRODUCTSKU", Constant.PRODUCTSKU479);//商户产品
        } else {
            map.put("PRODUCTSKU", Constant.PRODUCTSKU481);
        }
        Date orderdate = orderView.getOrderDate();
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        map.put("ORDERDATE", ft.format(orderdate));
        map.put("ORDERAMOUNT", orderView.getWebOrderAmount());//价格
        map.put("ORDERNAME", orderView.getOrderName());//用户名
        map.put("ORDERPHONE", orderView.getOrderPhone());//支付宝账号（电话）
        map.put("ORDERNUMBER", orderView.getOrderNumber());//身份证


        if (Constant.Payment1.equals(ipay)) {
            //支付成功回调的页面
           /* String MERCHANTURL = Constant.TOMCATURL + "/dankuan/toSubmisOrderPreser?id=" + userId +"orderId="+id;*/
          /*  String MERCHANTURL =  "http://167460x6b0.51mypc.cn/ciop/rongHe/toSubmisOrderPreser?id=" + userId +"orderId="+id;*/
            String MERCHANTURL = "http://hhrcode.winsun-aly.com/#/hhr/dkSuccessful?id="+userId+"&"+"orderId="+id;
            map.put("MERCHANTURL", MERCHANTURL);
        }
        //单宽回调后端接口地址
        //  map.put("BACKDROPURL", Constant.TOMCATURL + "/dankuan/toSubmisOrderPreser");
        map.put("BACKDROPURL", "http://hhrcode.winsun-aly.com/ciop/rongHe/toSubmisOrderPreser.do");

        String str = "ORDERSEQ=" + orderView.getOrderSeq() + "&ORDERDATE=" + ft.format(orderdate) + "&ORDERAMOUNT=" + orderView.getWebOrderAmount() + "&KEY=" + Constant.APPK;//商户标识
        //*	将值转换为大写	*//*
        map.put("MAC", MD5Utils.md5(str).toUpperCase());
        int PAYTYPE = 1;        // 支付类型
        int IPAY = 1;    // 支付平台
        log.info("----------支付渠道（0翼支付网厅，1支付宝，3微信）：" + ipay);
        if (Constant.Payment3.equals(ipay)) {
            PAYTYPE = 5;
            IPAY = 3;
        }
        map.put("PAYTYPE", String.valueOf(PAYTYPE));
        map.put("IPAY", String.valueOf(IPAY));
        log.info("----------支付请求参数：" + map);
        //定义Document对象
        Document doc = null;
        String result = "";
        String qrcode = "";
        //Jsoup用post提交,超时6秒钟，
        doc = Jsoup.connect("https://gzdxpay.mini189.cn/web/order-pay.action").data(map).timeout(20000).ignoreContentType(true).post();
        //获取回调信息
        String i = doc.text().trim();
        log.info(i);
        //解析json格式
        JSONObject json = JSONObject.parseObject(i);
        //获取jsonp格式中的result（短链接，返回到前端）
        log.info("----------调用穗易付接口返回的结果：" + json);
        result = (String) json.get("result");
        qrcode = (String) json.get("qrcode");
        String ORDERSEQ = (String) json.get("ORDERSEQ");
        String msg = (String) json.get("msg");
        if (StringUtils.isNotBlank(msg) && msg.equals("success")) {
            dataMapping.put("status", "未支付");
            orderViewMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
            Order order = new Order();
            order.setId(id);
            order.setOrderNumber(orderView.getOrderSeq());
            order.setHehuorenId(userId);
            order.setCustomerName(orderView.getOrderName());
            order.setContactNumber(orderView.getOrderPhone());
            order.setIdCard(orderView.getOrderNumber());
            order.setCreateTime(new Date());
            order.setUserType("5");
            order.setNetNumber(orderView.getOrderCustomerAccount());
            order.setNetPassword(orderView.getOrderCustomerPwd());
            order.setUserSchool(orderView.getOrderUniversityName());
            order.setExpenses(orderView.getOrderSetMeal());
            order.setKdOrderId(orderView.getOrderSeq());
            SysUser sysUser = sysUserMapper.selectById(userId);
            order.setHehuorenPhone(sysUser.getPhone());
            String schoolId = appMapper.selectSchoolId(userId);
            School school = schoolMapper.selectById(schoolId);
            order.setHehuorenSchool(school.getSchoolName());
            order.setHehuorenName(sysUser.getName());
            order.setHehuorenArea(sysUser.getSubstName());
            List<String> userId1 = appMapper.selectsupervisorBySchool(schoolId);
            SysUser user = sysUserMapper.selectById(userId1.get(0));
            order.setSupervisorName(user.getName());
            order.setLzgh(school.getLzgh());
            order.setOrderStatus("未下单");
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = simpleDateFormat1.parse(rhTime);
            order.setRhTime(parse);
            orderMapper.insert(order);
            appMapper.inserOrderHis(id, "支付请求提交！", new Date(), orderView.getOrderName());
            response.sendRedirect(result);
        }
    }

    /**
     * @author ljh
     * @Description:获取产品ID
     * @method:getProductId
     * @return: JSONObject
     * @date 2018年6月5日上午10:21:19
     * @version 1.0
     * @exception:
     */
    private static JSONObject getProductId(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", "product.broadband.query"));//api标识，必填
        signMap.put("service", "product.broadband.query");
        qParams.add(new BasicNameValuePair("userName", Constant.ZHENGSHIAUCCON));//用户名，必填
        signMap.put("userName", Constant.ZHENGSHIAUCCON);
        qParams.add(new BasicNameValuePair("timeStamp", currentTimeStr));//时间戳（YYYYMMDDHHMMSS） ，必填
        signMap.put("timeStamp", currentTimeStr);
        qParams.add(new BasicNameValuePair("business", "单宽带"));//产品类型，必填
        signMap.put("business", "单宽带");
        List<String> keys = new ArrayList<String>();
        keys.addAll(signMap.keySet());
        Collections.sort(keys);//key按字符串升序
        String value, plaintext = "";
        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }
        plaintext = plaintext.concat(Constant.ZHANGSHIKEY);
        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");
            resultDataJson = JSONObject.parseObject(httpResult);
        } catch (Exception e) {
            log.info("查询单宽带(预付费、移动、融合、续约、增值)产品接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }

    /**
     * @author ljh
     * @Description:获取销售品ID
     * @method:getSaleId
     * @return: JSONObject
     * @date 2018年6月5日上午10:23:42
     * @version 1.0
     * @exception:
     */
    /**
     * 单宽支付平台异步更新后台地址，主要对订单进去保存和提交订单到智能平台上
     */
    @RequestMapping(value = "getSaleId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=UTF-8")
    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(500000)
                .setConnectTimeout(500000).setConnectionRequestTimeout(500000).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;
    }

    /**
     * @author ljh
     * @Description:提交融合
     * @method:getOrderInfo
     * @return: JSONObject
     * @date 2018年6月5日上午10:41:21
     * @version 1.0
     * @exception:
     */
    private static JSONObject getOrderInfo(Map<String, Object> schoolMap, OrderView orderView, String currentTimeStr, String productId, String saleId1, String saleId2, String ORDERSEQ, String UPTRANSEQ, String ORDERAMOUNT, String ORDERREQTRANSEQ) throws Exception {
        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", "新宽旧移");
        /*  */
        qParams.add(new BasicNameValuePair("ctNumber", orderView.getOrderPhone()));// 电信号码，办理类型，若选择[新宽旧移]或[旧宽旧移]，此项必填
        signMap.put("ctNumber", orderView.getOrderPhone());
        /*  */
        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("university_charge_mode");
        } 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", orderView.getOrderName()));// 客户姓名，必填
        signMap.put("customerName", orderView.getOrderName());

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

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

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

        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", ORDERSEQ));//外部订单编号，选填!；
        //通过API接口下单，必须传入一个外部接入商的订单编号,该编号与智能营销系统编号一一对应
        signMap.put("orderOutNum", ORDERSEQ);

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

        qParams.add(new BasicNameValuePair("orderSourceNum", ORDERSEQ));// 订单来源单号，选填；与订单来源对应，用于业务上记录订单的来源订单编号
        signMap.put("orderSourceNum", 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", orderView.getOrderName()));// 联系人，必填
        signMap.put("deliveryContact", orderView.getOrderNumber());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        String payPlatform = orderView.getIPay();
        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", "主卡号码");
        inPropertyListMap.put("value", orderView.getOrderPhone());
        inPropertyList.add(inPropertyListMap);

        productMap.put("inpProperties", inPropertyList);

        Map<String, Object> propertyMap = new HashMap<String, Object>();
        propertyMap.put("name", "宽带速率");
        String setMeal = orderView.getOrderSetMeal();
        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", orderView.getOrderUniversityName());
        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", orderView.getOrderCustomerAccount());
        Map<String, Object> propertyMap11 = new HashMap<String, Object>();
        propertyMap11.put("name", "多媒体账号密码");
        propertyMap11.put("value", orderView.getOrderCustomerPwd());
        Map<String, Object> propertyMap12 = new HashMap<String, Object>();
        propertyMap12.put("name", "学生证号");
        propertyMap12.put("value", orderView.getOrderCustomerStudentId());
        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 = JSONObject.toJSONString(productList);
        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);
        String sign = MD5Utils.md5(plaintext).toUpperCase();//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填
        log.info("---------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.error("融合下单接口接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }


}
