package com.hr.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yy.basedevelop.common.util.ruoyi.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class FeishuMsgSendService {

    //构建发送飞书提醒
    private final static String accessToken = "f60b2c6a-56df-4b89-8875-30554fd2dbc1";
    private final static String accessToken_IpRobot = "4a5912a9-c19b-4caf-9151-326e3fd6da31";
    private final static String accessToken_IpRobotSec = "BVFVjvVmLDS7tbG7IdOWLd";

    @Autowired
    private Environment environment;
    @Value("${spring.application.name}")
    private String name;

    private static final Map<String,String> profilemap = new HashMap<String,String>(){{
        put("pre","测试");
        put("pretask","测试Task");
        put("prod2","诚易融");
        put("prod","诚易融");
        put("prodtask","诚易融Task");
        put("walletprod","惠融钱包");
        put("walletprodtask","惠融钱包Task");}};
    //这个是正式的
    private final static String accessToken_ReleaseRobot = "3e7c863f-cb5f-4fc9-addb-c64664808ff5";
    private final static String accessToken_ReleaseRobotSec = "WOHJHO6eBU3cRdOlRb9g9d";

    //这个是测试的
//    private final static String accessToken_ReleaseRobot = "5b4c51b1-d530-4fb9-952c-b073083413d4";
//    private final static String accessToken_ReleaseRobotSec = "3WZEWpISOajKCQwdEGg7Pg";


    /**
     * 处理发送的飞书消息
     * @param textMsg
     */
    private void dealFeishuMsgSend(String textMsg) {
        try {
//            String proFile = environment.getActiveProfiles()[0];
//            if (proFile.indexOf("prod")>=0) {
                HttpClient httpclient = HttpClients.createDefault();
                String WEBHOOK_TOKEN = "https://open.feishu.cn/open-apis/bot/v2/hook/" + accessToken;
                HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
                httppost.addHeader("Content-Type", "application/json; charset=utf-8");
                StringEntity se = new StringEntity(textMsg, "utf-8");
                httppost.setEntity(se);

                HttpResponse response = httpclient.execute(httppost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String result = EntityUtils.toString(response.getEntity(), "utf-8");
                    log.info("【发送飞书群消息】消息响应结果：" + JSON.toJSONString(result));
                }
//            }
        } catch (Exception e) {
            log.error("【发送飞书群消息】error：" + e.getMessage(), e);
        }
    }

    private void dealFeishuMsgSend(String textMsg,String token) {
        try {
//            String proFile = environment.getActiveProfiles()[0];
//            if (proFile.indexOf("prod")>=0) {
            log.info("目标token为：{}",token);
            HttpClient httpclient = HttpClients.createDefault();
            String WEBHOOK_TOKEN = "https://open.feishu.cn/open-apis/bot/v2/hook/" + token;
            HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
            StringEntity se = new StringEntity(textMsg, "utf-8");
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                log.info("【发送飞书群消息】消息响应结果：" + JSON.toJSONString(result));
            }
//            }
        } catch (Exception e) {
            log.error("【发送飞书群消息】error：" + e.getMessage(), e);
        }
    }
    /**
     * 发送异常消息
     * @param e
     */
    public void sendErrorMsg(Exception e)  {
        String msg = intercept(getStackTraceInfo(e));
        String proFile = environment.getActiveProfiles()[0];
        String content = "[系统异常]["+ name +"]["+ proFile +"]["+ DateUtils.getTime()+"]：" + msg ;
        JSONObject json = new JSONObject();
        json.put("msg_type","text");
        json.put("content",new JSONObject(){{
            put("text",content);
        }});
        String textMsg = JSON.toJSONString(json);
        dealFeishuMsgSend(textMsg);
    }

    /**
     * 获取异常信息
     */
    public String getStackTraceInfo(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            return sw.toString();
        } finally {
            try {
                pw.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                sw.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private String intercept(String content) {
        try {
            if (content.getBytes().length>=20000) {
                return new String(content.getBytes(),0,20000,"utf-8");
            }return content;
        } catch (Exception e) {
            return content;
        }
    }

    /**
     * 发送系统消息
     *
     * @param content
     */
    public void sendSystemMsg( String content) {
        String proFile = environment.getActiveProfiles()[0];
        String msg = "[系统通知]["+ name +"]["+ proFile +"]" + content;
        JSONObject json = new JSONObject();
        json.put("msg_type","text");
        json.put("content",new JSONObject(){{
            put("text",msg);
        }});
        String textMsg = JSON.toJSONString(json);
        dealFeishuMsgSend(textMsg);
    }

    public void sendSystemMsgAndType( String content,String type) {
        String proFile = environment.getActiveProfiles()[0];
        String msg = "[系统通知]["+ name +"]["+ proFile +"]" + content;
        JSONObject json = new JSONObject();
        json.put("msg_type","text");
        json.put("content",new JSONObject(){{
            put("text",msg);
        }});
        String textMsg = JSON.toJSONString(json);
        dealFeishuMsgSend(textMsg,type);
    }

    /**
     * 处理发送的飞书消息
     * @param textMsg
     */
    public void dealFeishuMsgSendIpGroup(String textMsg) {
        try {
//            String proFile = environment.getActiveProfiles()[0];
//            if (proFile.indexOf("prod")>=0) {
            String proFile = environment.getActiveProfiles()[0];
            HttpClient httpclient = HttpClients.createDefault();
            String WEBHOOK_TOKEN = "https://open.feishu.cn/open-apis/bot/v2/hook/" + accessToken_IpRobot;

            String msg = "[埃文用量]["+ name +"]["+ proFile +"]" + textMsg;
            long timestamp = System.currentTimeMillis() / 1000;
            String sign = generateSign(accessToken_IpRobotSec, timestamp);

            // 构建消息体
            Map<String, Object> content = new HashMap<>();
            content.put("text", msg);

            Map<String, Object> payload = new HashMap<>();
            payload.put("timestamp", timestamp);
            payload.put("sign", sign);
            payload.put("msg_type", "text");
            payload.put("content", content);

            // 发送请求
//            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(WEBHOOK_TOKEN);
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(JSON.toJSONString(payload), StandardCharsets.UTF_8));

//            CloseableHttpResponse response = client.execute(httpPost);
            HttpResponse response = httpclient.execute(httpPost);
//                    System.out.println("飞书返回: " + EntityUtils.toString(response.getEntity()));
//            log.info("【发送飞书群消息IpGroup】消息响应结果：" + JSON.toJSONString(response.getEntity()));

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                log.info("【发送飞书群消息IPGroup】消息响应结果：" + JSON.toJSONString(result));
            }
//            HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
//            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
//            StringEntity se = new StringEntity(textMsg, "utf-8");
//            httppost.setEntity(se);
//
//            HttpResponse response = httpclient.execute(httppost);
//            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                String result = EntityUtils.toString(response.getEntity(), "utf-8");
//                log.info("【发送飞书群消息】消息响应结果：" + JSON.toJSONString(result));
//            }
//            }
        } catch (Exception e) {
            log.error("【发送飞书群消息IPGroup】error：" + e.getMessage(), e);
        }
    }

    private static String generateSign(String secret, long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData,false));
    }

    public void dealFeishuMsgSendReleaseNotify(String ipname,Long diffInSeconds) {
        try {
//            String proFile = environment.getActiveProfiles()[0];
//            if (proFile.indexOf("prod")>=0) {
            String proFile = environment.getActiveProfiles()[0];
            //对于没有包含在定义中的则不会发消息
            if(!profilemap.containsKey(proFile.toLowerCase())){
                return;
            }
            Date now = new Date();
            // 定义时间格式
            DateTimeFormatter formattertime = DateTimeFormatter.ofPattern("HH:mm:ss");
            // 格式化当前时间
            String formattedTime = DateUtils.parseDateToStr("HH:mm:ss", now);
            HttpClient httpclient = HttpClients.createDefault();
            String WEBHOOK_TOKEN = "https://open.feishu.cn/open-apis/bot/v2/hook/" + accessToken_ReleaseRobot;

            String msg = "[发版完成]["+ name +"]["+ proFile +"]"+caseParm2Name(ipname,name,proFile)+",当前时间"+formattedTime+",共花费了"+diffInSeconds.toString()+"秒" ;
            long timestamp = System.currentTimeMillis() / 1000;
            String sign = generateSign(accessToken_ReleaseRobotSec, timestamp);

            // 构建消息体
            Map<String, Object> content = new HashMap<>();
            content.put("text", msg);

            Map<String, Object> payload = new HashMap<>();
            payload.put("timestamp", timestamp);
            payload.put("sign", sign);
            payload.put("msg_type", "text");
            payload.put("content", content);

            // 发送请求
            HttpPost httpPost = new HttpPost(WEBHOOK_TOKEN);
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(JSON.toJSONString(payload), StandardCharsets.UTF_8));

            HttpResponse response = httpclient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                log.info("【发版完成发送飞书群消息发版】消息响应结果：" + JSON.toJSONString(result));
            }

        } catch (Exception e) {
            log.error("【发版完成发送飞书群消息发版】error：" + e.getMessage(), e);
        }
    }




    private static String caseParm2Name(String ipname,String appname,String proFile){
        StringBuffer sb = new StringBuffer();
        if(profilemap.containsKey(proFile.toLowerCase())){
            sb.append(profilemap.get(proFile.toLowerCase()));
        }
        if(appname.startsWith("admin-api")){
            sb.append("---ADMIN-API");
        }
        if(appname.startsWith("web-api")){
            sb.append("---WEB-API");
        }
        if(ipname!=null && !"".equals(ipname)){
            sb.append("---"+ipname);
        }

        if(sb.length()==0) {
            return appname + "_" + proFile;
        }
        return sb.toString();
    }

}
