package com.winsun.controller;

import com.alibaba.fastjson.JSONArray;
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.FilePath;
import com.winsun.constant.OrderStatus;
import com.winsun.mapper.*;
import com.winsun.outSideSystem.IntelligenceSendOrder;
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.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 单宽办理接口
 *
 * @Author xuede
 * @Date 2020/3/9 16:52
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/dankuan")
public class DankuanController {
    @Autowired
    private ProductMapper productMapper;
    @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;

    @Autowired
    private Base64ToImgUtils base64ToImgUtils;

    @Autowired
    private IntelligenceSendOrder intelligenceSendOrder;
    /**
     * 查询单宽办理接口
     *
     * @return
     */
    @RequestMapping("/data")
    public ResponseData<Product> getdankuanData(@RequestParam("id") Integer id) {
        //空，直接返回
        if (id == null) {
            return ResponseData.error("请输入合伙人id");
        }
        String schoolId = appMapper.selectSchoolId(id.toString());
        School school = schoolMapper.selectById(schoolId);
        String bandproductId = school.getBandproductId();
        if (StringUtils.isBlank(bandproductId)) {
            return ResponseData.error("敬请期待");
        }
        Product product = productMapper.selectById(bandproductId);
        return ResponseData.success(product);
    }

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

    /**
     * 创建单宽order_view
     *
     * @return
     */
    @PostMapping("/createProductOrder")
    public ResponseData<Object> createProductOrder(HttpServletRequest request,HttpServletRequest response){
        String orderName = request.getParameter("orderName");
        String orderPhone = request.getParameter("orderPhone");
        String orderNumber = request.getParameter("orderNumber");
        String banLiPhone = request.getParameter("banLiPhone");
        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 setMealIndex = request.getParameter("setMealIndex");
        String imgUrl = request.getParameter("imgUrl");
        String filePath = "";
        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 = base64ToImgUtils.base64ToImg(imgUrl, FilePath.PATH.getValue()+FilePath.IMGURLPATH.getValue());
            }
            OrderView orderV = new OrderView();
            String orderSeq = RandomUtil.RandomNumber(20);
            Product product = productMapper.selectById(productId);
            OrderView orderView = new OrderView();
            orderView.setOrderName(orderName);
            orderView.setOrderPhone(orderPhone);
            orderView.setOrderNumber(orderNumber);
            orderView.setOrderCustomerStudentId(orderCustomerStudentId);
            orderView.setOrderCustomerAccount(orderCustomerAccount);
            orderView.setOrderCustomerPwd(orderCustomerPwd);
            orderView.setOrderSetMeal(orderSetMeal);
            orderView.setOrderSeq(orderSeq);
            orderView.setProductName(product.getProductTitle());
            orderView.setOrderDate(new Date());
            orderView.setOrderUniversityName(product.getProductUniversity());
            orderView.setHehuorenId(partner);
            orderView.setOrderRegion(product.getProductRegion());
            orderView.setPayType("1");
            orderView.setWebOrderAmount(webOrderAmount);
            if (webOrderAmount.equals("0")) {
                orderView.setIPay("0");
            } else {
                orderView.setIPay("1");
            }
            orderView.setCustomerId("xyzxyql");
            orderView.setOrderCustomerType("学生");

            ResponseData<Object> res = null;

            orderView.setSetMealIndex(setMealIndex);

            Integer insert = orderViewMapper.insert(orderView);

            if (webOrderAmount.equals("0")) {
                res = createOrder(productId,orderView, partner,filePath,"未下单");
                Map<String,Object> map = orderMapper.selectKdOrder(orderSeq);
                intelligenceSendOrder.singleBroadSendOrder(map);
                Order order =(Order) res.getData();
                orderV.setOrderRf2(order.getId());
            }else {
                res = createOrder(productId,orderView, partner,filePath,"未支付");
            }
            if (!res.isSuccess()) {
                return ResponseData.error("网络超时，请重试!");
            }
            if (insert == 1) {
                orderV.setOrderId(orderView.getOrderId());
                orderV.setOrderSeq(orderView.getOrderSeq());
                orderV.setWebOrderAmount(webOrderAmount);
                return ResponseData.success(orderV, "订单提交完成！");
            }
            return ResponseData.error("提交失败！");
        }catch (Exception e){
            return ResponseData.error("网络超时，请重试!");
        }finally {
            redisTemplate.delete(orderNumber);
            redisTemplate.delete(orderCustomerAccount);
        }
    }

    /**
     * 0元调用 创建order
     * @param orderView
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseData<Object> createOrder(String productId, OrderView orderView, String userId,String filePath,String orderStatus){
        Order order = new Order();
        try{
            String uuid = UUID.randomUUID().toString();
            String id = uuid.split("-")[0] + uuid.split("-")[1];
            order.setId(id);

            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");
            order.setOrderNumber(orderNumber);
            order.setOrderStatus(OrderStatus.NOTPAID.getName().toString());
            order.setHehuorenId(userId);
            order.setCustomerName(orderView.getOrderName());
            order.setContactNumber(orderView.getOrderPhone());
            order.setIdCard(orderView.getOrderNumber().toString());
            order.setCreateTime(new Date());
            order.setUserType("5");
            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());
            String schoolId = appMapper.selectSchoolId(userId);
            School school = schoolMapper.selectById(schoolId);
            order.setHehuorenSchool(school.getSchoolName());
            order.setHehuorenName(sysUser.getName());
            order.setHehuorenArea(sysUser.getSubstName());
            order.setSignImg(filePath);
            List<String> userId1 = appMapper.selectsupervisorBySchool(schoolId);
            SysUser user = sysUserMapper.selectById(userId1.get(0));
            order.setSupervisorName(user.getName());
            order.setLzgh(school.getLzgh());
            order.setOrderStatus(orderStatus);
            // 根据订单号，获取该订单信息
            // 根据学校名称，获取该学校信息
            Product product = productMapper.selectById(productId);
            Wrapper<UniversityInfo> uiWrapper = new EntityWrapper<>();
            uiWrapper.eq("university_id", product.getUniversityId());
            Map<String, Object> schoolMap = universityInfoMapper.selectMaps(uiWrapper).get(0);
            orderMapper.insert(order);
            appMapper.inserOrderHis(id, "待审核！", new Date(), orderView.getOrderName());
        }catch (Exception e){
            e.getMessage();
            Wrapper<OrderView> wrapper = new EntityWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(orderView.getOrderSeq().toString()), "orderSeq", orderView.getOrderSeq().toString());
            orderViewMapper.delete(wrapper);
            return ResponseData.error("订单创建失败");
        }

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

    /**
     * 支付完成回调接口
     *
     * @param request
     * @throws Exception
     */
    @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());
    }

    /**
     * 支付完成回调接口--(旧)
     *
     * @param request
     * @throws Exception
     */
    public void toSubmisOrderPreser1(HttpServletRequest request) throws Exception {
        OrderView orderMap = null;
        Map<String, Object> schoolMap = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTimeStr = simpleDateFormat.format(new Date());
        log.info("----------异步通知后返回入口----------");
        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);


        orderMap = orderViewMapper.selectList(wrapper).get(0);

        // 根据学校名称，获取该学校信息
        Wrapper<UniversityInfo> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("university_name", orderMap.getOrderUniversityName());
        wrapper1.eq("university_region", orderMap.getOrderRegion());
        schoolMap = universityInfoMapper.selectMaps(wrapper1).get(0);

        if (StringUtils.isBlank(orderMap.getOrderseqThd())) {
            //	1、获取产品ID
            JSONObject productJsonObject = getProductId(currentTimeStr);
            log.info("----------调用智能平台的产品接口返回参数：" + productJsonObject);
            //	2、获取销售品ID
            if (productJsonObject.toString().indexOf("list") == -1) {
                return;
            }
            JSONArray list = productJsonObject.getJSONArray("list");
            String productId = null;    // 产品id
            orderamount = orderamount.replace("元", "");
            orderamount = orderamount.replace(".00", "");

            String productName = "校园宽带" + orderamount + "元";
            if (orderamount.equals("0.01")) {
                productName = "校园宽带30元";
            } else if (orderamount.equals("0.02")) {
                productName = "校园宽带300元";
            }
            log.info("------" + productName);
            //productName = "校园宽带30元";
            for (int i = 0; i < list.size(); i++) {
                JSONObject itmeJson = JSONObject.parseObject(list.get(i).toString());
                // 判断获取的全部产品与订单产品符合的拿取对应的ID
                if (itmeJson.getString("name").indexOf(productName) != -1) {
                    productId = itmeJson.getString("id");                            // 获取对应产品ID
                    break;
                }
            }
            log.info("----------根据返回参数获取产品ID：" + productId);
            String saleId = null;    // 销售id
            JSONObject saleJsonObject = getSaleId(productId, currentTimeStr);    // 获取销售ID
            log.info("----------调用智能平台的获取销售品接口返回值：" + saleJsonObject);
            JSONArray saleList = saleJsonObject.getJSONArray("list");
            JSONObject itmeJson = JSONObject.parseObject(saleList.get(0).toString());
            saleId = itmeJson.getString("saleId");

            //	3、提交订单到智能平台
            JSONObject submitOrderJsonObject = getOrderInfo(schoolMap, orderMap, currentTimeStr, productId, saleId, orderseq, uptranseq, orderamount, orderreqtranseq);
            log.info("----------调用单宽带接口（提交订单至智能平台）并返回参数信息---status:" + submitOrderJsonObject.get("status") + " msg:" + submitOrderJsonObject.get("msg") + " orderNum:" + submitOrderJsonObject.get("orderNumber"));

            //	4、查询智能订单是否存在
            String orderNum = (String) submitOrderJsonObject.get("orderNumber");
            if (StringUtils.isNotBlank(orderNum)) {
                /*	5、更新数据库   */
                Map<String, Object> dataMapping1 = new HashMap<>();
                dataMapping1.put("orderSeqTHD", orderNum);
                dataMapping1.put("status", "已支付");
                orderViewMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping1), wrapper);

                Wrapper<Order> objectEntityWrapper = new EntityWrapper<>();
                objectEntityWrapper.eq("order_number", orderseq);
                Map<String, Object> dataMapping2 = new HashMap<>();
                dataMapping2.put("order_status", "审核中");
                dataMapping2.put("order_id", orderNum);
                dataMapping2.put("th_status", submitOrderJsonObject.get("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());
            }
        } else {
            log.info("---单宽支付接口推送---" + orderseq + "---" + uptranseq + "---" + orderamount + "---" + orderreqtranseq);
        }
    }

    /**
     * 支付接口
     *
     * @param orderId
     * @param ipay
     * @param userId
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "orderPay")
    public ResponseData<Object> toPaymentPlatformPage(@RequestParam("orderSeq") String orderSeq, @RequestParam("ipay") String ipay, @RequestParam("userId") String userId, HttpServletRequest request, HttpServletResponse response) {
        String uuid = UUID.randomUUID().toString();
        try {
            boolean boo1 = redisLockUtil.redisLock(orderSeq,uuid,10);
            if(!boo1){
                return ResponseData.error("已在支付中");
            }
            String result = JsoupMethodZhifu(orderSeq, ipay, userId, request, response);
            return ResponseData.success(result);
        }catch (Exception e){
            e.getMessage();
        }finally {
            redisLockUtil.deleteLock(orderSeq);
        }
        return ResponseData.error("订单异常");
    }

    /**
     * @author ljh
     * @Description:支付请求
     */
    public String JsoupMethodZhifu(String orderSeq, String ipay, String userId,
                                 HttpServletRequest request, HttpServletResponse response) throws Exception {
        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/dkSuccessful?id="+userId+"&"+"orderSeq="+orderSeq;
        map.put("MERCHANTURL", MERCHANTURL);
        //单宽回调后端接口地址
        // 正式环境
        map.put("BACKDROPURL", "https://dx.dianyuanjiangli.com/apply-net/ciop/dankuan/toSubmisOrderPreser");
        //测试地址
    //      map.put("BACKDROPURL", "http://3715zj2369.qicp.vip/ciop/dankuan/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;    // 支付平台
        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秒钟，
//      旧地址    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();
        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);
            appMapper.inserOrderHis(id, "支付请求提交！", new Date(), orderView.getOrderName());
            return result;
        }
        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 orderMap, String currentTimeStr, String productId, String saleId, String ORDERSEQ, String UPTRANSEQ, String ORDERAMOUNT, String ORDERREQTRANSEQ) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(Constant.ZHANGSHIURL + "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.broadband.create"));//api标识，必填
        signMap.put("service", "order.broadband.create");    //api标识，必填
        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("customerType", "2"));    //客户类型 （1：已有固话，未有宽带 2：未有固话和宽带），必填
        signMap.put("customerType", "2");
        qParams.add(new BasicNameValuePair("fixedPhoneNum", ""));    //客户类型为1时，固话号码，必填
        signMap.put("fixedPhoneNum", "");
        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", orderMap.getOrderName()));    //客户姓名，必填
        signMap.put("customerName", orderMap.getOrderName());
        qParams.add(new BasicNameValuePair("customerPhone", orderMap.getOrderPhone()));    //客户电话，必填
        signMap.put("customerPhone", orderMap.getOrderPhone());
        qParams.add(new BasicNameValuePair("customerCardType", "身份证"));    //证件类型，必填
        signMap.put("customerCardType", "身份证");
        qParams.add(new BasicNameValuePair("customerCardNum", orderMap.getOrderNumber()));    //证件号码，必填
        signMap.put("customerCardNum", orderMap.getOrderNumber());
        qParams.add(new BasicNameValuePair("addressProvince", "广东省"));    //报装地址省份，必填
        signMap.put("addressProvince", "广东省");
        qParams.add(new BasicNameValuePair("addressCity", "广州市"));    //报装地址城市，必填
        signMap.put("addressCity", "广州市");

        String addressDistrict = null;
        String address = null;
        String addressID = null;
        String landId = null;
        String universityTerminalType = null;
        String universityUserCategory = null;
        String universityUserType = null;
        String universityMonthlyRentType = null;
        String universityChargingAttribute = null;
        String universityOnlineNumber = null;
        String universityOneManTerminal = null;
        String universityIsFtthHub = null;
        String universityExteriorLines = null;
        String universityChargeMode = null;
        if (BeanUtil.isNotBlank(schoolMap)) {
            addressDistrict = (String) schoolMap.get("universityRegion");
            address = (String) schoolMap.get("universityInstalledAddress");
            addressID = (String) schoolMap.get("universityInstalledAddressId");
            landId = (String) schoolMap.get("universityPackageNumber");
            universityTerminalType = (String) schoolMap.get("universityTerminalType");
            universityUserCategory = (String) schoolMap.get("universityUserCategory");
            universityUserType = (String) schoolMap.get("universityUserType");
            universityMonthlyRentType = (String) schoolMap.get("universityMonthlyRentType");
            universityChargingAttribute = (String) schoolMap.get("universityChargingAttribute");
            universityOnlineNumber = (String) schoolMap.get("universityOnlineNumber");
            universityOneManTerminal = (String) schoolMap.get("universityOneManTerminal");
            universityIsFtthHub = (String) schoolMap.get("universityIsFtthHub");
            universityExteriorLines = (String) schoolMap.get("universityExteriorLines");
            universityChargeMode = (String) schoolMap.get("universityChargeMode");
        } else {
            addressDistrict = "测试区";
            address = "广东省广州市测试区测试街道1号";
            addressID = "00000";
            landId = "20180621";
            universityTerminalType = "测试";
            universityUserCategory = "测试";
            universityUserType = "测试";
            universityMonthlyRentType = "测试";
            universityChargingAttribute = "测试";
            universityOnlineNumber = "0";
            universityOneManTerminal = "否";
            universityIsFtthHub = "否";
            universityExteriorLines = "测试";
            universityChargeMode = "测试";
        }
        qParams.add(new BasicNameValuePair("addressDistrict", addressDistrict));    //报装地址区域，必填
        signMap.put("addressDistrict", addressDistrict);
        qParams.add(new BasicNameValuePair("address", address));    //报装详细地址，必填
        signMap.put("address", address);
        qParams.add(new BasicNameValuePair("deliveryContact", orderMap.getOrderName()));    //报装联系人，必填
        signMap.put("deliveryContact", orderMap.getOrderName());
        qParams.add(new BasicNameValuePair("deliveryContactPhone", orderMap.getOrderPhone()));    //报装联系电话，必填
        signMap.put("deliveryContactPhone", orderMap.getOrderPhone());

        qParams.add(new BasicNameValuePair("invoiced", "0"));    //是否需要发票 0：否 1：是，必填
        signMap.put("invoiced", "0");
        qParams.add(new BasicNameValuePair("invoiceTitle", ""));    //若需要发票，发票抬头，必填
        signMap.put("invoiceTitle", "");
        qParams.add(new BasicNameValuePair("invoiceDeliveryAddress", ""));    //若需要发票，发票电子邮箱，必填
        signMap.put("invoiceDeliveryAddress", "");
        qParams.add(new BasicNameValuePair("landId", landId));    //揽装工号，必填
        signMap.put("landId", landId);
        qParams.add(new BasicNameValuePair("groupLanId", ""));    //集团揽装工号，选填
        signMap.put("groupLanId", "");
        qParams.add(new BasicNameValuePair("comarketingLanId", ""));    //协销工号，选填
        signMap.put("comarketingLanId", "");
        qParams.add(new BasicNameValuePair("groupComarketingLanId", ""));    //集团协销工号，选填
        signMap.put("groupComarketingLanId", "");
        qParams.add(new BasicNameValuePair("orderOutNum", orderMap.getOrderSeq()));    //外部订单编号，选填!；通过API接口下单，必须传入一个外部接入商的订单编号,该编号与智能营销系统编号一一对应
        signMap.put("orderOutNum", orderMap.getOrderSeq());
        qParams.add(new BasicNameValuePair("orderSource", "校园宽带自助受理"));    //订单来源 ，选填
        signMap.put("orderSource", "校园宽带自助受理");
        qParams.add(new BasicNameValuePair("orderSourceNum", orderMap.getOrderSeq()));    //订单来源单号，选填； 与订单来源对应，用于业务上记录订单的来源订单编号
        signMap.put("orderSourceNum", orderMap.getOrderSeq());
        qParams.add(new BasicNameValuePair("salePointCode", ""));    //销售点编码，选填
        signMap.put("salePointCode", "");
        qParams.add(new BasicNameValuePair("personCode", ""));    //人员编码，选填
        signMap.put("personCode", "");
        qParams.add(new BasicNameValuePair("distributorSmsReceive", ""));    //分销商短信接收号码，选填
        signMap.put("distributorSmsReceive", "");
        qParams.add(new BasicNameValuePair("agent", ""));    //代理商推荐人，选填
        signMap.put("agent", "");
        qParams.add(new BasicNameValuePair("copyied", "0"));    //是否收取复印件(0:否 1:是),必填
        signMap.put("copyied", "0");
        qParams.add(new BasicNameValuePair("deliveryContactPhone", orderMap.getOrderPhone()));    //联系人电话 ，必填
        signMap.put("deliveryContactPhone", orderMap.getOrderPhone());
        qParams.add(new BasicNameValuePair("deliveryContactPhone2", ""));    //联系人电话2，选填
        signMap.put("deliveryContactPhone2", "");

        List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>();//下单产品列表
        List<Map<String, String>> paymentList = new ArrayList<Map<String, String>>();//收费项列表
        List<Map<String, String>> propertyList = new ArrayList<Map<String, String>>();//产品自定义属性列表
        //下单产品
        Map<String, Object> productMap = new HashMap<String, Object>();
        //收费项；智能平台3.0产品设计中收费项可由用户自主选择（至少选择一个），可根据需要创建paymentMap对象；注意：每个收费项可独立选择缴费方式
        Map<String, String> paymentMap = new HashMap<String, String>();
        paymentMap.put("id", saleId);//收费项ID，必填；请通过销售品列表接口获取
        paymentMap.put("payType", "2");//缴费方式，必填（例：payType：1）；1：银行划账2：现金支付3：代理商打款4：穗易付5：原套餐缴费方式6：支付宝划扣8：装维上门收取
        paymentMap.put("tag", "");//费用项标识，选填
        paymentMap.put("bank", "");//缴费银行，缴费方式为“银行划账”时必填 ：[中国银行|中国工商银行|中国农业银行|民生银行|招商银行|中信银行|商业银行|广东发展银行|光大银行|华夏银行|兴业银行|浦发银行|广州农村商业银行|广州银行|深圳发展银行|交通银行|中国建设银行|邮政储蓄]
        paymentMap.put("bankNumber", "");//银行账号，缴费方式为“银行划账”时必填
        paymentMap.put("bankOwner", "");////银行账号持有人，缴费方式为“银行划账”时必填
        paymentMap.put("payPlatform", "");
        paymentMap.put("electronicPayNumber", "");//支付流水号，缴费方式为“穗易付”时必填
        paymentMap.put("payOrderNumber", "");// 穗易付订单号，若选择穗易付，此项必填
        paymentMap.put("alipayUserid", "");//用户ID，缴费方式为“支付宝支付”时必填
        paymentMap.put("alipayNumber", "");//支付宝账号，缴费方式为“支付宝支付”时必填
        paymentMap.put("alipayAuthNumber", "");//授权协议号，缴费方式为“支付宝支付”时必填
        paymentMap.put("payAmount", "");//缴费金额（打款金额），缴费方式为“代理商打款”或“穗易付”时必填
        paymentList.add(paymentMap);
        //产品自定义属性；暂时默认属性名称只能传“日租卡号码”
        Map<String, String> propertyMap = new HashMap<String, String>();
        propertyMap.put("name", "宽带速率");
        String setMeal = orderMap.getOrderSetMeal();
        if (StringUtils.isNotBlank(setMeal)) {
            setMeal = setMeal.replace("包月", "");
            setMeal = setMeal.replace("包年", "");
        }
        if (setMeal.equals("20M")) {
            setMeal = "20M下行速率/4M上行速率";
        } else if (setMeal.equals("2M")) {
            setMeal = "2M下行速率/512K上行速率";
        } else if (setMeal.equals("50M")) {
            setMeal = "50M下行速率/10M上行速率";
        }
        propertyMap.put("value", setMeal);
        Map<String, String> propertyMap1 = new HashMap<String, String>();
        propertyMap1.put("name", "学校名称");
        propertyMap1.put("value", orderMap.getOrderUniversityName());
        Map<String, String> propertyMap2 = new HashMap<String, String>();
        propertyMap2.put("name", "允许上网终端类型");
        propertyMap2.put("value", universityTerminalType);
        Map<String, String> propertyMap3 = new HashMap<String, String>();
        propertyMap3.put("name", "用户类别");
        propertyMap3.put("value", universityUserCategory);
        Map<String, String> propertyMap4 = new HashMap<String, String>();
        propertyMap4.put("name", "用户类型");
        propertyMap4.put("value", universityUserType);
        Map<String, String> propertyMap5 = new HashMap<String, String>();
        propertyMap5.put("name", "月租类型");
        propertyMap5.put("value", universityMonthlyRentType);
        Map<String, String> propertyMap6 = new HashMap<String, String>();
        propertyMap6.put("name", "计费属性");
        propertyMap6.put("value", universityChargingAttribute);
        Map<String, String> propertyMap7 = new HashMap<String, String>();
        propertyMap7.put("name", "一人一号多终端");
        propertyMap7.put("value", universityOneManTerminal);
        Map<String, String> propertyMap8 = new HashMap<String, String>();
        propertyMap8.put("name", "外线方式");
        propertyMap8.put("value", universityExteriorLines);
        Map<String, String> propertyMap9 = new HashMap<String, String>();
        propertyMap9.put("name", "是否FTTH+HUB");
        propertyMap9.put("value", universityIsFtthHub);
        Map<String, String> propertyMap10 = new HashMap<String, String>();
        propertyMap10.put("name", "多媒体账号");
        propertyMap10.put("value", orderMap.getOrderCustomerAccount());
        Map<String, String> propertyMap11 = new HashMap<String, String>();
        propertyMap11.put("name", "多媒体账号密码");
        propertyMap11.put("value", orderMap.getOrderCustomerPwd());
        Map<String, String> propertyMap12 = new HashMap<String, String>();
        propertyMap12.put("name", "学生证号");
        propertyMap12.put("value", orderMap.getOrderCustomerStudentId());
        Map<String, String> propertyMap13 = new HashMap<String, String>();
        propertyMap13.put("name", "宽带首月费用类型");
        propertyMap13.put("value", universityChargeMode);
        Map<String, String> propertyMap14 = new HashMap<String, String>();
        propertyMap14.put("name", "最大在线数");
        propertyMap14.put("value", universityOnlineNumber);
        Map<String, String> propertyMap15 = new HashMap<String, String>();
        propertyMap15.put("name", "地址ID");
        propertyMap15.put("value", addressID);
        propertyList.add(propertyMap);
        propertyList.add(propertyMap1);
        propertyList.add(propertyMap2);
        propertyList.add(propertyMap3);
        propertyList.add(propertyMap4);
        propertyList.add(propertyMap5);
        propertyList.add(propertyMap6);
        propertyList.add(propertyMap7);
        propertyList.add(propertyMap8);
        propertyList.add(propertyMap9);
        propertyList.add(propertyMap10);
        propertyList.add(propertyMap11);
        propertyList.add(propertyMap12);
        propertyList.add(propertyMap13);
        propertyList.add(propertyMap14);
        propertyList.add(propertyMap15);
        productMap.put("productId", productId);//产品ID，请通过产品列表接口获取
        productMap.put("payment", paymentList);//收费项列表
        productMap.put("addProperties", propertyList);//产品自定义属性列表
        productList.add(productMap);
        //将对象装换为json字符串
        String productJson = JSONArray.toJSONString(productList);
        qParams.add(new BasicNameValuePair("productJson", URLEncoder.encode(productJson, "UTF-8")));//产品信息，必填
        signMap.put("productJson", URLEncoder.encode(productJson, "UTF-8"));

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


}
