package com.nokia.tsl_data.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
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.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nokia.common.excel.entity.CellRect;
import com.nokia.common.excel.poi.PoiUtil;
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;

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

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

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

    /**
     * 定时任务
     * 
     * @return
     */
    public Runnable cronTask() {
        return new Runnable() {

            @Override
            public void run() {
                // 获取入参 day
                String day = new SimpleDateFormat("yyyyMMdd")
                        .format(new Date(System.currentTimeMillis() - 1000L * 3600 * 24));

                try {
                    dataWaraHouseTask(day);
                    reportGenerateTask(day);
                    screenShotTask(day);
                } catch (Exception e) {
                    log.error("定时任务出错--{}", e.getMessage());
                    e.printStackTrace();
                }
            }

        };
    }

    /**
     * 报表生成任务
     * 
     * @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 = tslDao.selectCompCountForDay(day);
        if (compCountForDay == 0) {
            throw new RuntimeException("he_d_mobile_comp表缺少数据");
        }
        tslReportService.workbookToFile(day, file.getAbsolutePath() + "/" + outputFileName + day + ".xlsx");
    }

    /**
     * 截图任务
     * 
     * @param day
     */
    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"));

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

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

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

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

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

    /**
     * 数据入库任务
     * 
     * @param day
     * @throws IOException
     * @throws FileNotFoundException
     */
    @Transactional(rollbackFor = Exception.class)
    public void dataWaraHouseTask(String day) throws FileNotFoundException, IOException {
        tslWaraHouseService.waraHouseHighQuality(day);
        tslWaraHouseService.waraHouseMobileComp(day);
    }
}
