package com.yihu.wlyy.util;

import com.yihu.wlyy.entity.security.AccessToken;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.security.AccessTokenDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.Clock;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import static sun.management.Agent.error;

/**
 * Created by Reece on 2017/5/20.
 */
@Component
public class SendNews {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 模拟form表单的形式 ，上传文件 以输出流的形式把文件写入到url中，然后用输入流来获取url的响应
     *
     * @param url      请求地址 form表单url地址
     * @param filePath 文件在服务器保存路径
     * @return String 上传的图片地址
     * @throws IOException
     */
    public static String uploadImage(String url, String filePath) throws IOException {
        String result = null;
        File file = new File(filePath);
        System.out.println("file  ====> " + file);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }
        /**
         * 第一部分
         */
        URL urlObj = new URL(url);
        // 连接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        /**
         * 设置关键值
         */
        con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post方式不能使用缓存
        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "---------------------------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                + BOUNDARY);
        // 请求正文信息
        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // 必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\";filename=\""
                + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);
        // 文件正文部分
        // 把文件已流文件的方式 推入到url中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);

        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
            throw new IOException("数据读取异常");
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return result;
    }

    /**
     * 上传图文消息文字素材
     *
     * @param accessToken
     * @param data        图文消息文字素材内容
     * @return
     */
    public static String uploadNesText(String accessToken, String url, JSONObject data) throws Exception {
        url = url.replaceFirst("ACCESS_TOKEN", accessToken);
        //上传的图文消息数据，其中thumb_media_id是文件上传图片上传的id
        String result = HttpClientUtil.postBody(url, data);
        return result;
    }

    /**
     * 发送图文消息
     *
     * @param accessToken
     * @param openidData  群发图文消息内容
     * @return
     */
    public static String sendNewspMessage(String accessToken, String url, JSONObject openidData) throws Exception {
        url = url.replace("ACCESS_TOKEN", accessToken);
        String json = HttpClientUtil.postBody(url, openidData);
        return json;
    }

    public static void sendNews(String accessToken, List<String> openIds) throws Exception {
        // 配置信息
        Properties systemConf = SystemConf.getInstance().getSystemProperties();
        //本地上传图片的路径及跳转路径
        String renewPath = systemConf.getProperty("renew_path");
        String renewUrl = systemConf.getProperty("patient_sign_again_url");
        renewUrl = renewUrl.replaceAll("\\{server\\}", SystemConf.getInstance().getSystemProperties().getProperty("wechat_base_url"));
        renewUrl = renewUrl.replaceAll("\\{appId\\}", SystemConf.getInstance().getSystemProperties().getProperty("appId"));
        renewUrl = renewUrl.replaceAll("amp;","");
        renewUrl = renewUrl.replaceAll(";","&");

        String signPath = systemConf.getProperty("sign_path");
        String signUrl = systemConf.getProperty("doctor_subscribe_url");
        signUrl = signUrl.replaceAll("\\{server\\}", SystemConf.getInstance().getSystemProperties().getProperty("wechat_base_url"));
        signUrl = signUrl.replaceAll("\\{appId\\}", SystemConf.getInstance().getSystemProperties().getProperty("appId"));
        signUrl = signUrl.replaceAll("amp;","");
        signUrl = signUrl.replaceAll(";","&");

        String getMediaUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=image";//由sendUrl获取远程图片的mediaId
        String mediaurl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN";//ACCESS_TOKEN是获取到的access_token
        String groupUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";//根据openid发群发消息地址
        getMediaUrl = getMediaUrl.replace("ACCESS_TOKEN", accessToken);

        String renewImage = SendNews.uploadImage(getMediaUrl, renewPath);
        String signImage = SendNews.uploadImage(getMediaUrl, signPath);

        JSONObject newsTextData = new JSONObject();
        JSONArray newsText = new JSONArray();
//            续签图文
        JSONObject data = new JSONObject();
        data.put("thumb_media_id", new JSONObject(renewImage).get("media_id"));
        data.put("content_source_url", renewUrl);
        data.put("content", "家庭医生续签提醒");
        data.put("title", "家庭医生续签提醒");
        data.put("show_cover_pic", 1);
//            签约图文
        JSONObject data1 = new JSONObject();
        data1.put("thumb_media_id", new JSONObject(signImage).get("media_id"));
        data1.put("content_source_url", signUrl);
        data1.put("content", "欢迎关注厦门i健康，快来签约家庭医生吧~");
        data1.put("title", "欢迎关注厦门i健康，快来签约家庭医生吧~");
        data1.put("show_cover_pic", 1);

        newsText.put(data1);
        newsText.put(data);
        newsTextData.put("articles", newsText);
        String media = SendNews.uploadNesText(accessToken, mediaurl, newsTextData);

        JSONObject news = new JSONObject();
        JSONObject mapnews = new JSONObject();
        mapnews.put("media_id", new JSONObject(media).get("media_id"));

        news.put("touser", openIds);
        news.put("mpnews", mapnews);
        news.put("msgtype", "mpnews");
        news.put("send_ignore_reprint", 1);

        SendNews.sendNewspMessage(accessToken, groupUrl, news);
    }


}
