package com.tax.token.utils;

import com.alibaba.fastjson.JSONObject;
import com.tax.token.constants.TokenConstants;
import com.tax.token.model.TkToken;
import com.yxcheng.token.utils.HttpHelper;
import com.yxcheng.token.utils.JSONHelper;
import com.yxcheng.token.utils.ResponseContent;
import com.yxcheng.token.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class DingdingUtil {

	private static final Logger logger = LoggerFactory.getLogger(DingdingUtil.class);

	public static String monitorLoginDingUrl = TokenConstants.LOGIN_DING_URL;
	public static String monitorKeywords = TokenConstants.LOGIN_KEYWORDS;

	public static String sendDingInfo(String url, String content) {
		String result = "";
		JSONObject dingJson = new JSONObject();
		dingJson.put("msgtype", "text");

		JSONObject contJson = new JSONObject();
		contJson.put("content", content);

		JSONObject atJson = new JSONObject();
		atJson.put("atMobiles", new String[]{});
		atJson.put("isAtAll", false);

		dingJson.put("text", contJson);
		dingJson.put("at", atJson);

		try {
			ResponseContent res = HttpHelper.postJsonEntity(url, dingJson.toString());
			result = res.getContent();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(content +  " send message is error!" + e.getMessage());
		}
		return result;
	}

	public static void sendLoginErrorNotice(String uuIdFlag, TkToken tokenEntity, String content) {
		try {
			String result = "";
			if(StringUtil.isNotEmpty(content) && !JSONHelper.isJSONObject(content)) {
				CheckResult checkResult = checkContentErrorFlag(content);
				if(checkResult.getNoticeFlag()) {
					String sendContent = "【登录异常】：" + tokenEntity.getUserCode()
							+ "，" + tokenEntity.getTaxno() + "，" + uuIdFlag + "，异常关键字：" + checkResult.getNoticeKeyword();
					result = sendDingInfo(monitorLoginDingUrl, sendContent);
					logger.info(uuIdFlag + " sendContent " + sendContent+ " send message result is " + result);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(uuIdFlag +  " sendLoginErrorNotice is error!" + e.getMessage());
		}
	}

	public static CheckResult checkContentErrorFlag(String content) {
		CheckResult checkResult = new CheckResult();
		String[] keywordArr = monitorKeywords.split(",");
		for(String keyword:keywordArr) {
			if(content.contains(keyword)) {
				checkResult.setNoticeFlag(true);
				checkResult.setNoticeKeyword(keyword);
				break;
			}
		}
		return checkResult;
	}

	static class CheckResult {
		private boolean noticeFlag = false;
		private String noticeKeyword;

		public boolean getNoticeFlag() {
			return noticeFlag;
		}

		public void setNoticeFlag(boolean noticeFlag) {
			this.noticeFlag = noticeFlag;
		}

		public String getNoticeKeyword() {
			return noticeKeyword;
		}

		public void setNoticeKeyword(String noticeKeyword) {
			this.noticeKeyword = noticeKeyword;
		}
	}
}
