package com.sunxung.factoring.web.bankLink;

import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 银企直连路由类
 *
 * @author fengxuan
 * @email xuan.feng@changan-inkasso.com
 * @date 2021/1/12 10:37
 */
@Controller
public class BankLinkController {

    private static Logger log = LogManager.getLogger(BankLinkController.class);

    //银企直连获取推送列表URL
    private static final String GET_LIST_URL = "http://47.114.148.98:9666/flowPush/do_list";
    //银企直连发送推送消息URL
    private static final String SEND_URL = "http://47.114.148.98:9666/flowPush/sendPushInfo";
    //银企直连获取推送列表URL（测试）
    private static final String GET_LIST_URL_TEST = "http://localhost:8848/flowPush/do_list";
    //银企直连发送推送消息URL（测试）
    private static final String SEND_URL_TEST = "http://localhost:8848/flowPush/sendPushInfo";

    /**
     * 查询银企直连推送信息列表
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @param searchStatus 关联状态，0：未关联，1：已关联
     * @return
     * @throws Exception
     */
    @RequestMapping("/bankLink/getPushInfoList")
    @ResponseBody
    public Object getPushInfoList(String startTime,String endTime,String searchStatus,String page,String rows) {
        HashMap<String, String> map = new HashMap<>();
        map.put("page",page);
        map.put("rows",rows);
        if (startTime!=null){
            map.put("startTime",startTime);
        }
        if (endTime!=null){
            map.put("endTime",endTime);
        }
        if (searchStatus != null){
            map.put("searchStatus",searchStatus);
        }
        String result = null;
        try {
            result = sendGet(getUrlAsString(GET_LIST_URL,map));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询银企直连推送信息列表出现异常"+e);
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    /**
     * 发送推送消息
     * @param ids 推送消息ID集合
     * @return
     */
    @RequestMapping(value = "/bankLink/sendPushInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object sendPushInfo(String ids) {
        String[] idStr = ids.split(",");
        HashMap<String, String> map = new HashMap<>();

        map.put("ids",ids);

        String result = null;
        try {
            result = sendGet(getUrlAsString(SEND_URL,map));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("推送消息出现异常"+e);
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }


    public static String getUrlAsString(String url, Map<String, String> params) throws Exception {
        StringBuilder wholeUrl = new StringBuilder(url);
        if(params != null && !params.isEmpty()) {
            wholeUrl.append("?");
            for(Map.Entry<String, String> entry: params.entrySet()) {
                wholeUrl.append(entry.getKey());
                wholeUrl.append("=");
                wholeUrl.append(entry.getValue());
                wholeUrl.append("&");
            }
            wholeUrl = wholeUrl.deleteCharAt(wholeUrl.length() - 1);
        }
        return wholeUrl.toString();
    }

    /**
     * 向指定URL发送GET方法的请求
     * @param url 发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


}
