package com.cesgroup.cesmonitor.service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.Response;

import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
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.scheduling.annotation.Scheduled;

import com.ces.itsm.ws.service.monitor.MonitorService;
import com.cesgroup.cesmonitor.bean.FaultWarningDto;
import com.cesgroup.cesmonitor.common.JSON;
import com.google.gson.reflect.TypeToken;

//@Component
//@Job(name="StatisticJob", cronExpression = "0 */1 * * * ?")
//@Service
public class Job {

    private SimpleDateFormat DF_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    OverviewService overviewService;

    @Value("${s1.url}")
    String s1Url = null;//"http://10.10.38.20:8080/services/jaxrs";

    @Value("${s1.ip}")
    String s1Ip = null;

    //起始时间
    private Date lastStartTime = null;

    //终止时间
    private Date lastEndTime = null;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private Date toDate(String str) {
        try {
            if (str.length() == 10) {
                str = str + " 00:00:00";
            }
            return DF_TIME.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    private String toString(final Date date) {
        return DF_TIME.format(date);
    }

    //    public String doPost(String jsonString) {
    //        HttpClient httpClient = null;
    //        HttpPost httpPost = null;
    //        String result = null;
    //        try {
    //            httpClient = HttpClients.createDefault();
    //            httpPost = new HttpPost("http://10.10.38.20:8080/monitor/monitorService/savaWarn");
    //            //设置参数
    //            httpPost.addHeader("content-type", "application/json");
    //            httpPost.addHeader("Accept", "application/json");
    //            List<NameValuePair> list = new ArrayList<NameValuePair>();
    //            list.add(new BasicNameValuePair("jsonString", jsonString));
    //
    //            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
    //            httpPost.setEntity(entity);
    //
    //            HttpResponse response = httpClient.execute(httpPost);
    //            if (response != null) {
    //                HttpEntity resEntity = response.getEntity();
    //                if (resEntity != null) {
    //                    result = EntityUtils.toString(resEntity, "UTF-8");
    //                }
    //            }
    //        } catch (Exception ex) {
    //            ex.printStackTrace();
    //        }
    //        return result;
    //    }

    public void sendToS1(final String url, final String json) {
        //        WSSConfig.setAddJceProviders(false);

        JAXRSClientFactoryBean factory = new JAXRSClientFactoryBean();
        //        factory.setAddress("http://10.10.38.20:8080/services/jaxrs");
        factory.setAddress(url);

        factory.setResourceClass(MonitorService.class);
        MonitorService create = (MonitorService) factory.create();

        Response save = create.save(json);
        System.err.println(save.getStatus());
    }

    public static void main(final String[] args) {
        String json = " {" + "\"warningTime\": \"2017-08-28 12:23:45\","
            + "\"warningMessage\": \"10.250.200.4 接口1/0/8流量小于10bps\"," + "\"ip\": \"10.250.198.200\","
            + "\"warningLevel\": \"5\"," + "\"faultStatus\": \"0\"," + "\"hostName\": \"10.250.200.4 \","
            + "\"triggerId\": \"16181\"," + "\"systemType\": \"\"," + "\"hostIp\": \"10.250.200.4 \""
            + "}";
        new Job().sendToS1("http://10.10.38.20:8080/services/jaxrs", json);
    }

    @Scheduled(cron = "0 */2 * * * ?")
    public void doJob() {
        logger.info("开始发送报警信息...");
        File file = new File("doJOb.json");
        if (lastStartTime == null || lastEndTime == null) {
            if (file.exists()) {
                String json = JSON.getStringFromFile(file);
                //               Type type = new TypeToken<ArrayList<City>>() {}.getType();
                Map<String, Date> config = JSON.fromJson(json, new TypeToken<Map<String, Date>>() {}.getType());
                lastStartTime = config.get("lastStartTime");
                lastEndTime = config.get("lastEndTime");
            }
        }
        if (lastStartTime == null || lastEndTime == null) {
            lastStartTime = new Date(new Date().getTime() - 120 * 60000);
            lastEndTime = new Date(new Date().getTime() - 60 * 60000);
        }
        Date startTime = lastEndTime;
        Date endTime = new Date();
        //发送报警信息
        //sendData(startTime, endTime);

        List<FaultWarningDto> list = overviewService.listsResourceAlarmInfo(startTime, endTime);
        for (FaultWarningDto alert : list) {
            alert.setObjectid(null);
            alert.setIp(s1Ip);
            String json = JSON.toJson(alert);
            logger.info(json);
            this.sendToS1(s1Url, json);
        }

        lastStartTime = startTime;
        lastEndTime = endTime;
        Map<String, Date> config = new HashMap<String, Date>();
        config.put("lastStartTime", lastStartTime);
        config.put("lastEndTime", lastEndTime);

        JSON.saveStringToFile(JSON.toJson(config), file);
        logger.info("发送报警信息,从{}到{}", toString(startTime), toString(endTime));
    }
}
