package com.ghy.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.config.WxConfig;
import com.ghy.common.enums.WxMsgEnum;
import com.ghy.common.enums.WxStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 但星霖
 * @Date 2023-09-23 10：35：41
 * 说明：微信消息工具类
 */
@Slf4j
@Component
public class WechatMsgUtils {

    @Autowired
    private static WxConfig wxConfig;

    static final String appid = "wx404f2439a8c24e15";
    static final String appsecret = "49ade04a817067fe2d65ab2f17afce75";


    /**
     * 获取token
     * token有效期暂定
     * 方便后面存储为redis数据使用。
     */
    public static String getToken() {
        // 接口地址拼接参数
        String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
        String tokenJsonStr = doGetPost(getTokenApi, "GET", null);
        JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
        log.info("获取到的token返回json内容: {} ", tokenJson);
        String token = tokenJson.get("access_token").toString();
        log.info("获取到用户token:{}", token);
        return token;
    }

    private void setConfig(String token){

    }

    /**
     * 推送消息
     *
     * @param dataMap    消息内容
     * @param mesType    消息类型-- 后面补充为枚举数据
     * @param userOpenId 用户openId
     * @param token      鉴权token信息
     */
    public static void sendWeChatMsg(String token, String userOpenId, WxMsgEnum mesType, Map<String, Object> dataMap) {
        String type=mesType+"";
        String  wxStatusByWxMsgUrl=getWxStatusByWxMsg(WxStatusEnum.valueOf(type));
        if (StringUtils.isEmpty(wxStatusByWxMsgUrl)){
            wxStatusByWxMsgUrl="/pages/order-manage/order-manage";
        }
        log.info("传入的参数值{}，获取到的url{}",type,wxStatusByWxMsgUrl);
        // 接口地址
        String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("touser", userOpenId);
        paramMap.put("page", "index");
        paramMap.put("template_id", mesType.getTempCode());
        paramMap.put("url","");
       Map<String, Object> miniprogram=new HashMap<>();
       miniprogram.put("appid","wx105ce607b514ff2a");
       miniprogram.put("pagepath",wxStatusByWxMsgUrl);
       paramMap.put("miniprogram",miniprogram);
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<String, Object> objectEntry : dataMap.entrySet()) {
            JSONObject model = new JSONObject();
            model.put("value", objectEntry.getValue());
            jsonObject.put(objectEntry.getKey(), model);
        }
        paramMap.put("data", jsonObject);
        String reposont = doGetPost(sendMsgApi, "POST", paramMap);
        log.info("reposont:{}", reposont);
        log.info("用户：{}消息：{}推送返回谁：{}", userOpenId, paramMap.toString(),reposont);
    }

    /**
     * 调用接口 post
     *
     * @param apiPath
     */
    public static String doGetPost(String apiPath, String type, Map<String, Object> paramMap) {
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try {
            // 创建连接
            URL url = new URL(apiPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod(type);
            // 设置接收数据的格式
            connection.setRequestProperty("Accept", "application/json");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            if (type.equals("POST")) {
                // utf-8编码
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                out.append(JSON.toJSONString(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            // 获取长度
            int length = (int) connection.getContentLength();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                // utf-8编码
                result = new String(data, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
   public  static String getWxStatusByWxMsg(WxStatusEnum type){
        return type.getTempCode();
   }
}
