package com.lightinit.hsdataplatform.tasks.logger;

import com.lightinit.hsdataplatform.common.ConfigUtils;
import com.lightinit.hsdataplatform.common.ShortPhoneUtils;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;

import com.lightinit.hsdataplatform.dictionary.DicTemplateCode;
import com.lightinit.hsdataplatform.entity.RunningMonitoring;
import com.lightinit.hsdataplatform.entity.RunningMonitoringExample;
import com.lightinit.hsdataplatform.entity.RunningMonitoringLog;
import com.lightinit.hsdataplatform.mapper.RunningMonitoringLogMapper;
import com.lightinit.hsdataplatform.mapper.RunningMonitoringMapper;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.commons.lang.StringUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author: sunxiang
 * @Date: 2019/3/8 11:29
 * @Description:
 **/
@DisallowConcurrentExecution
public class LoggerJob implements Job {


    private static final Logger logger = LoggerFactory.getLogger(LoggerJob.class);
    private static final SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String phones=ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.PHONEPEOPLE);
    public void execute(JobExecutionContext jobExecutionContext) {
        JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
        String path =(String) map.get("path");
        String start = (String)map.get("alertStart");
        String end =(String) map.get("alertEnd");
        RunningMonitoringLogMapper runningMonitoringLogMapper =(RunningMonitoringLogMapper) map.get("runningMonitoringLogMapper");
        map.clear();
        try {
            //System.out.println( "读取日子路径: "+path);
            if(StringUtils.isEmpty(path)){
                return;
            }
            FileInputStream fis = new FileInputStream(path);
            InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line=null;
            StringBuilder builder = new StringBuilder();
            int count=0;//统计几处错误
            List<RunningMonitoringLog> list=new ArrayList<>();
            RunningMonitoringLog monitoringLog = null;
            while((line=reader.readLine())!=null){
                if(line.contains("[ ERROR ]")){
                    count++;
                    if(monitoringLog!=null){
                        monitoringLog.setDescription(builder.toString());
                        builder.delete(0,builder.length());
                    }
                    monitoringLog=new RunningMonitoringLog();
                    list.add(monitoringLog);
                    String logtimeTime = line.substring(0, 20);
                    try {
                        monitoringLog.setLogTime(SimpleDateFormat.parse(logtimeTime));
                    } catch (ParseException e) {
                        logger.error("日志读取日期格式转化错误");
                        e.printStackTrace();
                    }
                    monitoringLog.setTitle(line.substring(line.lastIndexOf("[ ERROR ]")+9).trim().equals(" ")?"未知错误":line.substring(line.lastIndexOf("[ ERROR ]")+9).trim());
                    monitoringLog.setCreatedAt(new Date());
                    monitoringLog.setMonitoringType("用户日志监控");
                }
                builder.append(line);
            }
            if(builder.length()>0){
                list.get(list.size()-1).setDescription(builder.toString());//添加只有一个错误对象的情况，和最后一个错误日志对象
            }
            //插入日志数据库中
            for (RunningMonitoringLog runningMonitoringLog : list) {
                runningMonitoringLogMapper.insert(runningMonitoringLog);
            }
            if(StringUtils.isEmpty(start) || StringUtils.isEmpty(end)){
                return;
            }
            //判断是否在发短信的事件内
            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 && StringUtils.isNotEmpty(phones)){
                //调用短信接口，发送短信
                //System.out.println("发送短信:  程序出现异常--"+builder.toString());
                String[] phoneArray = phones.split(",");
                for (String phone : phoneArray) {
                    ShortPhoneUtils.send(phone, DicTemplateCode.LOG,new Date(),"程序异常"+count+"处");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
