package com.weaver.seconddev.chapanda.feishu.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
public class Esb2FeishuSendMessageUtil{
    private final static Logger log = LoggerFactory.getLogger(Esb2FeishuSendMessageUtil.class);

    @Autowired
    private Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public Map<String, Object> senCardMessage(String template_id,String template_version_name,String openId, Map<String,Object> paraMap) {
        Map<String, Object> messageMap = new HashMap<String, Object>();


        List<String> defaultList = new ArrayList<String>();
        defaultList.add("templateId");
        defaultList.add("templateVersionName");
        defaultList.add("receiveId");

        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
            JSONObject templateVariable = new JSONObject();

            Iterator<Map.Entry<String, Object>> iterator = paraMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                String key = entry.getKey();
                String value = entry.getValue().toString();
                log.error("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                if(!defaultList.contains(key)){
                    templateVariable.put(key,value);
                }
            }

//            templateVariable.put("name,","石磊");
//            templateVariable.put("current_date,",sdf.format(new Date()));

            JSONObject data_Json = new JSONObject();
            data_Json.put("template_id",template_id);
            data_Json.put("template_version_name",template_version_name);
            data_Json.put("template_variable",templateVariable);

            JSONObject contentJson = new JSONObject();
            contentJson.put("type","template");
            contentJson.put("data",data_Json);

            JSONObject bodyJson = new JSONObject();
            bodyJson.put("receive_id",openId);
            bodyJson.put("msg_type","interactive");
            bodyJson.put("content", contentJson.toJSONString());
            String uuid = UUID.randomUUID().toString();
            bodyJson.put("uuid", uuid);

            log.error("bodyJson:{}",bodyJson.toJSONString());

            String message= doPostSendMessage(bodyJson.toJSONString(),token);
            if(StringUtils.isNotBlank(message)){
                JSONObject returnData = JSONObject.parseObject(message);
                if(returnData.containsKey("code")){
                    String code = returnData.getString("code");
                    if("0".equals(code)){
                        JSONObject dataJson = returnData.getJSONObject("data");
                        String chat_id = dataJson.getString("chat_id");
                        String msg_type = dataJson.getString("msg_type");
                        String message_id = dataJson.getString("message_id");
                        String create_time = dataJson.getString("create_time");

                        messageMap.put("chat_id",chat_id);
                        messageMap.put("msg_type",msg_type);
                        messageMap.put("message_id",message_id);
                        messageMap.put("create_time",create_time);
                    }
                }
            }
        }
        return messageMap;
    }




    public Map<String, Object> senTextMessage(String content,String openId) {
        log.error("senCardMessage start");
        Map<String, Object> messageMap = new HashMap<String, Object>();
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            JSONObject contentJson = new JSONObject();
            contentJson.put("text",content);

            String uuid = UUID.randomUUID().toString();
            JSONObject bodyJson = new JSONObject();
            bodyJson.put("receive_id",openId);
            bodyJson.put("msg_type","text");
            bodyJson.put("content", contentJson.toJSONString());
            bodyJson.put("uuid", uuid);

            System.out.println("bodyJson:"+bodyJson.toJSONString());

            String message= doPostSendMessage(bodyJson.toJSONString(),token);
            if(StringUtils.isNotBlank(message)){
                JSONObject returnData = JSONObject.parseObject(message);
                if(returnData.containsKey("code")){
                    String code = returnData.getString("code");
                    if("0".equals(code)){
                        JSONObject dataJson = returnData.getJSONObject("data");
                        String chat_id = dataJson.getString("chat_id");
                        String msg_type = dataJson.getString("msg_type");
                        String message_id = dataJson.getString("message_id");
                        String create_time = dataJson.getString("create_time");

                        messageMap.put("chat_id",chat_id);
                        messageMap.put("msg_type",msg_type);
                        messageMap.put("message_id",message_id);
                        messageMap.put("create_time",create_time);

                    }
                }
            }
        }
        return messageMap;
    }


    public String doPostSendMessage(String bodyData,String token){
        String msg = "";

        // https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id
        // t-g1046ofDRKNCIEO3YKB42MQCDBZCYZGWAROROPGJ

//        bodyData = "{\n  \"receive_id\": \"ou_f2ee4ea6545e537c426fa058c31bab88\",\n  \"msg_type\": \"interactive\",\n  \"content\": \"{\\\"type\\\":\\\"template\\\",\\\"data\\\":{\\\"template_id\\\":\\\"AAqIMF4quXR02\\\",\\\"template_version_name\\\":\\\"1.0.1\\\",\\\"template_variable\\\":{\\\"name\\\":\\\"王文猛\\\",\\\"current_date\\\":\\\"06-24\\\"}}}\"\n}" ;

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyData);
        try {
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.messageUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            msg = response.body().string();
            log.error("msg:{}",msg);
        } catch (IOException e) {
            log.error("e:{}",e);
            throw new RuntimeException(e);
        }
        return msg;
    }

//
//    /**
//     * 获取token
//     *
//     * @return
//     */
//    public String getToken() {
//        String token = (String) baseCache.get(FeishuTokenModuleKey.FENSHUTOKEN_DATACENTER, FeishuTokenCacheKey.FEISHU_TOKEN);
//        log.error("token:{}",token);
//        if (StringUtils.isBlank(token)) {
//            JSONObject returnData = getAccessToken();
//            if(returnData.containsKey("tenantAccessToken")){
//                token = returnData.getString("tenantAccessToken");
//                int expire = returnData.getInteger("expire");
//
//                log.error("token:{}",token);
//                log.error("expire:{}",expire);
//
//                if(expire > 0){
//                    baseCache.set(FeishuTokenModuleKey.FENSHUTOKEN_DATACENTER, FeishuTokenCacheKey.FEISHU_TOKEN, token, expire);
//                }
//            }
//        }
//        return token;
//    }
//
//
//    public String getToken2() {
//        String token = "";
//        JSONObject returnData = getAccessToken();
//        if(returnData.containsKey("tenantAccessToken")){
//            token = returnData.getString("tenantAccessToken");
//        }
//        System.out.println("token:"+token);
//        return token;
//    }
//
//    /**
//     *
//     * @return
//     */
//    public JSONObject getAccessToken() {
//
//        // https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal
//        JSONObject returnData = new JSONObject();
//        JSONObject dataJson = new JSONObject();
//        dataJson.put("app_id", Constants.app_id);
//        dataJson.put("app_secret", Constants.app_secret);
//
//        log.error("dataJson:{}",dataJson.toJSONString());
////        dataJson.put("app_id", "cli_a8d0ee6b667dd00e");
////        dataJson.put("app_secret", "UjShC4eY7vCgHsQvFWZZleVdCqSEWGD0");
//
//        try {
//            OkHttpClient client = new OkHttpClient().newBuilder()
//                    .build();
//            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
//            RequestBody body = RequestBody.create(mediaType, dataJson.toJSONString());
//            Request request = new Request.Builder()
//                    .url(Constants.feishuHost+Constants.tokenUrl)
//                    .method("POST", body)
//                    .addHeader("Content-Type", "application/json; charset=utf-8")
//                    .build();
//            Response response = client.newCall(request).execute();
//            int code = response.code();
//            String msg = response.body().string();
//
//            log.error("code:{}",code);
//            log.error("msg:{}",msg);
//
//            if(code == 200){
//                if(StringUtils.isNotBlank(msg)){
//                    JSONObject returnJson = JSONObject.parseObject(msg);
//                    if(returnJson.containsKey("code")){
//                        String dataCode = returnJson.getString("code");
//                        if("0".equals(dataCode)){
//                            String tenantAccessToken = returnJson.getString("tenant_access_token");
//                            int expire = returnJson.getInteger("expire");
//
//                            log.error("tenantAccessToken:{}",tenantAccessToken);
//                            log.error("expire:{}",expire);
//
//                            returnData.put("tenantAccessToken",tenantAccessToken);
//                            returnData.put("expire",expire - earlySecond);
//                        }
//                    }
//                }
//            }else{
//                log.error("msg:{}",msg);
//            }
//        } catch (Exception e) {
//            log.error("msg:{}",e.getMessage());
//            e.printStackTrace();
//        }
//        return returnData;
//    }
//
//
//    /**
//     *
//     * @param bodyData
//     * @param token
//     * @return
//     */

//
//    public static void main(String[] args) {
//
//        String feishuHost = "https://open.feishu.cn";
//        String tokenUrl = "/open-apis/auth/v3/tenant_access_token/internal";
//        String feishuUrl = "/open-apis/im/v1/messages?receive_id_type=open_id";
//        String app_id = "cli_a8d0ee6b667dd00e";
//        String app_secret = "UjShC4eY7vCgHsQvFWZZleVdCqSEWGD0";
//        String template_id = "AAqIMF4quXR02" ;
//        String template_version_name = "1.0.1";
//        String receiveId = "ou_8ff7816cfa8cda57643cac2a06fbdc7e";
//
//        Esb2FeishuSendMessageUtil esb2FeishuSendMessageUtil = new Esb2FeishuSendMessageUtil();
//        esb2FeishuSendMessageUtil.senCardMessage(template_id, template_version_name,receiveId);
//    }
}
