package com.nokia.tsl_data.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.nokia.common.excel.entity.CellRect;
import com.nokia.common.excel.poi.PoiUtil;
import com.nokia.common.message.pushmessage.PushMessageUtil;
import com.nokia.tsl_data.dao.MobileCompDao;
import com.nokia.tsl_data.dao.TslDao;

import lombok.extern.slf4j.Slf4j;

/**
 * 任务
 */
@Slf4j
@Service
public class TslTaskService {

    private final TslReportService tslReportService;
    private final TslWaraHouseService tslWaraHouseService;
    private final TslDao tslDao;
    @Autowired
    private MobileCompDao mobileCompDao;
    private final PushMessageUtil pushMessageUtil;

    @Value("${tslTask.outputPath}")
    private String outputPath;

    private String outputFileName = "投诉清单各地市投诉率";

    public TslTaskService(TslReportService tslReportService, TslWaraHouseService tslWaraHouseService, TslDao tslDao,
            PushMessageUtil pushMessageUtil) {
        this.tslReportService = tslReportService;
        this.tslWaraHouseService = tslWaraHouseService;
        this.tslDao = tslDao;
        this.pushMessageUtil = pushMessageUtil;
    }

    /**
     * 定时任务
     * 
     * @return
     */
    public void cronTask() {
        // 获取入参 day
        String day = new SimpleDateFormat("yyyyMMdd")
                .format(new Date(System.currentTimeMillis() - 1000L * 3600 * 24));

        try {
            // 检查数据源
            checkSrcExsit(day);
            // 数据入库 v1.5修改修改了入库的表
            tslWaraHouseService.dataWaraHouseTask(day);
            // 生成xlsx
            reportGenerateTask(day);
            // 截图
            screenShotTask(day);
        } catch (Exception e) {
            log.error("定时任务出错--{}", e.getMessage());
            e.printStackTrace();
            pushMessageUtil.sendTextMessage("定时任务出错--" + e.getMessage());
        }
    }

    public void doTask(String day) {
        try {
            // 检查数据源
            // checkSrcExsit(day);
            // 数据入库 v1.5修改修改了入库的表
            // tslWaraHouseService.dataWaraHouseTask(day);
            // 生成xlsx
            reportGenerateTask(day);
            // 截图
            screenShotTask(day);
        } catch (Exception e) {
            log.error("定时任务出错--{}", e.getMessage());
            e.printStackTrace();
            pushMessageUtil.sendTextMessage("定时任务出错--" + e.getMessage());
        }
    }

    /**
     * 检查源文件是否存在，不存在发送提醒，等待1小时后再次检查
     * 
     * @param day
     */
    public void checkSrcExsit(String day) {
        boolean flag = false;
        do {
            String checkResult = tslWaraHouseService.check(day);
            if (checkResult == null || !checkResult.endsWith("数据源正常。")) {
                pushMessageUtil.sendTextMessage(checkResult);
                // 每小时检查一次
                try {
                    Thread.sleep(1000L * 3600L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                }
            } else {
                flag = true;
            }
        } while (!flag);
    }

    /**
     * 报表生成任务
     * 
     * @param day
     */
    public void reportGenerateTask(String day) {
        File file = new File(outputPath + day);
        if (!file.exists()) {
            file.mkdirs();
        }
        String dayId = day.substring(0, 4) + "-" + day.substring(4, 6) + "-" + day.substring(6);
        int qualityCountForDay = tslDao.selectQualityCountForDay(dayId);
        if (qualityCountForDay == 0) {
            throw new RuntimeException("he_d_high_quality表缺少数据");
        }
        int compCountForDay = mobileCompDao.selectCompCountForDay(day);
        if (compCountForDay == 0) {
            throw new RuntimeException("he_d_mobile_comp表缺少数据");
        }
        tslReportService.workbookToFile(day, file.getAbsolutePath() + "/" + outputFileName + day + ".xlsx");
    }

    /**
     * 截图任务
     */
    public void screenShotTask(String day) {
        String screenShotPath = outputPath + day + "/";
        File file = new File(outputPath + day + "/" + outputFileName + day + ".xlsx");
        if (!file.exists()) {
            throw new RuntimeException(String.format("无法截图，文件%s不存在", file.getAbsolutePath()));
        }
        try (Workbook workbook = WorkbookFactory.create(file);) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new SimpleDateFormat("yyyyMMdd").parse(day));
            int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
            BufferedImage screenShot;
            // 截图1
            String area = "A1:" + CellRect.getColumnName(dayOfMonth + 7) + "15";
            screenShot = PoiUtil.screenShot(workbook.getSheet("管理端-移网质量类"), area, "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-1-投诉率.png"));

            // 新截图
            String area2 = "A1:" + CellRect.getColumnName(dayOfMonth + 7) + "15";
            screenShot = PoiUtil.screenShot(workbook.getSheet("客户端-战略考核"), area2, "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-2-客户端-战略考核.png"));

            // 截图2
            if (!day.endsWith("01")) {
                screenShot = PoiUtil.screenShot(workbook.getSheet("管理端-重复投诉率"), "A1:G16", "微软雅黑");
                ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-3-重复投诉率.png"));
            }

            // 截图3 4
            Sheet sheet = workbook.getSheet("投诉处理时长、超时工单概况");
            screenShot = PoiUtil.screenShot(sheet, "A1:D15", "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-4-超时工单.png"));
            screenShot = PoiUtil.screenShot(sheet, "G1:J14", "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-5-处理时长.png"));

            // 截图5
            screenShot = PoiUtil.screenShot(workbook.getSheet("客户端-投诉问题解决满意度"), "A1:D15", "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-6-满意率.png"));

            // 截图6
            screenShot = PoiUtil.screenShot(workbook.getSheet("客户端-投诉问题解决率"), "A1:D15", "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-7-解决率.png"));

            // 截图7
            screenShot = PoiUtil.screenShot(workbook.getSheet("客户端-投诉问题响应率"), "A1:D15", "微软雅黑");
            ImageIO.write(screenShot, "png", new File(screenShotPath + day + "-8-响应率.png"));
        } catch (EncryptedDocumentException | IOException | ParseException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
