package com.ruoyi.common.weixin.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImgUpload;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.weixin.config.WeiXinConfig;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 微信相关工具类
 * @author Wzp
 */
@Component
public class WeiXinUtils {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(WeiXinUtils.class);

    @Resource
    private RedisCache redisCache;

    @Resource
    private WeiXinConfig weiXinConfig;




    /**
     * 获取access_token
     *
     * @return access_token
     */
    public String getAccessToken() {
        JSONObject jsonObject = new JSONObject();
        String accessToken = "";
        String redisKey = "XCX_ACCESS_TOKEN";
        try {
            if (redisCache.hasKey(redisKey)) {
                return redisCache.getCacheObject(redisKey).toString();
            }
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/token" +
                    "?grant_type=client_credential" +
                    "&appid="+weiXinConfig.getAppId() +
                    "&secret="+weiXinConfig.getAppSecret();
            String result = HttpUtil.get(requestUrl);

            jsonObject = JSONObject.parseObject(result);
            // 有效期(s)
            Integer expiresIn = 0;
            if (ObjectUtils.isNotEmpty(jsonObject)) {
                accessToken = jsonObject.getString("access_token");
                expiresIn = jsonObject.getInteger("expires_in");
            }
            if (StringUtils.isBlank(accessToken)){
                logger.error("小程序获取access_token失败 -> {"+ DateUtils.getTime()+": "+jsonObject+"}");
            }else {
                redisCache.setCacheObject(redisKey, accessToken, expiresIn, SECONDS);
            }
        } catch (Exception e) {
            logger.error("小程序获取access_token异常 -> {"+DateUtils.getTime()+": "+e.getMessage()+"}");
        }
        return accessToken;
    }

    /**
     * 小程序授权
     *
     * @param code 登录时获取的 code
     * @return 结果
     */
    public JSONObject getWebAuthorizeInfo(String code) {
        try {
            String requestUrl = "https://api.weixin.qq.com/sns/jscode2session" +
                    "?appid=" + weiXinConfig.getAppId() + "&" +
                    "secret=" + weiXinConfig.getAppSecret() + "&" +
                    "js_code=" + code + "&" +
                    "grant_type=authorization_code";
            String result = HttpUtil.get(requestUrl);

            return JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("小程序登录异常 -> "+DateUtils.getTime()+": "+e.getMessage()+"}");
        }
        return null;
    }

    /**
     * 获取用户手机号
     *
     * @param phoneCode 手机号获取凭证
     * @return 手机号
     */
    public String getUserPhoneNumber(String phoneCode) {
        String phoneNumber = "";
        try {
            // 请求地址
            String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+this.getAccessToken();
            // 请求参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", phoneCode);
            // 结果
            String res = HttpUtil.createPost(requestUrl).
                    body(jsonObject.toString()).execute().body();
            JSONObject result = JSONObject.parseObject(res);

            logger.info("请求手机号API----->" + result);
            if ("0".equals(result.getString("errcode"))) {
                JSONObject phone_info = result.getJSONObject("phone_info");
                phoneNumber = phone_info.get("phoneNumber").toString();
            }
            return phoneNumber;
        } catch (Exception e) {
            logger.error("请求手机号API异常 -> "+DateUtils.getTime()+": "+e.getMessage()+"}");
        }
        return phoneNumber;
    }

    /**
     * 获取小程序码
     *
     * @param memberUserId 用户id
     * @param key key
     * @return 图片链接
     */
    public String getQRCode(Long memberUserId, String key){
        String resultUrl = "";
        try {
            //获取token
            String accessToken = this.getAccessToken();
            String codeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token="+ accessToken;
            //post参数
            String path = weiXinConfig.getWxPath()+memberUserId;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("path", path);
            Map<String, Object> lineColor = new HashMap<>();
            lineColor.put("r", 4);
            lineColor.put("g", 157);
            lineColor.put("b", 150);
            jsonObject.put("line_color", lineColor);
            String env_version = "release";// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            jsonObject.put("env_version", env_version);
            String params = jsonObject.toString();

            URL url = new URL(codeUrl);
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            // 提交模式
            httpUrlConnection.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream());
            printWriter.write(params);
            printWriter.flush();
            //获取数据
            BufferedInputStream bis = new BufferedInputStream(httpUrlConnection.getInputStream());
            //文件上传,返回小程序码url
            resultUrl = new ImgUpload().streamUpload(bis, IdUtil.getSnowflakeNextIdStr()+"_"+key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUrl;
    }

//    public String getQRCode(Long memberUserId, String key){
//        String qrCodeUrl = "";
//        try {
//            //获取token
//            String accessToken = this.getAccessToken();
//            String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ accessToken;
//            String path = weiXinConfig.getWxPath()+memberUserId;
//            //post参数
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("path", path);
//            Map<String, Object> lineColor = new HashMap<>();
//            lineColor.put("r", 4);
//            lineColor.put("g", 157);
//            lineColor.put("b", 150);
//            jsonObject.put("line_color", lineColor);
//            String env_version = "release";// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
//            jsonObject.put("env_version", env_version);
//            String params = jsonObject.toString();
//
//            URL url = new URL(codeUrl);
//            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
//            // 提交模式
//            httpUrlConnection.setRequestMethod("POST");
//            // 发送POST请求必须设置如下两行
//            httpUrlConnection.setDoOutput(true);
//            httpUrlConnection.setDoInput(true);
//            // 获取URLConnection对象对应的输出流
//            PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream());
//            printWriter.write(params);
//            printWriter.flush();
//            //获取数据
//            BufferedInputStream bis = new BufferedInputStream(httpUrlConnection.getInputStream());
//            //文件上传,返回小程序码url
//            qrCodeUrl = new ImgUpload().streamUpload(bis, key);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return qrCodeUrl;
//    }

    /**
     * 获取不限制的小程序码
     *
     * @param memberUserId 用户id
     * @param key key
     * @return 图片链接
     */
    // public String getQRCode(Long memberUserId, String key){
    //     String qrCodeUrl = "";
    //     try {
    //         //获取token
    //         String accessToken = this.getAccessToken();
    //         String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ accessToken;
    //         String path = weiXinConfig.getWxPath()+memberUserId;
    //         //post参数
    //         JSONObject jsonObject = new JSONObject();
    //         jsonObject.put("path", path);
    //         Map<String, Object> lineColor = new HashMap<>();
    //         lineColor.put("r", 4);
    //         lineColor.put("g", 157);
    //         lineColor.put("b", 150);
    //         jsonObject.put("line_color", lineColor);
    //         String env_version = "release";
    //         jsonObject.put("env_version", env_version);
    //         String params = jsonObject.toString();
    //
    //         URL url = new URL(codeUrl);
    //         HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
    //         // 提交模式
    //         httpUrlConnection.setRequestMethod("POST");
    //         // 发送POST请求必须设置如下两行
    //         httpUrlConnection.setDoOutput(true);
    //         httpUrlConnection.setDoInput(true);
    //         // 获取URLConnection对象对应的输出流
    //         PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream());
    //         printWriter.write(params);
    //         printWriter.flush();
    //         //获取数据
    //         BufferedInputStream bis = new BufferedInputStream(httpUrlConnection.getInputStream());
    //         //文件上传,返回小程序码url
    //         qrCodeUrl = new ImgUpload().streamUpload(bis, key);
    //
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     return qrCodeUrl;
    // }

    /**
     * 获取学校小程序码
     *
     * @param schoolId
     * @param key key
     * @return 图片链接
     */
    public String getSchoolQRCode(Long schoolId, String key){
        String qrCodeUrl = "";
        try {
            //获取token
            String accessToken = this.getAccessToken();
            String codeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token="+ accessToken;
            String path = weiXinConfig.getSchoolPath() + schoolId;
            //post参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("path", path);
            Map<String, Object> lineColor = new HashMap<>();
            lineColor.put("r", 4);
            lineColor.put("g", 157);
            lineColor.put("b", 150);
            jsonObject.put("line_color", lineColor);
            String env_version = "release";// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            jsonObject.put("env_version", env_version);
            String params = jsonObject.toString();

            URL url = new URL(codeUrl);
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            // 提交模式
            httpUrlConnection.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream());
            printWriter.write(params);
            printWriter.flush();
            //获取数据
            BufferedInputStream bis = new BufferedInputStream(httpUrlConnection.getInputStream());
            //文件上传,返回小程序码url
            qrCodeUrl = new ImgUpload().streamUpload(bis, key);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCodeUrl;
    }

    /**
     * 获取不限制的小程序码
     *
     * @param parentId 用户id
     * @param key key
     * @return 图片链接
     */
    public String getUnLimitQRCode(Long parentId, String key){
        String qrCodeUrl = "";
        try {
            //获取token
            String accessToken = this.getAccessToken();
            String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ accessToken;
            String path = weiXinConfig.getWxPath();
            String scene = "parentId="+ parentId;
            boolean check_path = false; // 小程序未发布
            String env_version = "trial"; // 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            //post参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("scene", scene);
            System.out.println(scene);
            jsonObject.put("path", path);
            jsonObject.put("check_path", check_path);
            jsonObject.put("env_version", env_version);
            Map<String, Object> lineColor = new HashMap<>();
            lineColor.put("r", 4);
            lineColor.put("g", 157);
            lineColor.put("b", 150);
            jsonObject.put("line_color", lineColor);
            String params = jsonObject.toString();

            URL url = new URL(codeUrl);
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            // 提交模式
            httpUrlConnection.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream());
            printWriter.write(params);
            printWriter.flush();
            //获取数据
            BufferedInputStream bis = new BufferedInputStream(httpUrlConnection.getInputStream());

            //文件上传,返回小程序码url
            qrCodeUrl =  new ImgUpload().streamUpload(bis, key);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCodeUrl;
    }

    ///**
    // *  小程序录入发货信息
    // * @param paySn 支付单号(订单号)
    // * @param openId 支付人openid
    // * @param companyCode 物流公司编码
    // * @param expressCode 物流单号
    // * @param goodsSpec 商品描述
    // * @param receivePhone 收货人手机号
    // * @return 结果
    // */
    //public String deliveryInfo(String paySn, String openId ,String companyCode, String expressCode, String goodsSpec, String receivePhone){
    //   try {
    //       //获取token
    //       String accessToken = this.getAccessToken();
    //       String url = weiXinConfig.getDeliveryUrl() + accessToken;
    //
    //       // post参数
    //       JSONObject jsonObject = new JSONObject();
    //       HashMap<Object, Object> orderKey = new HashMap<>();
    //       orderKey.put("order_number_type" , 1);  // 1.使用下单商户号和商户侧单号；枚举值2.使用微信支付单号
    //       orderKey.put("mchid", weiXinConfig.getMchId()); // 商户号
    //       orderKey.put("out_trade_no", paySn);  // 内部订单支付单号
    //       jsonObject.put("order_key", orderKey);
    //       jsonObject.put("logistics_type", 1); // 1.物流配送,2.同城配送,3.虚拟商品,4.用户自提
    //       jsonObject.put("delivery_mode", 1); // 1.同意发货,2.分拆发货
    //       List<Map<String, Object>> shippingList = new ArrayList<>();
    //       // 物流信息
    //       Map<String, Object> shipping = new HashMap<>();
    //       shipping.put("tracking_no", expressCode ); // 物流单号
    //       shipping.put("express_company", companyCode);  // 物流公司编码
    //       shipping.put("item_desc", goodsSpec);  // 商品信息描述
    //       shippingList.add(shipping);
    //       HashMap<Object, Object> contact = new HashMap<>();
    //       //contact.put("consignor_contact"); // 寄件人电话
    //       contact.put("receiver_contact", receivePhone );  // 收件人电话
    //       shipping.put("contact", contact );
    //       jsonObject.put("shipping_list", shippingList);
    //
    //       jsonObject.put("upload_time", DateUtil.format(DateUtils.getNowDate(), "yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'"));
    //
    //       HashMap<Object, Object> payer = new HashMap<>();
    //       payer.put("openid", openId);
    //       jsonObject.put("payer", payer);
    //
    //       // 结果
    //       String res = HttpUtil.createPost(url).
    //               body(jsonObject.toString()).execute().body();
    //       JSONObject result = JSONObject.parseObject(res);
    //       logger.info("小程序发货信息录入结果: {}", res);
    //       if ("0".equals(result.getString("errcode"))){
    //           return "SUCCESS";
    //       }else{
    //           return "FAIL";
    //       }
    //   }catch (Exception e){
    //       e.printStackTrace();
    //   }
    //   return  "FAIL";
    //}

    //public static void main(String[] args) {
    //    String requestUrl = "https://api.weixin.qq.com/cgi-bin/token" +
    //            "?grant_type=client_credential" +
    //            "&appid=wx1af9a4981bdfb5c3&secret=e27278cbb8bbc0d00d8468155eaf7c71";
    //    String result = HttpUtil.get(requestUrl);
    //    JSONObject jsonObject1 = JSONObject.parseObject(result);
    //
    //    String url = "https://api.weixin.qq.com/wxa/sec/order/set_msg_jump_path?access_token="+jsonObject1.getString("access_token");
    //    JSONObject jsonObject = new JSONObject();
    //    jsonObject.put("path", "/pages/user/order/order?type=2");
    //    System.out.println(HttpUtil.post(url, jsonObject.toJSONString()));
    //}

}


