package com.ruoyi.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.utils.wx.wecom.AesException;
import com.ruoyi.utils.wx.wecom.ConstantUtil;
import com.ruoyi.utils.wx.wecom.WXBizMsgCrypt;
import com.ruoyi.vo.RyController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api")
@Api(tags = "企业微信")
@Slf4j
public class ApiWeComController extends RyController {

    public static void main(String[] args) {
        sendMessage();
    }

    /**
     * 获取access_token
     *
     * @return
     */
    public static String getToken() {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" + "?corpid=" + "ww45fb4d72c735ee1d" + "&corpsecret=" + "5x3F-AHQMO9VwpXH9_lOUX8887sqb1fUx0-5goN6U_Y";
        String result = HttpRequest.get(url).execute().body();
        System.err.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //服务断了status会有值
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode == 0) {
            String access_token = (String) jsonObject.get("access_token");
            return access_token;
        }
        return "";
    }

    /**
     * 发送消息
     */
    public static void sendMessage() {
//        Map map = new HashMap();
//        map.put("touser", "liwenlong");
//        map.put("toparty", "@all");
//        map.put("totag", "@all");
//        map.put("msgtype", "text");
//        map.put("agentid", "1000003");
//        Map map1 = new HashMap();
//        map1.put("content", "测试消息同步肯定接口接口的肌肤的接口的加快进度看即可当借款方的接口接口对接付款即可 肯德基咖啡机 就连接口对接发空间打开健康的风景\n软云");
//        map.put("text", map1);
//        String s = JSONObject.toJSONString(map);
//        String result = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + getToken()+"&debug=1")
//                .header("Content-Type", "application/json;charset=utf-8")
//                .body(s).execute().body();
//        System.err.println(result);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        Integer errcode = (Integer) jsonObject.get("errcode");
//        if (errcode == 0) {
//            System.out.println("消息发送成功");
//        }

//        //根据手机号获取userid
        Map map = new HashMap();
        map.put("mobile", "15855540307");
        String body = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + getToken() + "&debug=1")
                .header("Content-Type", "application/json;charset=utf-8")
                .body(JSONObject.toJSONString(map)).execute().body();
        System.out.println(body);

//        //根据邮箱获取userid
//        Map map = new HashMap();
//        map.put("email", "3350632748@qq.com");
//        map.put("email_type", 1);
//        String body = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/user/get_userid_by_email?access_token=" + getToken() + "&debug=1")
//                .header("Content-Type", "application/json;charset=utf-8")
//                .body(JSONObject.toJSONString(map)).execute().body();
//        System.out.println(body);


//        //获取用户列表
//        Map map = new HashMap();
//        map.put("cursor", "");
//        map.put("limit", 10000);
//        String body = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token=" + getToken() + "&debug=1")
//                .header("Content-Type", "application/json;charset=utf-8")
//                .body(JSONObject.toJSONString(map)).execute().body();
//        System.out.println(body);



    }


    @GetMapping("/weCom")
    @ApiOperation(value = "企业微信回调地址", notes = "企业微信回调地址")
    public Object weCom(HttpServletRequest request, @RequestBody(required = false) String body) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String jsonstring = JSONObject.toJSONString(parameterMap);
        log.info("企业微信回调参数:{}, 解析参数:{}", jsonstring, body);
        if (body == null) {
            return verificationUrl(request);
        }
        Map<String, String> resultMap = getRequestParameter(request, body);
        System.out.println(resultMap);
        return "success";
    }


    public Object verificationUrl(HttpServletRequest request) {
        String signature = request.getParameter("msg_signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        // 验证完整性
        log.info("=========验证URL有效性开始=========");
        String sEchostr; //需要返回的明文
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("token", "aeskey", "id");
            log.info("企业微信加密签名:{},时间戳:{},随机数:{},加密的字符串:{}", signature, timestamp, nonce, echostr);
            sEchostr = wxcpt.VerifyURL(signature, timestamp, nonce, echostr);
            log.info("给企业微信返回的明文,{}", sEchostr);
            log.info("=========验证URL有效性结束=========");
            return sEchostr;
        } catch (AesException e) {
            log.error("验证URL失败，错误原因请査看异常:{}", e.getCode());
            e.printStackTrace();
            return "error";
        }

    }


    public Map<String, String> getRequestParameter(HttpServletRequest request, String body) {
        log.info("=========参数解析开始=====");
        Map<String, String> resultMap = new HashMap<>(16);
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("token", "aesKey", "id");
            String msgSignature = request.getParameter("msg_signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            log.info("企业微信加密签名:{},时间戳:{},随机数:{}", msgSignature, timestamp, nonce);
            String sMsg = wxcpt.DecryptMsg(msgSignature, timestamp, nonce, body);
            ConstantUtil.parseXmlToMap(sMsg, resultMap);
            log.info("decrypt密文转为map结果为{}", resultMap);
            log.info("=========参数解析结束=========");
        } catch (AesException e) {
            log.error("密文参数解析失败，错误原因请査看异常:{}", e.getMessage());
        }
        return resultMap;
    }


}
