package com.malk.mc.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Extension;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/bot/")
public class McBotController {

    @Autowired
    private  DDClient_Extension ddClientExtension;
    @Autowired
    private DDClient ddClient;

    @PostMapping("groupMsg/send")
    public McR sendGroupMsg(@RequestBody JSONObject param){
        log.info("推送消息:{}",param);
        McException.assertParamException_Null(param,"msgParam","msgKey","openConversationId","robotCode","coolAppCode");
        Map map = ddClientExtension.sendGroupMessages(ddClient.getAccessToken(), param.getJSONObject("msgParam"), param.getString("msgKey"), param.getString("openConversationId")
                , param.getString("robotCode"), param.getString("coolAppCode"));
        return McR.success(map);
    }

    @PostMapping("card/createAndDeliver")
    public McR createAndDeliverCard(@RequestBody JSONObject param){
        log.info("推送消息:{}",param);
        McException.assertParamException_Null(param,"cardData","outTrackId","openSpaceId","robotCode","cardTemplateId");
        Map<String,Object> data = new HashMap();
        data.put("imGroupOpenDeliverModel",UtilMap.map("robotCode",param.getString("robotCode")));
        data.put("imGroupOpenSpaceModel",UtilMap.map("supportForward",true));
        if(param.containsKey("extInfo")){
            data.putAll(param.getJSONObject("extInfo"));
        }
        Map map = ddClientExtension.createAndDeliverCards(ddClient.getAccessToken(),param.getString("cardTemplateId"),param.getString("outTrackId"),
                UtilMap.map("cardParamMap",param.getJSONObject("cardData")),param.getString("openSpaceId"),data);
        return McR.success(map);
    }


    @PostMapping("msg")
    public McR msg(@RequestBody JSONObject param){
        log.info("机器人消息:{}",param);
        String text=param.getJSONObject("text").getString("content");
        if(text.contains("群信息")){
            sendBotTextMsgByWebhook(param.getString("sessionWebhook"),
                    "群ID："+param.getString("conversationId"));
        }
        return McR.success();
    }

    private void sendBotTextMsgByWebhook(String sessionWebhook,String text){
        Map<String,Object> map=new HashMap<>();
        map.put("msgtype","text");
        map.put("text",UtilMap.map("content",text));
        HttpUtil.createPost(sessionWebhook).body(JSONObject.toJSONString(map)).execute();
    }

    public static void main(String[] args) {
        String AppKey="949306";
        String UID="2195100110";
        String ForCorp="0";
        String AppSecurity="nG0#bSa5pCzt3!XuRC(:+$WM";
        String AppSecurityMd5=SecureUtil.md5(AppSecurity);
        System.out.println(AppSecurityMd5);
        System.out.println(getMD5Hash(AppSecurity));
//        String Signature=SecureUtil.md5(AppKey+UID+ForCorp+AppSecurityMd5);
//        System.out.println(Signature);
    }

    public static String getMD5Hash(String source) {
        StringBuilder sb = new StringBuilder();
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(source.getBytes());
            for (byte b : md5.digest()) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
