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.OrderStatus;
import com.winsun.mapper.*;
import com.winsun.smsUtils.StringUtil;
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.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.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
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;

    @Resource
    private RedisTemplate<String, String>  redisTemplate;

    @Resource
    private RedisLockUtil redisLockUtil;

    /**
     * 跟据合伙人id查找融合套餐信息
     *
     * @param hhrId
     * @return
     */

    @RequestMapping(value = "/rhData",method = {RequestMethod.GET, RequestMethod.POST})
    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);
    }
    /**
     * 宽带下单获取产品信息
     *
     */
    @RequestMapping(value = "/selectProductManage",method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Object> selectProductManage(@RequestParam("id") String id){
        Map<String,Object> map = productMapper.queryProductById(id).get(0);
        if(map.size()>0){
            map.put("id",id);
            return ResponseData.success(map);
        }
        return ResponseData.error("查询数据出错！");
    }

    /**
     * 获取支付状态
     * @param orderSeq
     * @return
     */
    @PostMapping("/payStatus")
    public ResponseData<String> getPayStatus(@RequestParam("orderSeq") String orderSeq) {
        Wrapper<OrderView> wrapper = new EntityWrapper<>();
        wrapper.eq("orderSeq", orderSeq);
        List<OrderView> orderViews = orderViewMapper.selectList(wrapper);

        if (orderViews == null || orderViews.size() == 0) {
            return ResponseData.error("未找到当前订单");
        }

        if (orderViews.size() == 2) {
            return ResponseData.error("重复订单");
        }

        if(StringUtils.isNotBlank(orderViews.get(0).getUptranseq())) {
            return ResponseData.success("支付成功");
        }

        return ResponseData.error("");
    }
    /**
     * 支付平台异步更新后台地址，主要对订单进去保存和提交订单到智能平台上
     *
     * @return
     */
    @PostMapping("/createRongHeOrder")
    public ResponseData<Object> createRongHeOrder(HttpServletRequest request,HttpServletRequest response){
        String orderName = request.getParameter("orderName");
        String orderPhone = request.getParameter("orderPhone");
        String banLiPhone = request.getParameter("banLiPhone");
        String orderNumber = request.getParameter("orderNumber");
        String orderCustomerStudentId = request.getParameter("orderCustomerStudentId");
        String orderCustomerAccount = request.getParameter("orderCustomerAccountInfo");
        String orderCustomerPwd = request.getParameter("orderCustomerPwd");
        String orderSetMeal = request.getParameter("orderSetMeal");
        String productId = request.getParameter("productId");
        String webOrderAmount = request.getParameter("webOrderAmount");
        String partner = request.getParameter("partner");
        String rhTime = request.getParameter("rhTime");
        String setMealIndex = request.getParameter("setMealIndex");
        String sell = request.getParameter("sell");
        String campus = request.getParameter("campus");

        if(sell != null && StringUtils.isNumeric(sell)){

        }else {
            sell = "";
        }
        String imgUrl = request.getParameter("imgUrl");
        String filePath = "";
        String orderSeq = RandomUtil.RandomNumber(20);
        // 生成随机字符串

        try{
            String uuid = UUID.randomUUID().toString();
            boolean boo1 = redisLockUtil.redisLock(orderNumber,uuid,10);
            boolean boo2 = redisLockUtil.redisLock(orderCustomerAccount,uuid,10);
            if(!boo1 || !boo2){
                return ResponseData.error("重复下单！");
            }

            if(StringUtils.isBlank(imgUrl)){
                return ResponseData.error("签名失败！");
            }
            if(StringUtils.isNotBlank(imgUrl)){
                filePath  = PicturesUtil.uploadPictures(imgUrl, orderSeq,"signImg");
            }
            OrderView orderV = new OrderView();
            String mealStr = null;
            String byStr = null;
            String prices = null;
            Integer index = 0;
            Product product = productMapper.selectById(productId);
            UniversityInfo universityInfo = universityInfoMapper.selectById(product.getUniversityId());
            String[] rateArry = product.getProductRhRate().split(",");    // 年月（包年,包月）
            String[] mealArry = product.getProductMeal().split(",");  // 套餐 （4M，8M，20M等）
            String[] priceArry = product.getProductRhPrice().split(",");    // 金额（300,30）
            String expenses = universityInfo.getExpenses();

            OrderView orderView = new OrderView();
            orderView.setOrderSeq(orderSeq); // 订单号码
            orderView.setOrderName(orderName); // 姓名
            orderView.setOrderPhone(orderPhone); // 联系电话
            orderView.setOrderNumber(orderNumber); // 身份证号码
            orderView.setOrderCustomerRemarks(banLiPhone);
            orderView.setOrderCustomerStudentId(orderCustomerStudentId);// 学生证号
            orderView.setOrderCustomerAccount(orderCustomerAccount);// 多媒体账号
            orderView.setOrderCustomerPwd(orderCustomerPwd);// 多媒体密码
            orderView.setOrderSetMeal(orderSetMeal);// 套餐

            /**
             * 广美用来判断校区
             */
            if (StringUtils.isNotBlank(productId) && "84".equals(productId)){
                if (StringUtils.isNotBlank(campus) && "1".equals(campus)){
                    orderView.setOrderRegion("海珠区");
                }
            }

            if ("".equals(setMealIndex) && !setMealIndex.matches("[0-9]*")) {
                if (orderSetMeal.indexOf("包年") != -1) {
                    mealStr = orderSetMeal.replace("包年", "");
                    byStr = "包年";
                } else {
                    mealStr = orderSetMeal.replace("包月", "");
                    byStr = "包月";
                }
                for (int i = 0; i < priceArry.length; i++) {
                    if (byStr.equals(rateArry[i]) && mealStr.equals(mealArry[i])) {
                        prices = priceArry[i] + "元";
                        break;
                    }
                }
            }else {
                index = Integer.parseInt(setMealIndex);
//                mealStr = mealArry[index];
                byStr = rateArry[index];
                prices = priceArry[index] + "元";
            }

            if(StringUtils.isBlank(expenses)){
                expenses = "";
            }
            orderView.setExpenses(expenses+byStr);
            orderView.setProductName(product.getProductTitle());// 产品名称
            orderView.setOrderDate(new Date());      // 提交时间
            orderView.setOrderUniversityName(product.getProductUniversity()); // 学校
            orderView.setStatus(OrderStatus.NOTPAID.getId());
            orderView.setHehuorenId(partner);
            orderView.setOrderRegion(product.getProductRegion()); // 区域
            orderView.setPayType("1");   // 支付方式
            orderView.setOrderRf2(rhTime);
            orderView.setWebOrderAmount(webOrderAmount);  // 产品价格
            //	支付平台：0翼支付网厅|1支付宝|3微信
            if (webOrderAmount.equals("0")) {
                orderView.setIPay("0"); // 支付平台
            } else {
                orderView.setIPay("1"); // 支付平台
            }
            if(product.getProductIntroductionPic4().equals("1")){
                // 现金支付
                orderView.setCustomerId("xjzf");   // 接入商
            }else {
                orderView.setCustomerId("xyzxyql");   // 接入商
            }

            if (StringUtils.isBlank((String) orderCustomerStudentId)) {
                orderView.setOrderCustomerType("老师");    // 用户类别
            } else {
                orderView.setOrderCustomerType("学生");   // 用户类别
            }


            ResponseData<Object> res = null;
            if (webOrderAmount.equals("0") || product.getProductIntroductionPic4().equals("1")) {
                res = createOrder(productId, orderView, partner, rhTime,filePath,"未下单",sell);
                Order order =(Order) res.getData();
                orderV.setOrderRf2(order.getKdOrderId());
            }else {
                res = createOrder(productId, orderView, partner, rhTime,filePath,"未支付",sell);
            }

            if (!res.isSuccess()) {
                return ResponseData.error("下单失败，请检查套餐设置!");
            }


            orderView.setSetMealIndex(setMealIndex);
            Integer insert = 0;

            insert = orderViewMapper.insert(orderView);

            if (insert == 1) {
                orderV.setOrderSeq(orderSeq);
                orderV.setWebOrderAmount(webOrderAmount);
                orderV.setProductIntroductionPic4(product.getProductIntroductionPic4());
                return ResponseData.success(orderV, "订单提交完成！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.error("下单失败，请检查套餐设置!");
        }finally {
            redisTemplate.delete(orderNumber);
            redisTemplate.delete(orderCustomerAccount);
        }
        return ResponseData.error("请重新提交");
    }

    public ResponseData<Object> createOrder(String productId, OrderView orderView, String userId, String rhTime,String filePath,String orderStatus,String sell){
        Order order = new Order();
        try {
            String uuid = UUID.randomUUID().toString();
            String id = uuid.split("-")[0] + uuid.split("-")[1];

            order.setId(id);
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat sd2 = new SimpleDateFormat("yyyyMM");
            String orderNumber = "YRYM" + sd.format(new Date()) + id.substring(1, 12);
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = null;
            try {
                if (StringUtils.isNotBlank(rhTime)) {
                    parse = simpleDateFormat1.parse(rhTime);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            order.setRhTime(parse);
            order.setOrderNumber(orderNumber);
            order.setOrderStatus(OrderStatus.NOTPAID.getName());
            order.setHehuorenId(userId);
            order.setCustomerName(orderView.getOrderName());
            order.setContactNumber(orderView.getOrderPhone());
            order.setBusinessNumber(orderView.getOrderCustomerRemarks());
            order.setIdCard(orderView.getOrderNumber());
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserType("3");
            order.setKapin("融合办理");

            order.setStudenCard(orderView.getOrderCustomerStudentId().toString());
            order.setNetNumber(orderView.getOrderCustomerAccount().toString());
            order.setNetPassword(orderView.getOrderCustomerPwd().toString());
            order.setUserSchool(orderView.getOrderUniversityName().toString());
            order.setExpenses(orderView.getOrderSetMeal().toString());
            order.setKdOrderId(orderView.getOrderSeq().toString());
            SysUser sysUser = sysUserMapper.selectById(userId);
            order.setHehuorenPhone(sysUser.getPhone().toString());
            String schoolId = appMapper.selectSchoolId(userId);
            School school = schoolMapper.selectById(schoolId);
            order.setHehuorenSchool(school.getSchoolName());
            order.setHehuorenName(sysUser.getName()+sell);
//            order.setPackageId(productId);
            order.setHehuorenArea(school.getSubName());
            order.setSignImg(filePath);
            List<String> userId1 = appMapper.selectsupervisorBySchool(schoolId);
            if (userId1 != null && userId1.size() != 0 ) {
                for (String data:userId1){
                    try{
                        Wrapper<HhrUser> userWrapper = new EntityWrapper<>();
                        userWrapper.eq("id",data);
                        userWrapper.eq("position","总经理");
                        List<HhrUser> hhrUsers = hhrUserMapper.selectList(userWrapper);
                        if(hhrUsers != null && hhrUsers.size()==1){
                            SysUser user = sysUserMapper.selectById(hhrUsers.get(0).getId());
                            order.setSupervisorName(user.getName());
                        }
                    }catch (Exception e){
                        log.error("查询督导失败:"+e.getMessage(),e);
                    }
                }
            }
            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(orderStatus);
            orderMapper.insert(order);
            appMapper.inserOrderHis(id, "待下单！", new Date(), orderView.getOrderName());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.error("操作失败");
        }

        return ResponseData.success(order, "订单创建成功");
    }

    @RequestMapping(value = "toSubmisOrderPreser", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=UTF-8")
    public void toSubmisOrderPreser(HttpServletRequest request){
        try{
            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);
            List<OrderView> orderViews = orderViewMapper.selectList(wrapper);
            if(orderViews.size()>0){
                if(!"".equals(orderViews.get(0).getUptranseq())&&uptranseq.equals(orderViews.get(0).getUptranseq())){

                }else {
                    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("kd_order_id", 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());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 支付接口
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "orderPay")
    public ResponseData<Object> toPaymentPlatformPage(HttpServletRequest request, HttpServletResponse response){
        String uuid = UUID.randomUUID().toString();
        String orderSeq =  request.getParameter("orderSeq");
        String ipay =  request.getParameter("ipay");
        String userId =  request.getParameter("userId");
        String rhTime =  request.getParameter("rhTime");

        // 参数校验
        if (StringUtils.isBlank(orderSeq) || StringUtils.isBlank(ipay)) {
            return ResponseData.error("参数有误，请重新进入下单页面进行支付");
        }

        try {
            boolean boo1 = redisLockUtil.redisLock(orderSeq,uuid,10);
            if(!boo1){
                return ResponseData.error("已在支付中");
            }
            String result = JsoupMethodZhifu(orderSeq, ipay, userId, request, response,rhTime);
            return ResponseData.success(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redisLockUtil.deleteLock(orderSeq);
        }
        return ResponseData.error("支付失败！若已支付请实名认证，未支付请稍后尝试支付。");
    }
    @RequestMapping(value = "/selectUniversity",method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<UniversityInfo> selectUniversity(@RequestParam("universityId") String universityId) {
        UniversityInfo universityInfo = universityInfoMapper.selectById(universityId);
        return ResponseData.success(universityInfo);
    }

    /**
     * @author ljh
     * @Description:支付请求
     */
    public String JsoupMethodZhifu(String orderSeq, String ipay, String userId,
                                 HttpServletRequest request, HttpServletResponse response, String rhTime){
        try{
            log.info("----------首先发送支付请求接口----------");
            //查询订单信息

            String uuid = UUID.randomUUID().toString();
            String id = uuid.split("-")[0] + uuid.split("-")[1];
            //修改支付方式
            Wrapper<OrderView> wrapper = new EntityWrapper<>();
            wrapper.eq("orderSeq", orderSeq);
            OrderView orderView = orderViewMapper.selectList(wrapper).get(0);
            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());//身份证

            //支付成功回调的页面（以前限制支付宝支付才能回调）
            /**
             * 测试后提交代码要恢复正式环境地址
             */
//            String MERCHANTURL = "https://dx.dianyuanjiangli.com/mobile/#/hhr/kdyToSuccessPage?kdId=" + orderSeq;
            String MERCHANTURL = "https://dx.dianyuanjiangli.com/mobile/#/hhr/kdyToSuccessPage/" + orderSeq;
//            测试
//            String MERCHANTURL = "http://3715zj2369.qicp.vip:52511/#/hhr/kdyToSuccessPage?kdId=" + orderSeq;
            map.put("MERCHANTURL", MERCHANTURL);
            // 融合回调后端接口地址
            //正式地址
            map.put("BACKDROPURL", "https://dx.dianyuanjiangli.com/app/ciop/rongHe/toSubmisOrderPreser");
//            测试
//            map.put("BACKDROPURL", "http://3715zj2369.qicp.vip/ciop/rongHe/toSubmisOrderPreser");
            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;    // 支付平台
            if (Constant.Payment3.equals(ipay)) {
                PAYTYPE = 5;
                IPAY = 3;
            }
            log.info("----------支付渠道（0翼支付网厅，1支付宝，3微信）：" + ipay);

            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秒钟，
//      旧地址    https://gzdxpay.mini189.cn/web/order-pay.action
//      新环境测试地址 https://gzctpay.mini189.cn/previewpay/orderPay/order-pay
//      新环境正式地址 https://gzctpay.mini189.cn/pay/orderPay/order-pay
            doc =
                    Jsoup.connect("https://gzctpay.mini189.cn/pay/orderPay/order-pay")
//                        .proxy("172.18.101.170", 3128)
                            .data(map)
                            .timeout(20000)
                            .ignoreContentType(true)
                            .post();
            //获取回调信息
            String i = doc.text().trim();
            //解析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("payType", PAYTYPE + "");
                log.info("====默认受理未付费，之后可通过提交订单到智能平台后再更新状态====");
                dataMapping.put("status", "100");
                log.info("====保存到本地数据库 ====");
                orderViewMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
                appMapper.inserOrderHis(id, "支付请求提交！", new Date(), orderView.getOrderName());
                return result;
            }
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }

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


}
