package com.iotechn.unimall.biz.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.iotechn.unimall.data.domain.UserDO;
import com.iotechn.unimall.data.mapper.UserMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.*;

@Component
public class SendUtils {
    @Autowired
    private UserMapper userMapper;
    @Value("${com.iotechn.unimall.wx.gongzhonghao.app-id}")
    private String gzhAppId;
    @Value("${com.iotechn.unimall.wx.gongzhonghao.app-secret}")
    private String gzhAppSecret;
    @Value("${com.iotechn.unimall.wx.mini.app-id}")
    private String minAppId;

    private OkHttpClient okHttpClient = new OkHttpClient();

    //这里建议用多线程来做，否则容易卡。
    /**
     * @Description
     * 交易审核信息
     * @param @param pro_ota_id
     * @param @param flag
     * @param @return
     * @throws
     * @author gdc
     */
    public  String sendMessage(Map<String, Object> map)  throws Exception{
        UserDO userDO =  userMapper.selectById(String.valueOf(map.get("userId")));
        List<Map<String, Object>> accessTokenList = new ArrayList<>();
        if(userDO == null || userDO.getAccessToken() == null){
            return "";
        }
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getAccessToken(userDO.getId())+"";
        JSONObject json = new JSONObject();
//        List<Map<String, Object>> infoList = new ArrayList<>();

        //根据出差申请id获取要推送的审批人union-再根据审批人的union找到审批人的公众号openid，进行推送
//        infoList = pushDao.getOpenId(pro_ota_id,flag);
//        for(int i=0;i<infoList.size();i++){ //循环推送
        json.put("touser",  userDO.getOfficialOpenId());//所a要发送的用户openId
        json.put("template_id", map.get("templateId"));
        json.put("page", map.get("page"));//点击模板可以跳转到小程序的具体界面
        //json.put("form_id", formId);//用户的fromId或者预订单Id
        JSONObject jo = new JSONObject();
        jo.put("appid",minAppId);
        jo.put("pagepath", map.get("page"));
        json.put("miniprogram", jo);
        json.put("topcolor", "#173177");
        json.put("data", JsonMsg(map));//这个data可以直接调用上文的JsonMsg方法生成所需要发送给用户的信息

        String result = httpsRequest(tmpurl, "GET", json.toString()); //注意推送需要是get模式
        JSONObject resultJson = JSON.parseObject(result);

        System.out.println("模板消息返回数据:"+resultJson);
//            String errmsg = (String) resultJson.get("errmsg");
//        }
        return "success";
    }

    /**
     * @param map
     * @method packJsonmsg
     * @参数@param first  头部
     * @参数@param remark  说明
     * @参数@return
     * @返回类型：JSONObject
     */
    public  JSONObject JsonMsg(Map<String, Object> map){
        JSONObject json = new JSONObject();
        try {
            JSONObject jsonFirst = new JSONObject();
            jsonFirst.put("value", map.get("header"));
            jsonFirst.put("color", "#173177");
            json.put("first", jsonFirst);
            /**
             * 信息部分JSON
             */
            JSONObject k1 = new JSONObject();
            k1.put("value",  map.get("userName"));
            k1.put("color", "#173177");
            json.put("keyword1", k1);
            JSONObject k2 = new JSONObject();
            k2.put("value", map.get("result"));
            k2.put("color", "#173177");
            json.put("keyword2", k2);
            JSONObject k3 = new JSONObject();
            k3.put("value", map.get("time"));
            k3.put("color", "#173177");
            json.put("keyword3", k3);
            //具体模板消息有几个参数就写几个 可查看小程序后台模板消息
            JSONObject jsonRemark = new JSONObject();
            jsonRemark.put("value", "请进入小程序（我的-我的合同）进行查看");
            jsonRemark.put("color", "#173177");
            json.put("remark", jsonRemark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }
    /****************************************************************  keyword2  **********************************************/

    /**
     * @Description
     * 订单发货提醒
     * @param @param pro_ota_id
     * @param @param flag
     * @param @return
     * @throws
     * @author gdc
     */
    public  String sendMessageForDeliver(Map<String, Object> map) {
        UserDO userDO =  userMapper.selectById(String.valueOf(map.get("userId")));
        List<Map<String, Object>> accessTokenList = new ArrayList<>();
        if(userDO == null || userDO.getAccessToken() == null){
            return "";
        }
        try {
            String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(userDO.getId()) + "";
            JSONObject json = new JSONObject();
            //根据出差申请id获取要推送的审批人union-再根据审批人的union找到审批人的公众号openid，进行推送
            json.put("touser", userDO.getOfficialOpenId());//所a要发送的用户openId
            json.put("template_id", map.get("templateId"));
            json.put("page", map.get("page"));//点击模板可以跳转到小程序的具体界面
            //json.put("form_id", formId);//用户的fromId或者预订单Id
            JSONObject jo = new JSONObject();
            jo.put("appid", minAppId);
            jo.put("pagepath", map.get("page"));
            json.put("miniprogram", jo);
            json.put("topcolor", "#173177");
            json.put("data", JsonMsgForDeliver(map));//这个data可以直接调用上文的JsonMsg方法生成所需要发送给用户的信息

            String result = httpsRequest(tmpurl, "GET", json.toString()); //注意推送需要是get模式
            JSONObject resultJson = JSON.parseObject(result);

            System.out.println("模板消息返回数据:" + resultJson);
        }
        catch (Exception e){
            return "NG";
        }
        //            String errmsg = (String) resultJson.get("errmsg");
//        }
        return "success";
    }

    /**
     * @param map
     * @method packJsonmsg
     * @参数@param first  头部
     * @参数@param remark  说明
     * @参数@return
     * @返回类型：JSONObject
     */
    public  JSONObject JsonMsgForDeliver(Map<String, Object> map){
        JSONObject json = new JSONObject();
        try {
            JSONObject jsonFirst = new JSONObject();
            jsonFirst.put("value",  map.get("header"));
            jsonFirst.put("color", "#173177");
            json.put("first", jsonFirst);
            /**
             * 信息部分JSON
             */
            JSONObject k1 = new JSONObject();
            k1.put("value",  map.get("value"));
            k1.put("color", "#173177");
            json.put("keyword1", k1);
            JSONObject k2 = new JSONObject();
            k2.put("value", map.get("valueOne"));
            k2.put("color", "#173177");
            json.put("keyword2", k2);
//            JSONObject k3 = new JSONObject();
//            k3.put("value", map.get("time"));
//            k3.put("color", "#173177");
//            json.put("keyword3", k3);
            //具体模板消息有几个参数就写几个 可查看小程序后台模板消息
            JSONObject jsonRemark = new JSONObject();
            jsonRemark.put("value", map.get("remark"));
            jsonRemark.put("color", "#173177");
            json.put("remark", jsonRemark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }


    /****************************************************************  keyword3  **********************************************/

    /**
     * @Description
     * 订单发货提醒
     * @param @param pro_ota_id
     * @param @param flag
     * @param @return
     * @throws
     * @author gdc
     */
    public  String sendMessageForNotice(Map<String, Object> map){
        UserDO userDO =  userMapper.selectById(String.valueOf(map.get("userId")));
        List<Map<String, Object>> accessTokenList = new ArrayList<>();
        if(userDO == null){
            return "";
        }
         try {
             String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(userDO.getId()) + "";
             JSONObject json = new JSONObject();
             //根据出差申请id获取要推送的审批人union-再根据审批人的union找到审批人的公众号openid，进行推送
             json.put("touser", userDO.getOfficialOpenId());//所a要发送的用户openId
             json.put("template_id", map.get("templateId"));
             json.put("page", map.get("page"));//点击模板可以跳转到小程序的具体界面
             //json.put("form_id", formId);//用户的fromId或者预订单Id
             JSONObject jo = new JSONObject();
             jo.put("appid", minAppId);
             jo.put("pagepath", map.get("page"));
             json.put("miniprogram", jo);
             json.put("topcolor", "#173177");
             json.put("data", JsonMsgForNotice(map));//这个data可以直接调用上文的JsonMsg方法生成所需要发送给用户的信息

             String result = httpsRequest(tmpurl, "GET", json.toString()); //注意推送需要是get模式
             JSONObject resultJson = JSON.parseObject(result);

             System.out.println("模板消息返回数据:" + resultJson);
//            String errmsg = (String) resultJson.get("errmsg");
//        }
             return "success";
         }
         catch (Exception e){
             return "NG";
         }
    }

    /**
     * @param map
     * @method packJsonmsg
     * @参数@param first  头部
     * @参数@param remark  说明
     * @参数@return
     * @返回类型：JSONObject
     */
    public  JSONObject JsonMsgForNotice(Map<String, Object> map){
        JSONObject json = new JSONObject();
        try {
            JSONObject jsonFirst = new JSONObject();
            jsonFirst.put("value",  map.get("header"));
            jsonFirst.put("color", "#173177");
            json.put("first", jsonFirst);
            /**
             * 信息部分JSON
             */
            JSONObject k1 = new JSONObject();
            k1.put("value",  map.get("value"));
            k1.put("color", "#173177");
            json.put("keyword1", k1);
            JSONObject k2 = new JSONObject();
            k2.put("value", map.get("valueOne"));
            k2.put("color", "#173177");
            json.put("keyword2", k2);
            JSONObject k3 = new JSONObject();
            k3.put("value", map.get("valueTwo"));
            k3.put("color", "#173177");
            json.put("keyword3", k3);
            //具体模板消息有几个参数就写几个 可查看小程序后台模板消息
            JSONObject jsonRemark = new JSONObject();
            jsonRemark.put("value", map.get("remark"));
            jsonRemark.put("color", "#173177");
            json.put("remark", jsonRemark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }
    /**
     * @Description
     * 打款通知
     * @param @param pro_ota_id
     * @param @param flag
     * @param @return
     * @throws
     * @author gdc
     */
    public  String sendMessageForPay(Map<String, Object> map)  throws Exception{
        UserDO userDO =  userMapper.selectById(String.valueOf(map.get("userId")));
        List<Map<String, Object>> accessTokenList = new ArrayList<>();
        if(userDO == null){
            return "";
        }
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getAccessToken(userDO.getId())+"";
        JSONObject json = new JSONObject();
        //根据出差申请id获取要推送的审批人union-再根据审批人的union找到审批人的公众号openid，进行推送
        json.put("touser",  userDO.getOfficialOpenId());//所a要发送的用户openId
        json.put("template_id", map.get("templateId"));
        json.put("url", map.get("url"));//点击查看凭证
        //json.put("form_id", formId);//用户的fromId或者预订单Id
//        JSONObject jo = new JSONObject();
//        jo.put("appid",minAppId);
//        jo.put("pagepath", map.get("page"));
//        json.put("miniprogram", jo);
        json.put("topcolor", "#173177");
        json.put("data", JsonMsgForNotice(map));//这个data可以直接调用上文的JsonMsg方法生成所需要发送给用户的信息

        String result = httpsRequest(tmpurl, "GET", json.toString()); //注意推送需要是get模式
        JSONObject resultJson = JSON.parseObject(result);

        System.out.println("模板消息返回数据:"+resultJson);
//            String errmsg = (String) resultJson.get("errmsg");
//        }
        return "success";
    }



    /**
     * http请求方法
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public  String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}");
        } catch (Exception e) {
            System.out.println("https请求异常：{}");
        }
        return null;
    }



    /*
     * 获取accesstoken
     * (non-Javadoc)
     * @see com.yspro.service.PubUserService#getAccessToken()
     */
    public String getAccessToken(Long userId)throws Exception {
        UserDO userDO = userMapper.selectById(userId);
        Date now = new Date();
        Long diff = now.getTime() - userDO.getGmtUpdate().getTime();
        String accessToken = "";
        if(diff > 7200 || userDO.getAccessToken() == null || userDO.getAccessToken().isEmpty()){
            String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+gzhAppId+"&secret="+gzhAppSecret;
            String code = okHttpClient.newCall(new Request.Builder().url(url).get().build()).execute().body().string();
            JSONObject jsonObject = JSONObject.parseObject(code);

            System.out.println("jsonObject的值为："+jsonObject);
            Integer errcode = jsonObject.getInteger("errcode");
            accessToken=jsonObject.getString("access_token");
            String expires_in = jsonObject.getString("expires_in");
            userDO.setGmtUpdate(now);
            userDO.setAccessToken(accessToken);
            userMapper.updateById(userDO);
            System.out.println("accessToken的值为："+accessToken+",过期时间为："+expires_in);
        }
        else{
            accessToken = userDO.getAccessToken();
        }
        return accessToken;
    }
}
