package com.cesgroup.cesmonitor.service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cesgroup.cesmonitor.bean.IcmppingLossReport;
import com.cesgroup.cesmonitor.bean.InterfaceIncomingReport;
import com.cesgroup.cesmonitor.common.EhcacheUtil;
import com.cesgroup.cesmonitor.common.Util;
import com.cesgroup.cesmonitor.dao.IcmppingLossReportMapper;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 丢包率报表service
 *
 * @author user
 * @version 1.0.0 2017年5月11日
 */
@Service("icmppingLossReportService")
public class IcmppingLossReportService {

    @Autowired
    private IcmppingLossReportMapper icmppingLossReportMapper;

    private Long timeFormat = 0L;

    /**
     *
     * @param group
     *            主机组
     * @param interval
     *            时间间隔
     * @param topNum
     *            top数量
     * @return 查询出丢包率数据
     */
    public List<IcmppingLossReport> selectIcmppingLossService(final String group, final Integer interval, final Integer topNum) {
        LoginUser user = Util.getLoginUser();
        Integer userId = user.getUserid();
        boolean isSuperAdmin = user.isSuperAdmin();
        List icmppingLossReports = new ArrayList();
        List icmppingLossReports2 = new ArrayList();
        Long deadLine = Util.getDeadLine(interval);
        timeFormat = Util.getTimeFormat(interval);

        if (isSuperAdmin) {
            icmppingLossReports = icmppingLossReportMapper.selectIcmppingLoss(group, deadLine - interval * timeFormat,
                deadLine);
        } else {
            icmppingLossReports = icmppingLossReportMapper.selectIcmppingLossByUser(group,
                deadLine - interval * timeFormat,
                deadLine, userId);
        }

        String ehcacheKey = "icmppingLossReports" + deadLine.toString() + group + interval + topNum;
        icmppingLossReports2.addAll(icmppingLossReports);
        String ehcacheKey2 = "myicmppingLossReports" + deadLine.toString() + group + interval + topNum;

        EhcacheUtil.put(ehcacheKey, icmppingLossReports);
        EhcacheUtil.put(ehcacheKey2, icmppingLossReports2);

        Iterator<IcmppingLossReport> it = icmppingLossReports.iterator();
        while (it.hasNext()) {
            IcmppingLossReport icmppingLossReport = it.next();
            if (icmppingLossReport.getValueAvg() == 100.0 || icmppingLossReport.getValueAvg() == 0.0) {
                it.remove();
            }

            //设置保留位数
            icmppingLossReport.setValueMin(Util.round(icmppingLossReport.getValueMin(), 2));
            icmppingLossReport.setValueAvg(Util.round(icmppingLossReport.getValueAvg(), 2));
            icmppingLossReport.setValueMax(Util.round(icmppingLossReport.getValueMax(), 2));
        }
        icmppingLossReports = Util.reduceList(icmppingLossReports, topNum.intValue());
        return icmppingLossReports;
    }

    /**
     *
     * @param group
     *            主机组
     * @param interval
     *            时间间隔
     * @param topNum
     *            top数量
     * @return 查询出本周期和上周期丢包率数据
     */
    public List<IcmppingLossReport> selectMulticycleIcmppingLossService(final String group, final Integer interval,
        final Integer topNum) {
        List icmppingLossReports = new ArrayList();
        List tempIcmppingLossReports = new ArrayList();
        IcmppingLossReport icmppingLossReport = new IcmppingLossReport();
        IcmppingLossReport previousCycleIcmppingLossReport = new IcmppingLossReport();
        Long deadLine = Util.getDeadLine(interval);
        timeFormat = Util.getTimeFormat(interval);

        tempIcmppingLossReports = (List<InterfaceIncomingReport>) EhcacheUtil
            .get("myicmppingLossReports" + deadLine.toString() + group + interval + topNum);
        /*lowInterfaceIncomingReports = interfaceIncomingReportMapper.selectLowInterfaceIncomingReport(group,
                deadLine - interval * timeFormat, deadLine);*/
        if (null == tempIcmppingLossReports) {

            tempIcmppingLossReports = selectIcmppingLossService(group, interval, topNum);
        } else {
            Collections.reverse(tempIcmppingLossReports);
        }

        EhcacheUtil.remove("myicmppingLossReports" + deadLine.toString() + group + interval + topNum);
        /*  lowInterfaceIncomingReports = interfaceIncomingReportMapper.selectLowInterfaceIncomingReport(group,
                   deadLine - interval * timeFormat, deadLine);*/

        int size = tempIcmppingLossReports.size();
        for (int i = 0; i < size; i++) {
            icmppingLossReport = (IcmppingLossReport) tempIcmppingLossReports.get(i);
            previousCycleIcmppingLossReport = icmppingLossReportMapper.selectIcmppingLossByHost(
                icmppingLossReport.getHost(), deadLine - 2 * interval * timeFormat, deadLine - interval * timeFormat);

            if (previousCycleIcmppingLossReport != null) {
                //设置保留位数
                previousCycleIcmppingLossReport
                .setValueMin(Util.round(previousCycleIcmppingLossReport.getValueMin(), 2));
                previousCycleIcmppingLossReport
                .setValueAvg(Util.round(previousCycleIcmppingLossReport.getValueAvg(), 2));
                previousCycleIcmppingLossReport
                .setValueMax(Util.round(previousCycleIcmppingLossReport.getValueMax(), 2));
            }

            icmppingLossReports.add(icmppingLossReport);
            icmppingLossReports.add(previousCycleIcmppingLossReport);
        }
        return icmppingLossReports;
    }

    /**
     *
     * @param group
     *            主机组
     * @param interval
     *            时间间隔
     * @param topNum
     *            top数量
     * @return 查询出本周期和上周期丢包率数据
     */
    public List<IcmppingLossReport> selectMulticycleIcmppingLossService2(final String group, final Integer interval,
        final Integer topNum) {
        List icmppingLossReports = new ArrayList();
        List tempIcmppingLossReports = new ArrayList();
        IcmppingLossReport icmppingLossReport = new IcmppingLossReport();
        IcmppingLossReport previousCycleIcmppingLossReport = new IcmppingLossReport();
        Long deadLine = Util.getDeadLine(interval);
        timeFormat = Util.getTimeFormat(interval);

        //tempIcmppingLossReports = (List<InterfaceIncomingReport>) EhcacheUtil.get("myicmppingLossReports" + deadLine.toString() + group + interval + topNum);
        tempIcmppingLossReports = selectIcmppingLossService(group, interval, topNum);
        /*   	 if(null == tempIcmppingLossReports){

           		 tempIcmppingLossReports = selectIcmppingLossService(group, interval, topNum);
           	 }else{
           		 Collections.reverse(tempIcmppingLossReports);
           	 }

           	EhcacheUtil.remove("myicmppingLossReports" + deadLine.toString() + group + interval + topNum);
         lowInterfaceIncomingReports = interfaceIncomingReportMapper.selectLowInterfaceIncomingReport(group,
                  deadLine - interval * timeFormat, deadLine);*/

        int size = tempIcmppingLossReports.size();
        for (int i = 0; i < size; i++) {
            icmppingLossReport = (IcmppingLossReport) tempIcmppingLossReports.get(i);
            previousCycleIcmppingLossReport = icmppingLossReportMapper.selectIcmppingLossByHost(
                icmppingLossReport.getHost(), deadLine - 2 * interval * timeFormat, deadLine - interval * timeFormat);

            if (previousCycleIcmppingLossReport != null) {
                //设置保留位数
                previousCycleIcmppingLossReport
                .setValueMin(Util.round(previousCycleIcmppingLossReport.getValueMin(), 2));
                previousCycleIcmppingLossReport
                .setValueAvg(Util.round(previousCycleIcmppingLossReport.getValueAvg(), 2));
                previousCycleIcmppingLossReport
                .setValueMax(Util.round(previousCycleIcmppingLossReport.getValueMax(), 2));
            }

            icmppingLossReports.add(icmppingLossReport);
            icmppingLossReports.add(previousCycleIcmppingLossReport);
        }
        return icmppingLossReports;
    }

    /**
     * 创建pdf文件
     *
     * @param fileName
     *            文件名称
     * @param imgList
     *            图片集合
     * @param interval
     *            时间间隔
     * @param group
     *            主机组
     * @param topNum
     *            top数量
     * @param table
     *            表格
     */
    public static void createPDF(final String fileName, final List<String> imgList, final Integer interval, final String group, final Integer topNum,
        final PdfPTable table, final String startDate, final String endDate) {
        //step 1
        Document document = new Document(PageSize.A4);
        //step 2
        if (fileName != null && !fileName.equals("") && !fileName.equals("cancel")) {
            try {
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
                writer.setStrictImageSequence(true);
                //step 3
                document.open();
                //step 4
                BaseFont baseFont = BaseFont.createFont(Util.getFontPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font font = new Font(baseFont);

                Font f = new Font(baseFont, 30);
                Paragraph p = new Paragraph("丢包率报表", f);
                p.setAlignment(Element.ALIGN_CENTER);
                document.add(p);

                String condition = Util.getCondition(interval, group, topNum, startDate, endDate);
                document.add(new Paragraph("统计条件:" + condition, font));
                document.add(new Paragraph("图表生成时间:" + Util.getCurrentTime(), font));

                Image img = null;
                for (int j = 0; j < imgList.size(); j++) {
                    // 图片
                    img = Image.getInstance(imgList.get(j));
                    float heigth = img.getHeight();
                    float width = img.getWidth();
                    int percent = Util.getPercent(heigth, width);
                    img.setAlignment(Image.MIDDLE);
                    img.scalePercent(percent + 3);// 表示是原来图像的比例;
                    document.add(img);
                }
                document.add(new Paragraph("丢包率Top" + topNum + "数据汇总", font));
                document.add(new Chunk(""));
                document.add(table);
                System.out.println("create pdf success!");

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                document.close();
            }
        }

    }

    /**
     * 创建表格
     *
     * @param icmppingLossReports
     *            丢包率数据
     * @return 表格
     */
    public static PdfPTable createTable(final List<IcmppingLossReport> icmppingLossReports) {
        PdfPTable table = null;
        try {
            table = new PdfPTable(8);
            table.setTotalWidth(800);
            table.setWidths(new int[] { 1, 1, 1, 1, 1, 1, 1, 1 });
            // 居中
            //            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            //            table.setHorizontalAlignment(Element.ALIGN_LEFT);
            BaseFont baseFont = BaseFont.createFont(Util.getFontPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(baseFont, 10);
            table.addCell(new Paragraph("主机名", font));
            table.addCell(new Paragraph("主机组", font));
            table.addCell(new Paragraph("本周期平均", font));
            table.addCell(new Paragraph("上周期平均", font));
            table.addCell(new Paragraph("本周期峰值", font));
            table.addCell(new Paragraph("上周期峰值", font));
            table.addCell(new Paragraph("本周期最低", font));
            table.addCell(new Paragraph("上周期最低", font));

            int size = icmppingLossReports.size();
            for (int i = 0; i < size; i = i + 2) {
                table.addCell(new Paragraph(icmppingLossReports.get(i).getHname(), font));
                table.addCell(new Paragraph(icmppingLossReports.get(i).getName(), font));
                table.addCell(String.valueOf(icmppingLossReports.get(i).getValueAvg()));
                if (icmppingLossReports.get(i + 1) == null) {
                    table.addCell(new Paragraph("-  -  -", font));
                } else {
                    table.addCell(String.valueOf(icmppingLossReports.get(i + 1).getValueAvg()));
                }

                table.addCell(String.valueOf(icmppingLossReports.get(i).getValueMax()));
                if (icmppingLossReports.get(i + 1) == null) {
                    table.addCell(new Paragraph("-  -  -", font));
                } else {
                    table.addCell(String.valueOf(icmppingLossReports.get(i + 1).getValueMax()));
                }

                table.addCell(String.valueOf(icmppingLossReports.get(i).getValueMin()));
                if (icmppingLossReports.get(i + 1) == null) {
                    table.addCell(new Paragraph("-  -  -", font));
                } else {
                    table.addCell(String.valueOf(icmppingLossReports.get(i + 1).getValueMin()));
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return table;
    }

    public List<IcmppingLossReport> selectIcmppingLossServiceByDate(final String group, final Integer interval, final Integer topNum,
        final String startDate, final String endDate) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long myStartDate = 0;
        long myEndDate = 0;
        long cycle = 0;
        Date startDate1;
        Date endDate1;

        try {
            startDate1 = df.parse(startDate);
            myStartDate = startDate1.getTime() / 1000;
            endDate1 = df.parse(endDate);
            myEndDate = endDate1.getTime() / 1000;
            cycle = myEndDate - myStartDate;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List icmppingLossReports = new ArrayList();
        Long deadLine = Util.getDeadLine(interval);
        timeFormat = Util.getTimeFormat(interval);
        icmppingLossReports = icmppingLossReportMapper.selectIcmppingLoss(group, myStartDate,
            myEndDate);

        Iterator<IcmppingLossReport> it = icmppingLossReports.iterator();
        while (it.hasNext()) {
            IcmppingLossReport icmppingLossReport = it.next();
            if (icmppingLossReport.getValueAvg() == 100.0 || icmppingLossReport.getValueAvg() == 0.0) {
                it.remove();
            }

            //设置保留位数
            icmppingLossReport.setValueMin(Util.round(icmppingLossReport.getValueMin(), 2));
            icmppingLossReport.setValueAvg(Util.round(icmppingLossReport.getValueAvg(), 2));
            icmppingLossReport.setValueMax(Util.round(icmppingLossReport.getValueMax(), 2));
        }
        icmppingLossReports = Util.reduceList(icmppingLossReports, topNum.intValue());
        return icmppingLossReports;
    }

    public List<IcmppingLossReport> selectMulticycleIcmppingLossServiceByDate(final String group, final Integer interval,
        final Integer topNum, final String startDate, final String endDate) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long myStartDate = 0;
        long myEndDate = 0;
        long cycle = 0;
        Date startDate1;
        Date endDate1;

        try {
            startDate1 = df.parse(startDate);
            myStartDate = startDate1.getTime() / 1000;
            endDate1 = df.parse(endDate);
            myEndDate = endDate1.getTime() / 1000;
            cycle = myEndDate - myStartDate;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List icmppingLossReports = new ArrayList();
        List tempIcmppingLossReports = new ArrayList();
        IcmppingLossReport icmppingLossReport = new IcmppingLossReport();
        IcmppingLossReport previousCycleIcmppingLossReport = new IcmppingLossReport();
        Long deadLine = Util.getDeadLine(interval);
        timeFormat = Util.getTimeFormat(interval);
        tempIcmppingLossReports = selectIcmppingLossServiceByDate(group, interval, topNum, myStartDate, myEndDate);
        int size = tempIcmppingLossReports.size();
        for (int i = 0; i < size; i++) {
            icmppingLossReport = (IcmppingLossReport) tempIcmppingLossReports.get(i);
            previousCycleIcmppingLossReport = icmppingLossReportMapper.selectIcmppingLossByHost(
                icmppingLossReport.getHost(), myStartDate - 2 * cycle, myStartDate - cycle);

            if (previousCycleIcmppingLossReport != null) {
                //设置保留位数
                previousCycleIcmppingLossReport
                .setValueMin(Util.round(previousCycleIcmppingLossReport.getValueMin(), 2));
                previousCycleIcmppingLossReport
                .setValueAvg(Util.round(previousCycleIcmppingLossReport.getValueAvg(), 2));
                previousCycleIcmppingLossReport
                .setValueMax(Util.round(previousCycleIcmppingLossReport.getValueMax(), 2));
            }

            icmppingLossReports.add(icmppingLossReport);
            icmppingLossReports.add(previousCycleIcmppingLossReport);
        }
        return icmppingLossReports;
    }

    public List<IcmppingLossReport> selectIcmppingLossServiceByDate(final String group, final Integer interval, final Integer topNum,
        final long startDate, final long endDate) {
        LoginUser user = Util.getLoginUser();
        Integer userId = user.getUserid();
        boolean isSuperAdmin = user.isSuperAdmin();

        List icmppingLossReports = new ArrayList();
        Long deadLine = Util.getDeadLine(interval);
        timeFormat = Util.getTimeFormat(interval);

        if (isSuperAdmin) {
            icmppingLossReports = icmppingLossReportMapper.selectIcmppingLoss(group, startDate,
                endDate);
        } else {
            icmppingLossReports = icmppingLossReportMapper.selectIcmppingLossByUser(group, startDate,
                endDate, userId);
        }

        Iterator<IcmppingLossReport> it = icmppingLossReports.iterator();
        while (it.hasNext()) {
            IcmppingLossReport icmppingLossReport = it.next();
            if (icmppingLossReport.getValueAvg() == 100.0 || icmppingLossReport.getValueAvg() == 0.0) {
                it.remove();
            }

            //设置保留位数
            icmppingLossReport.setValueMin(Util.round(icmppingLossReport.getValueMin(), 2));
            icmppingLossReport.setValueAvg(Util.round(icmppingLossReport.getValueAvg(), 2));
            icmppingLossReport.setValueMax(Util.round(icmppingLossReport.getValueMax(), 2));
        }
        icmppingLossReports = Util.reduceList(icmppingLossReports, topNum.intValue());
        return icmppingLossReports;
    }
}