package org.jeecg.modules.adweb.common.service;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xkcoding.http.util.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.adweb.common.constant.RobotMsgTemplate;
import org.jeecg.modules.adweb.common.dto.RobotDto;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description:
 * @Author: wrk
 * @date 2022/7/18 16:30
 */
@Slf4j
@Service
public class FeishuService {

    @Resource
    private ISysDictService sysDictService;

    @Resource
    private IAdwebSiteService adwebSiteService;

    /**
     * url
     */
    @Value("${robot.enquiry-url}")
    private String enquiryUrl;
    @Value("${robot.market-plan-missing-url}")
    private String marketPlanMissingUrl;
    @Value("${robot.flow-abnormal-url}")
    private String flowAbnormalUrl;

    @Value("${robot.keyword-preOrSuffix-url}")
    private String keywordPreOrSuffixUrl;

    @Value("${robot.gtm-url}")
    private String gtmUrl;


    /**
     * 本地属性
     */
    public static String PROFILES_ACTIVE;

    @Value("${spring.profiles.active}")
    public void setCustomName(String customName) {
        PROFILES_ACTIVE = customName;
    }

    /**
     * 异常栈发送机器人消息
     *
     * @param consumeTime
     * @param title
     * @param errorMsg
     */
    public void sendRobot(float consumeTime, String title, String classNameInit, String methodNameInit, String errorMsg) {
        //HttpServletRequest request = ContextHolderUtils.getRequest();
        String requestIp = "";
        String className = classNameInit == null ? "未知类名" : classNameInit;
        String methodName = methodNameInit == null ? "未知方法名" : methodNameInit;
        /*if (request != null){
            requestIp = IpUtil.getIpAddr(request);
            //className = request.getClass().getName();
            //methodName = request.getMethod();
        }*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStr = simpleDateFormat.format(new Date());
        String text = RobotMsgTemplate.EXCEPTION_MSG;
        text = text.replaceAll("\\{environment\\}", PROFILES_ACTIVE);
        text = text.replaceAll("\\{consumeTime\\}", consumeTime + "秒");
        text = text.replaceAll("\\{time\\}", timeStr);
        //text = text.replaceAll("\\{requestIp\\}", "".equals(requestIp) ? "0:0:0:0:0:0:0:1" : requestIp);
        text = text.replaceAll("\\{title\\}", title);
        text = text.replaceAll("\\{methodName\\}", className + "." + methodName + "()");
        text = text.replaceAll("\\{errorMsg\\}", errorMsg);
        RobotDto robotDto = new RobotDto();
        robotDto.setMsg_type("interactive");
        robotDto.setCard(JSON.parseObject(text, RobotDto.CardBean.class));
        String json = JSON.toJSONString(robotDto);

        HttpRequest.post(enquiryUrl).body(json).execute(true);
    }

    /**
     * 邮件发送失败通知
     */
    public void sendEnquiryEmailFailMsg(Long enquiryId, String siteCode, String email, String content) {
        SysDictItem dictItem = sysDictService.getDictItemByCodeAndText("feishu_msg_template", "enquiry_email_fail_msg");
        if (dictItem == null || StringUtil.isEmpty(dictItem.getItemValue())) {
            return;
        }

        String siteName = adwebSiteService.getSiteByCode(siteCode).getName();

        String template = dictItem.getItemValue();
        template = template.replace("{{siteName}}", siteName);
        template = template.replace("{{enquiryId}}", Long.toString(enquiryId));
        template = template.replace("{{email}}", email);
        template = template.replace("{{content}}", content);

        JSONObject object = new JSONObject();
        object.put("msg_type", "interactive");
        object.put("card", template);

        HttpRequest.post(enquiryUrl).body(object.toJSONString()).execute(true);
    }

    /**
     * @return
     */
    public void sendAdWebV2FeiShuMsg(String msgTitle, String message) throws NoSuchAlgorithmException, InvalidKeyException {
//        String secretSign = "Irf26L7VJCbXPH0HOLJEkf";
//        int timestamp = Integer.parseInt((System.currentTimeMillis() / 1000) + "");
//        int timestamp=Integer.parseInt(String.valueOf(System.currentTimeMillis()).substring(0,10));
//        log.info("timestamp:{}", timestamp);

        String param = "{\"msg_type\":\"interactive\",\"card\":{\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"msgTitle\"},\"template\":\"blue\"},\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"message\"}}]}}";
        if (StringUtils.isNotBlank(message)) {
            param = param.replace("message", message);
        }
        if (StringUtils.isNotBlank(msgTitle)) {
            param = param.replace("msgTitle", msgTitle);
        }

        JSONObject object = JSONObject.parseObject(param);
//        object.replace("timestamp", timestamp);
//        object.replace("sign", genSign(secretSign, timestamp));
        HttpRequest.post(gtmUrl).body(object.toJSONString()).execute(true);
    }

}
