package com.lightinit.hsdataplatform.tasks.logger;

import com.lightinit.hsdataplatform.common.ConfigUtils;
import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.common.ShortPhoneUtils;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.dictionary.DicPaasApi;
import com.lightinit.hsdataplatform.dictionary.DicRuningMonitoringType;
import com.lightinit.hsdataplatform.dictionary.DicTemplateCode;
import com.lightinit.hsdataplatform.entity.RunningMonitoringLog;
import com.lightinit.hsdataplatform.mapper.RunningMonitoringLogMapper;
import org.apache.log4j.LogManager;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@DisallowConcurrentExecution
public class StateJob implements Job {

    org.apache.log4j.Logger log = LogManager.getLogger(FluxJob.class);

    /*@Autowired
    private RunningMonitoringLogMapper runningMonitoringLogMapper ;*/

    public void execute(JobExecutionContext jobExecutionContext) {
        JobDataMap map_1 = jobExecutionContext.getJobDetail().getJobDataMap();
        String path =(String) map_1.get("path");
        String start = (String)map_1.get("alertStart");
        String end =(String) map_1.get("alertEnd");
        RunningMonitoringLogMapper runningMonitoringLogMapper =(RunningMonitoringLogMapper) map_1.get("runningMonitoringLogMapper");
        map_1.clear();
        try {
            String str = HttpUtil.httpPost(DicPaasApi.SERVICES, null, null);
            Map<String, Object> map1 = HttpUtil.strToMap(str);
            for (String key : map1.keySet()) {
                String st = cnToEncode(key);
                String str2 = HttpUtil.httpPost(DicPaasApi.ISSERVICE +st , null, null);
                List<Object> objects = HttpUtil.strToList(str2);
                for (Object object : objects) {
                    Map<String,Object> map  = (Map<String, Object>) object;
                    List<Map<String,Object>> checks = (List<Map<String, Object>>) map.get("Checks");
                    for (Map<String,Object> check : checks) {
                        if (!check.get("Status").equals("passing")){
                            //插入监控流量
                            RunningMonitoringLog runningMonitoringLog = new RunningMonitoringLog() ;
                            runningMonitoringLog.setMonitoringType(DicRuningMonitoringType.API);
                            runningMonitoringLog.setLogTime(new Date());
                            runningMonitoringLog.setCreatedAt(new Date());
                            runningMonitoringLog.setTitle(DicRuningMonitoringType.API);
                            runningMonitoringLog.setDescription("服务："+key+"运行状态异常");
                            runningMonitoringLogMapper.insert(runningMonitoringLog) ;
                            //发送短信
                            //判断是否在发短信的事件内
                            Calendar corrent = Calendar.getInstance();
                            int correntHuor = corrent.get(Calendar.HOUR_OF_DAY);
                            int correntMinute = corrent.get(Calendar.MINUTE);
                            String corr=(correntHuor<10?("0"+correntHuor):correntHuor)+":"+(correntMinute<10?("0"+correntMinute):correntMinute);
                            if(corr.compareTo(start)>0 && corr.compareTo(end)<0 ){
                                //发送短信
                                String phonepeople = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.PHONEPEOPLE);
                                String[] phones = phonepeople.split(",");
                                for (String phone : phones) {
                                    ShortPhoneUtils.send(phone, DicTemplateCode.STATE,new Date(),key);
                                }
                                return;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取服务列表异常！");
        }
    }

    /**
     * 将字符串中的中文进行编码
     * @param s
     * @return 返回字符串中汉字编码后的字符串
     */
    private  String cnToEncode(String s){
        char[] ch = s.toCharArray();
        String result = "";
        for(int i=0;i<ch.length;i++){
            char temp = ch[i];
            if(isChinese(temp)){
                try {
                    String encode = URLEncoder.encode(String.valueOf(temp), "utf-8");
                    result = result + encode;
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                  log.error(e.getMessage());
                }
            }else{
                result = result+temp;
            }
        }
        return result;
    }

    /**
     * 判断字符是否为汉字
     * @param c
     * @return
     */
    private  boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }
}
