package com.gic.haoban.manage.service.service.out.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.dubbo.entity.ProviderLocalTag;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.enums.AlertTypeEnum;
import com.gic.haoban.manage.api.service.CheckQywxSettingApiService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.mq.sdk.GicMQClient;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Created 2021/5/31.
 *
 * @author hua
 */
@Service
public class CheckQywxSettingApiServiceImpl implements CheckQywxSettingApiService {

    private static final Logger logger = getLogger(CheckQywxSettingApiServiceImpl.class);
    private static final String FRIEND_SETTING_KEY = "haoban-check-friend-setting";
    private static final String FRIEND_SETTING_VAL_KEY = "haoban-check-friend-setting-val";

    private static final String SELF_APP = "selfSuiteId";
    private static final String THIRD_APP = "thirdSuiteId";

    private static final String ALERT_KEY = "friend-alert:";

    private static final String ALERT_URL = "https://oapi.dingtalk.com/robot/send?access_token=435c0ddaacda849e145b64cc3a83c37f742105d88cf27b719b2dbef167436ad4";

    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private EnterpriseService enterpriseService;

//    @Override
//    public void setFriendSetting(String wxEnterpriseId, String name) {
//        CheckFriendSettingDTO checkFriendSettingDTO = new CheckFriendSettingDTO();
//        checkFriendSettingDTO.setName(name);
//        checkFriendSettingDTO.setWxEnterpriseId(wxEnterpriseId);
//        RedisUtil.setCache(FRIEND_SETTING_KEY, checkFriendSettingDTO);
//        RedissonClient redisClient = RedisUtil.getRedisClient();
//        RMap<Object, Object> map = redisClient.getMap(FRIEND_SETTING_VAL_KEY);
//        map.delete();
//    }

    @Override
    public CheckFriendSettingDTO getFriendSetting() {
        return RedisUtil.getCache(FRIEND_SETTING_KEY, CheckFriendSettingDTO.class);
    }

    @Override
    public void saveFriendCallback(String wxEnterpriseId, ExternalUserDTO externalUserDTO, MemberUnionidRelatedDTO dto) {
        try {
            if (null == externalUserDTO) {
                messageAlert(wxEnterpriseId, dto, "好友提醒");
                return;
            }
            CheckFriendSettingDTO friendSetting = this.getFriendSetting();
            if (friendSetting == null) {
                return;
            }
            if (!wxEnterpriseId.equals(friendSetting.getWxEnterpriseId())) {
                return;
            }
            if (!friendSetting.getName().equals(externalUserDTO.getName())) {
                return;
            }
            RedissonClient redisClient = RedisUtil.getRedisClient();
            RMap<Object, Object> map = redisClient.getMap(FRIEND_SETTING_VAL_KEY);
            if (SELF_APP.equals(dto.getSuiteid())) {
                map.put(SELF_APP, externalUserDTO);
            } else {
                map.put(THIRD_APP, externalUserDTO);
            }
            messageAlert(wxEnterpriseId, dto, "好友提醒：" + dto.getSuiteid());
        } catch (Exception e) {
            logger.info("通知异常：{}", e.getMessage(),e);
        }
    }

    /**
     * 告警
     *
     * @param wxEnterpriseId
     * @param dto
     */
    private void messageAlert(String wxEnterpriseId, MemberUnionidRelatedDTO dto, String titleSub) {
        titleSub = StringUtils.isBlank(titleSub) ? "加好友异常" : titleSub;
        String key = ALERT_KEY + wxEnterpriseId;
        RBucket<Object> bucket = RedisUtil.getRedisClient().getBucket(key);
        boolean b = bucket.trySet(1, 2L, TimeUnit.HOURS);
        if (!b) {
            logger.info("同一个企业加好友2小时内重复无需提醒");
            return;
        }
        ProviderLocalTag providerLocalTag = ProviderLocalTag.tag.get();
        String traceId = providerLocalTag.traceId;

        AlertMessageDTO messageDTO = new AlertMessageDTO();
        messageDTO.setAlertTitle(titleSub);
        messageDTO.setEnterpriseId(dto.getEnterpriseId());
        messageDTO.setAlertType(AlertTypeEnum.FRIEND_ADD.getType());
        messageDTO.setWxEnterpriseId(wxEnterpriseId);
        Map<String, Object> map = new HashMap<>();
        map.put("staffId", dto.getStaffId());
        map.put("wxEnterpriseId", wxEnterpriseId);
        messageDTO.setContentMap(map);
        messageDTO.setTraceId(traceId);
        GicMQClient clientInstance = GICMQClientUtil.getClientInstance();
        try {
            clientInstance.sendMessage("haobanAlertMq", JSONObject.toJSONString(messageDTO));
        } catch (Exception e) {
            logger.info("异常：{}", e.getMessage(),e);
        }
    }

    @Override
    public void alertCallback(String params) {
        logger.info("告警：{}", params);
        AlertMessageDTO messageDTO = JSONObject.parseObject(params, AlertMessageDTO.class);
        if (null == messageDTO) {
            return;
        }
        boolean alertFlag = false;
        if (messageDTO.getAlertType().equals(AlertTypeEnum.ES_BID_PAGE.getType())) {
            Object limit = RedisUtil.getCache("es_bid_page_limit");
            if (null != limit) {
                int begin = Integer.parseInt(messageDTO.getContentMap().get("begin").toString());
                if (begin < Integer.parseInt(limit.toString())) {
                    logger.info("没到阈值，无需告警");
                    alertFlag = true;
                }
            }
        }
        //告警是否拦截重复告警 防止批量触发
        if (StringUtils.isNotBlank(messageDTO.getKey())) {
            String key = messageDTO.getKey() + messageDTO.getAlertType() + alertFlag;
            RBucket<Object> bucket = RedisUtil.getRedisClient().getBucket(key);
            boolean b = bucket.trySet(1, 60L, TimeUnit.SECONDS);
            if (!b) {
                return;
            }
        }

        Map<String, Object> dingMap = new HashMap<>();
        Map<String, Object> markdownMap = new HashMap<>();
        dingMap.put("msgtype", "markdown");
        dingMap.put("markdown", markdownMap);

        StringBuffer text = new StringBuffer();
        String dingUrl = ALERT_URL;
        AlertTypeEnum anEnum = AlertTypeEnum.getEnum(messageDTO.getAlertType());
        if (anEnum != null) {
            markdownMap.put("title", anEnum.getName() + "-" + messageDTO.getAlertTitle());
            text.append("标题：").append(anEnum.getName()).append("-").append(messageDTO.getAlertTitle()).append("\n\r");
            if (anEnum.getDingUrl() != null) {
                dingUrl = anEnum.getDingUrl();
            }
            if (alertFlag) {
                dingUrl = ALERT_URL;
            }
        } else {
            markdownMap.put("title", messageDTO.getAlertTitle());
            text.append("标题：").append(messageDTO.getAlertTitle()).append("\n\r");
        }

        //企业信息
        if (StringUtils.isNotBlank(messageDTO.getWxEnterpriseId())) {
            WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseService.selectById(messageDTO.getWxEnterpriseId());
            text.append("企业：").append(wxEnterpriseDTO.getCorpName()).append("\n\r");
        }
        // 商户信息
        if (StringUtils.isNotBlank(messageDTO.getEnterpriseId())) {
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(messageDTO.getEnterpriseId());
            text.append("商户：").append(enterpriseDTO.getEnterpriseName()).append("(").append(enterpriseDTO.getBrandName()).append(")\n\r");
        }

        Map<String, Object> contentMap = messageDTO.getContentMap();
        if (MapUtils.isNotEmpty(contentMap)) {
            Set<String> keySet = contentMap.keySet();
            for (String k : keySet) {
                Object o = contentMap.get(k);
                text.append(k).append("：").append(o).append("\n\r");
            }
        }
        if (StringUtils.isNotBlank(messageDTO.getTraceId())) {
            String traceUrl = "http://10.0.100.2:8780/damo-stats/mongodb/getLogMessagesView?trace_id=" + messageDTO.getTraceId();
            text.append("链路：[").append(messageDTO.getTraceId()).append("](").append(traceUrl).append(")");
        }
        markdownMap.put("text", text.toString());
        String post = HttpUtil.post(dingUrl, JSONObject.toJSONString(dingMap));
        logger.info("dingding推送alert:{}", post);

    }
}
