package com.winsun.controller;

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.mapper.*;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.ProduceIdUtil;
import com.winsun.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Author xuede
 * @Date 2020/3/10 10:16
 * @Version 1.0
 */
@Slf4j
@RestController
public class StartSelectController {

    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AppMapper appMapper;
    @Autowired
    private OrderHistoryMapper historyMapper;
    @Autowired
    private UniversityInfoMapper universityInfoMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderViewMapper orderViewMapper;

    /**
     * 查询学校信息
     */
    @RequestMapping(value = "findStartData", method = RequestMethod.POST)
    public ResponseData<School> selectSchoolInfo(@RequestParam("id") String id) {

        UserSchool userSchool = userSchoolMapper.selectById(id);
        if(userSchool != null){
            School school = schoolMapper.selectById(userSchool.getSchoolId());
            return ResponseData.success(school);
        }
        return ResponseData.error("没有查询相关的合伙人id的信息！！！");
    }

    @ResponseBody
    @RequestMapping(value = "sendBysCodes", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkStudent(String phone) {

        Map<String, Object> map = new HashMap<>();
        try {

            List<Map<String, Object>> maps = orderMapper.selectBys(phone);
            if (maps == null || maps.size() == 0) {
                return ResponseData.error("该号码不允许办理此业务。");
            }

//          生成6位随机数
            int veCode = (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000);
            redisTemplate.opsForValue().set(phone, String.valueOf(veCode), 30, TimeUnit.MINUTES);
            SendSmsAndMail.sendSms(phone,veCode + "","7");
            log.info("验证码:" + veCode);
            map.put("code",1);
        } catch (Exception e) {
            log.error("获取验证码异常:", e);
            map.put("code",2);
        }
        return ResponseData.success(map);
    }

    /**
     *通过学生ID，name和身份证查询学生信息
     * @param stuId 学生ID
     * @param name 用户名
     * @param idCard 身份证号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "checkStudent", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkStudent(String stuId,String name,String idCard){

        Wrapper<Student> studentWrapper = new EntityWrapper<>();
        studentWrapper.setSqlSelect("id,stu_name AS stuName,id_card AS idCard,worker,aClass");
        if (StringUtils.isNotBlank(stuId)){
            studentWrapper.addFilter("id = '"+stuId+"'");
        }
        if (StringUtils.isNotBlank(name)){
            studentWrapper.addFilter("stu_name = '"+name+"'");
        }
        if (StringUtils.isNotBlank(idCard)){
            studentWrapper.addFilter("id_card = '"+idCard+"'");
        }
        List<Map<String, Object>> studentMap = studentMapper.selectMaps(studentWrapper);
        if (studentMap == null || studentMap.size() == 0) {
            return ResponseData.error("该学生信息不存在！");
        }
        return ResponseData.success(studentMap.get(0),"验证通过");
    }

    /**
     * 手机端主页面，带参数进入手机端主页
     * 对订单进去保存和提交订单到智能平台上
     */
    @RequestMapping(value = "toBYSOrderSuccessPage")
    @ResponseBody
    public Map<String, Object> toBYSOrderSuccessPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap();
        map.put("code", "0");
        log.info("====0元订单提交操作");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTimeStr = simpleDateFormat.format(new Date());
        Map<String, String[]> parameterMap = request.getParameterMap();

        // 身份证查重单
        List<Order> orders = orderMapper.selectRepeatOrder(parameterMap.get("identification")[0]);
        if (orders != null && orders.size() != 0) {
            map.put("code", "1");
            map.put("error", "已有重复订单");
            return map;
        }

        Map<String,String> maps = new HashMap<>();
        String orderSeq = ProduceIdUtil.getId().toString();
        maps.put("orderSeq",orderSeq);
        String productId = "1329";    // 产品id
        String saleId = null;    // 销售id
        JSONObject saleJsonObject = getSaleId(productId, currentTimeStr);    // 获取销售ID
        log.info("----------调用智能平台的获取销售品接口返回值：" + saleJsonObject);
        log.info("----111--" + (saleJsonObject.toString().indexOf("list") == -1));
        if (saleJsonObject.toString().indexOf("list") == -1) {
            map.put("code", "1");
            map.put("error", "销售品获取失败");
            return map;
        }
        JSONArray saleList = saleJsonObject.getJSONArray("list");
        log.info("----saleList---：" + saleList);
        String saleId1 = "";
        String saleId2 = "";
        String saleId3 = "";
        String saleId4 = "";
        for (int i = 0; i < saleList.size(); i++) {
            JSONObject itmeJson = JSONObject.fromObject(saleList.get(i));
            // 判断获取的全部产品与订单产品符合的拿取对应的ID
            if (itmeJson.getString("propertyName").indexOf("单宽带") != -1) {
                if (itmeJson.getString("name").equals("单宽_2015年7月-100M/190元")) {
                    saleId1 = itmeJson.getString("saleId");
                    maps.put("saleId1",saleId1);
                }
            } else if (itmeJson.getString("propertyName").indexOf("提速包") != -1) {
                if (itmeJson.getString("name").equals("移动老用户升级融合享套餐折扣_6个月")) {
                    saleId2 = itmeJson.getString("saleId");
                    maps.put("saleId2",saleId2);
                }
            } else if (itmeJson.getString("propertyName").indexOf("套餐优惠") != -1) {
                if (itmeJson.getString("name").equals("129-5G畅想单品+40元权益金")) {
                    saleId3 = itmeJson.getString("saleId");
                    maps.put("saleId3",saleId3);
                }
            } else if (itmeJson.getString("propertyName").indexOf("一次性收费") != -1) {
                if (itmeJson.getString("name").equals("一次性安装调测费200元")) {
                    saleId4 = itmeJson.getString("saleId");
                    maps.put("saleId4",saleId4);
                }
            }
        }

        //	3、提交订单到智能平台
        JSONObject submitOrderJsonObject = getOrderBYSRHInfo(parameterMap, currentTimeStr, productId,maps);
        log.info("----------调用融合接口（提交订单至智能平台）并返回参数信息---status:" + submitOrderJsonObject.get("status") + " msg:" + submitOrderJsonObject.get("msg") + " orderNum:" + submitOrderJsonObject.get("orderNumber"));
        String orderNum = (String) submitOrderJsonObject.get("orderNumber");
        JSONObject queryOrderJsonObject = null;
        if (StringUtils.isNotBlank(orderNum)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, String> orderMap = new HashMap<>();
            orderMap.put("orderSeq", orderSeq);
            orderMap.put("productTitle", "中国电信校园高速宽带");
            orderMap.put("order_set_meal", "毕业生融合套餐");
            orderMap.put("order_university_name", "毕业生");
            orderMap.put("orderName", parameterMap.get("userName")[0]);
            orderMap.put("orderDatetime", sdf.format(new Date()));
            orderMap.put("Status", "待提交");
            orderMap.put("universityRegion", "");
            orderMap.put("ipay", "0");
            orderMap.put("payType", "1");
            orderMap.put("prices", "200");
            orderMap.put("orderTHD", orderNum);
            orderMap.put("orderPhone", parameterMap.get("contactNumber")[0]);
            orderMap.put("orderNumber", parameterMap.get("identification")[0]);
            orderMap.put("expenses", "毕业生融合套餐");
            orderMap.put("upStatus", "2");
            orderMap.put("site", parameterMap.get("myAddrs")[0].replace("/"," "));
            orderMap.put("address", parameterMap.get("address")[0]);
            orderMap.put("partner", parameterMap.get("partner")[0]);
            /*	5、更新数据库   */
            saveOrderInfo(orderMap,"");

            map.put("orderSeq", orderSeq);
        }else{
            map.put("code", "1");
            map.put("msg", submitOrderJsonObject.get("msg"));
        }
        return map;    // 不成功
    }

    private JSONObject getOrderBYSRHInfo(Map<String, String[]> parameterMap, String currentTimeStr, String productId, Map<String,String> objectMap) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(500000)
                .setConnectTimeout(500000).setConnectionRequestTimeout(500000)
//                .setProxy(proxy)
                .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", parameterMap.get("bussnessPhone")[0]));// 电信号码，办理类型，若选择[新宽旧移]或[旧宽旧移]，此项必填
        signMap.put("ctNumber", parameterMap.get("bussnessPhone")[0]);


        String[] split = parameterMap.get("myAddrs")[0].split("/");

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

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

        String addressDistrict = split[2];
        String address = parameterMap.get("address")[0];
        String landId = "56190613";


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

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


        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", parameterMap.get("userName")[0]));// 客户姓名，必填
        signMap.put("customerName", parameterMap.get("userName")[0]);

        qParams.add(new BasicNameValuePair("customerPhone", parameterMap.get("bussnessPhone")[0]));// 客户电话|代办人电话，必填
        signMap.put("customerPhone", parameterMap.get("bussnessPhone")[0]);

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

        qParams.add(new BasicNameValuePair("customerCardNum", parameterMap.get("identification")[0]));// 证件号码，必填
        signMap.put("customerCardNum", parameterMap.get("identification")[0]);

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

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

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

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

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

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

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

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

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

        qParams.add(new BasicNameValuePair("deliveryContact", parameterMap.get("contactName")[0]));// 联系人，必填
        signMap.put("deliveryContact", parameterMap.get("contactName")[0]);

        qParams.add(new BasicNameValuePair("deliveryContactPhone", parameterMap.get("contactNumber")[0]));// 联系电话，必填
        signMap.put("deliveryContactPhone", parameterMap.get("contactNumber")[0]);

        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, String>> addPropertyList = new ArrayList<Map<String, String>>();// 自定义产品属性

        // 下单产品
        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", objectMap.get("saleId1"));// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
        paymentListMap2.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
        paymentListMap2.put("payType", "2");// 缴费方式，必填（例：payType：3）3：代理商打款4：穗易付7：货到付款

        Map<String, Object> paymentListMap3 = new HashMap<String, Object>();
        paymentListMap3.put("id", objectMap.get("saleId2"));// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
        paymentListMap3.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
        paymentListMap3.put("payType", "2");// 缴费方式，

        Map<String, Object> paymentListMap4 = new HashMap<String, Object>();
        paymentListMap4.put("id", objectMap.get("saleId3"));// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
        paymentListMap4.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
        paymentListMap4.put("payType", "2");// 缴费方式，

        Map<String, Object> paymentListMap5 = new HashMap<String, Object>();
        paymentListMap5.put("id", objectMap.get("saleId4"));// 收费项ID，选填；请通过销售品列表接口获取，若不填表示终端补收款
        paymentListMap5.put("saleName", "");// 销售品名称，选填，若id不填写此项必填写，且只能为终端补收款
        paymentListMap5.put("payType", "1");// 缴费方式，
        paymentListMap5.put("bank", parameterMap.get("bank")[0]);// 银行名称，若选择银行划账，此项必填
        // (中国银行、中国工商银行、中国农业银行、民生银行、招商银行、中信银行、商业银行、广东发展银行
        //  光大银行、华夏银行、兴业银行、浦发银行、广州农村商业银行、广州银行、深圳发展银行、交通银行、平安银行、中国建设银行、邮政储蓄)
        paymentListMap5.put("bankNumber", parameterMap.get("bankNumber")[0]);// 银行账号，若选择银行划账，此项必填
        paymentListMap5.put("bankOwner", parameterMap.get("userName")[0]);// 银行账号持有人，若选择银行划账，此项必填

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

        // 产品属性 必填主卡号码属性,name=主卡号码,value=11位数字或者随机；
        Map<String, Object> inPropertyListMap = new HashMap<String, Object>();
        inPropertyListMap.put("name", "主卡号码");
        inPropertyListMap.put("value", parameterMap.get("bussnessPhone")[0]);
        inPropertyList.add(inPropertyListMap);
        productMap.put("inpProperties", inPropertyList);

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

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

        for (String key : keys) {
            value = signMap.get(key);
            plaintext = plaintext.concat(value);
        }
        plaintext = plaintext.concat(Constant.ZHANGSHIKEY);
        log.info("---------plaintext---------:" + plaintext);
        String sign = MD5Utils.md5(plaintext).toUpperCase();//md5加密
        qParams.add(new BasicNameValuePair("sign", sign));//签名，必填
        //qParams.add(new BasicNameValuePair("sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext))));//签名，必填
        //log.info("---------sign---------:" + SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext)));
        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.fromObject(httpResult);
        } catch (Exception e) {
            log.info("融合下单接口接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }
    /**
     * 保存订单到数据库
     */
    private void saveOrderInfo(Map<String, String> orderMap,String ORDERSEQ) throws Exception {
        log.info("支付操作后保存数据到数据库");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OrderView orderView = new OrderView();
        orderView.setOrderSeq(ProduceIdUtil.getId()+"");// 订单号码
        orderView.setProductName(orderMap.get("productTitle"));    // 产品名称
        orderView.setOrderSetMeal(orderMap.get("order_set_meal"));    // 套餐
        orderView.setOrderUniversityName(orderMap.get("order_university_name"));    // 学校
        orderView.setOrderName(orderMap.get("orderName"));    // 姓名
        String orderDatetime = orderMap.get("orderDatetime");
        orderView.setOrderDate(df.parse(orderDatetime));    // 提交时间
        orderView.setStatus(orderMap.get("Status"));    // 订单状态
        orderView.setOrderRegion(orderMap.get("universityRegion"));    // 区域
        orderView.setIPay(orderMap.get("ipay"));    // 支付平台
        orderView.setPayType(orderMap.get("payType"));    // 支付方式
        orderView.setWebOrderAmount(orderMap.get("prices").replace("元", ""));    // 产品价格
        orderView.setCustomerId("xyzxyql");    // 接入商
        if (orderMap.get("orderTHD") != null) {
            orderView.setOrderseqThd(orderMap.get("orderTHD").toString());
        }
        orderView.setOrderPhone(orderMap.get("orderPhone"));    // 联系电话
        orderView.setOrderNumber(orderMap.get("orderNumber"));    // 身份证号码
        if (StringUtils.isBlank(orderMap.get("order_customer_student_id"))) {
            orderView.setOrderCustomerType("老师");    // 用户类别
        } else {
            orderView.setOrderCustomerType("学生");    // 用户类别
        }
        orderView.setOrderCustomerRemarks(orderMap.get("bussnessPhone"));
        orderView.setOrderCustomerStudentId(orderMap.get("order_customer_student_id")); // 学生证号
        orderView.setOrderCustomerAccount(orderMap.get("order_customer_account"));    // 多媒体账号
        orderView.setOrderCustomerPwd(orderMap.get("order_customer_pwd"));    // 多媒体密码

        orderViewMapper.insert(orderView);

        UserSchool userSchool = userSchoolMapper.selectById(orderMap.get("partner"));
        School school = schoolMapper.selectById(userSchool.getSchoolId());
        SysUser sysUser = sysUserMapper.selectById(userSchool.getUserId());

        if (orderMap.get("upStatus").equals("1")) {
            Order order = new Order();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            uuid = uuid.substring(1, 12);
            SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            order.setId(uuid);
            order.setOrderNumber("YRYM" + df2.format(new Date()) + (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 1000));
            order.setNetNumber(orderMap.get("order_customer_account"));
            order.setNetPassword(orderMap.get("order_customer_pwd"));
            order.setUserSchool(orderMap.get("order_university_name"));
            order.setHehuorenId(orderMap.get("partner"));
            order.setKdOrderId(orderMap.get("orderSeq"));
            order.setUserType("3");
            order.setBusinessNumber(orderMap.get("bussnessPhone"));
            order.setIdentifying(orderMap.get("identifying"));
            order.setCustomerName(orderMap.get("orderName"));
            order.setOrderStatus("审核中");
            order.setBusinessNumber(orderMap.get("orderPhone"));
            order.setContactNumber(orderMap.get("orderPhone"));
            order.setIdCard(orderMap.get("orderNumber"));
            order.setExpenses(orderMap.get("expenses"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setCreateTime(new Date());

            if (!school.equals(null)) {
                order.setHehuorenArea(school.getSubName());
                order.setHehuorenSchool(school.getSchoolName());
                order.setLzgh(school.getLzgh());
                order.setHehuorenName(sysUser.getName());
                order.setHehuorenPhone(sysUser.getPhone());
                order.setSupervisorName(sysUser.getName());
            }
            orderMapper.insert(order);

            OrderHistory history = new OrderHistory();
            history.setOrderId(uuid);
            history.setCreateDate(new Date());
            history.setStatus("资料已提交");
            historyMapper.insert(history);
        } else if (orderMap.get("upStatus").equals("2")) {
            // 毕业生办理
            Order order = new Order();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            uuid = uuid.substring(1, 12);
            order.setId(uuid);
            SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            order.setOrderNumber("YRYM" + df2.format(new Date()) + (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 1000));
            order.setNetNumber(orderMap.get("order_customer_account"));
            order.setNetPassword(orderMap.get("order_customer_pwd"));
            order.setUserSchool(orderMap.get("order_university_name"));
            order.setBusinessPackage("毕业生融合");
            order.setHehuorenId(orderMap.get("partner"));

            order.setKdOrderId(orderView.getOrderSeq());

            order.setUserType("9");
            if (orderMap.get("orderTHD") != null) {
                order.setOrderId(orderMap.get("orderTHD").toString());
            }
            if (orderMap.get("address") != null) {
                order.setAddress(orderMap.get("address").toString());
            }
            order.setSite(orderMap.get("site").toString());
            order.setBusinessNumber("");
            order.setCustomerName(orderMap.get("orderName"));
            order.setOrderStatus("审核中");
            order.setContactNumber(orderMap.get("orderPhone"));
            order.setIdCard(orderMap.get("orderNumber"));
            order.setExpenses("");
            order.setIdentifying(orderMap.get("identifying"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setCreateTime(new Date());
            order.setThStatus(orderMap.get("Status"));

            if (!school.equals(null)) {
                order.setHehuorenArea(school.getSubName());
                order.setHehuorenSchool(school.getSchoolName());
                order.setLzgh(school.getLzgh());
                order.setHehuorenName(sysUser.getName());
                order.setHehuorenPhone(sysUser.getPhone());
                order.setSupervisorName(sysUser.getName());
            }
            orderMapper.insert(order);
            OrderHistory history = new OrderHistory();
            history.setOrderId(uuid);
            history.setCreateDate(new Date());
            history.setStatus("资料已提交");
            historyMapper.insert(history);
        } else {
            Order order = new Order();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            uuid = uuid.substring(1, 12);
            order.setId(uuid);
            SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            order.setOrderNumber("YRYM" + df2.format(new Date()) + (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 1000));
            order.setNetNumber(orderMap.get("order_customer_account"));
            order.setNetPassword(orderMap.get("order_customer_pwd"));
            order.setUserSchool(orderMap.get("order_university_name"));
            order.setHehuorenId(orderMap.get("partner"));
            order.setKdOrderId(orderMap.get("orderSeq"));
            order.setUserType("5");
            order.setBusinessNumber("");
            order.setCustomerName(orderMap.get("orderName"));
            order.setOrderStatus("审核中");
            order.setContactNumber(orderMap.get("orderPhone"));
            order.setIdCard(orderMap.get("orderNumber"));
            order.setExpenses("");
            order.setIdentifying(orderMap.get("identifying"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setCreateTime(new Date());

            if (!school.equals(null)) {
                order.setHehuorenArea(school.getSubName());
                order.setHehuorenSchool(school.getSchoolName());
                order.setLzgh(school.getLzgh());
                order.setHehuorenName(sysUser.getName());
                order.setHehuorenPhone(sysUser.getPhone());
                order.setSupervisorName(sysUser.getName());
            }
            orderMapper.insert(order);
            OrderHistory history = new OrderHistory();
            history.setOrderId(uuid);
            history.setCreateDate(new Date());
            history.setStatus("资料已提交");
            historyMapper.insert(history);
        }
    }

    @RequestMapping(value = "getSaleId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    private JSONObject getSaleId(String productId, String currentTimeStr) throws Exception {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        Map<String, String> signMap = new HashMap<String, String>();//待签名参数
//        HttpHost proxy = new HttpHost("172.18.101.170", 3128);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(500000)
                .setConnectTimeout(500000).setConnectionRequestTimeout(500000)
//                .setProxy(proxy)
                .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));//签名，必填
        //qParams.add(new BasicNameValuePair("sign", SignUtil.exChange(SignUtil.md5EncodeSignature(plaintext))));//签名，必填
        JSONObject resultDataJson = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(qParams, "UTF-8"));
            log.info("提交参数:" + EntityUtils.toString(httpPost.getEntity(), "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            entity = response.getEntity();
            String httpResult = EntityUtils.toString(entity, "UTF-8");
            log.info("返回信息:" + httpResult);
            resultDataJson = JSONObject.fromObject(httpResult);
        } catch (Exception e) {
            log.info("---接口异常");
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultDataJson;
    }


    /**
     * 查询套餐信息（暂时弃用）
     * @param partner
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getTaoCanByType", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getTaoCanByType(String partner) {

        Wrapper<Product> productWrapper = new EntityWrapper<>();
        productWrapper.setSqlSelect(" product_id,product_title,product_creater,product_last_update_time,product_create_time," +
                "product_region,product_introduction_pic1,product_meal_price,product_set_meal_introduction,product_introduction," +
                "product_state,product_university,identifying,product_rf2,product_school_abbreviated,product_price,product_meal," +
                "product_rate,product_introduction_pic2,product_introduction_pic3,product_introduction_pic4," +
                "product_introduction_pic5,university_id ");
        if (StringUtils.isNotBlank(partner)){
            productWrapper.addFilter("product_university = '"+partner+"'");
        }
        Map<String, Object> productMap = productMapper.selectMaps(productWrapper).get(0);
        if (productMap == null || productMap.size() == 0) {
            return ResponseData.error("套餐不存在！");
        }

        /*String university_id = productMap.get("university_id").toString();

        Wrapper<UniversityInfo> universityInfoWrapper = new EntityWrapper<>();
        universityInfoWrapper.setSqlSelect(" * ");
        if(StringUtils.isNotBlank(university_id)){
            universityInfoWrapper.addFilter("university_id = '"+university_id+"'");
        }
        Map<String, Object> uniInfoMap = universityInfoMapper.selectMaps(universityInfoWrapper).get(0);
        */
        Map<String, Object> objMap = new HashMap<>();
        objMap.put("productMap",productMap);
        /*objMap.put("uniInfoMap",uniInfoMap);*/
        return ResponseData.success(objMap);
    }
}
