package com.nokia.dingtalk_auto.service;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.Row;
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.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.nokia.common.dingtalk.DingTalkUtil;
import com.nokia.common.dingtalk.exception.DingTalkApiException;
import com.nokia.common.jsch.SftpUtil;

/**
 * 向钉钉群发送投诉清单各地市投诉率
 */
@Service
public class TslTaskService {

    @Value("${tslTask.remoteDir:/data/report_auto/output}")
    private String remoteDir;

    @Value("${tslTask.localDir:./download}")
    private String localDir;

    @Value("${tslTask.remoteHost:133.96.94.105}")
    private String remoteHost;

    @Value("${tslTask.remotePort:22}")
    private int remotePort;

    @Value("${tslTask.remoteUser:do}")
    private String remoteUser;

    @Value("${tslTask.remotePassword:Richr00t}")
    private String remotePassword;

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private DingTalkUtil tslTaskDingTalkUtil;
    @Resource
    private DingTalkUtil remindDingTalkUtil;

    // 完成指定日期的发送任务
    public void runTask(String day) throws DingTalkApiException, Exception {
        // 1. 下载文件
        download(day);
        // 2. 生成要发送的内容
        String message = getFilesToSend(day);
        // 5. 发送提醒
        remindDingTalkUtil.sendMarkdownMsgWithRobot(message);
        // 3. 发送文件
        sendDingTalkMsg(day);
        // 4. 发送消息
        tslTaskDingTalkUtil.sendMarkdownMsgWithRobot(message);
        remindDingTalkUtil.sendTextMsgWithRobot("发送成功==" + day);
    }

    public void sendDingTalkMsg(String day) throws DingTalkApiException {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String localPath = localDir + "/" + day;
        File[] files = new File(localPath).listFiles();
        StringBuffer stringBuffer = new StringBuffer();
        // 分开发送，保证发送文件的顺序
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-1-投诉率.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-2-重复投诉率.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-3-超时工单.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-4-处理时长.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-5-满意率.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-6-解决率.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().endsWith("-7-响应率.png")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "image");
                tslTaskDingTalkUtil.sendImageMsgWithRobot(mediaId);
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        for (File file : files) {
            if (file.getName().toLowerCase().equals("投诉清单各地市投诉率" + day + ".xlsx")) {
                String mediaId = tslTaskDingTalkUtil.upload(file.getAbsolutePath(), "file");
                tslTaskDingTalkUtil.sendFileMsgWithRobot(mediaId, file.getName());
                stringBuffer.append(dateFormat.format(new Date())).append(file.getName()).append("发送成功==");
            }
        }
        remindDingTalkUtil.sendTextMsgWithRobot(stringBuffer.toString());
    }

    /**
     * 组织一段话
     * 
     * @param day
     * @throws Exception
     */
    public String getFilesToSend(String day) throws Exception {
        String localPath = localDir + "/" + day + "/";
        String localFile = localPath + "投诉清单各地市投诉率" + day + ".xlsx";
        StringBuffer stringBuffer = new StringBuffer();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new SimpleDateFormat("yyyyMMdd").parse(day));
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        stringBuffer.append(calendar.get(Calendar.YEAR))
                .append("年")
                .append(calendar.get(Calendar.MONTH) + 1)
                .append("月截至")
                .append(dayOfMonth)
                .append("日移动网投诉情况统计：\n\n管理端-移网质量类：投诉率：<font color=#FF0000>");
        File file = new File(localFile);
        if (!file.exists()) {
            throw new Exception(String.format("文件--%s--不存在", localFile));
        }
        try (Workbook workbook = WorkbookFactory.create(file)) {
            Sheet sheet = workbook.getSheet("管理端-移网质量类");
            Row row;
            List<List<Object>> list = new ArrayList<>();
            for (int i = 2; i < 14; i++) {
                row = sheet.getRow(i);
                double value = row.getCell(dayOfMonth + 6).getNumericCellValue();
                if (value > 0.0) {
                    List<Object> list2 = new ArrayList<>();
                    list.add(list2);
                    list2.add(0, value);
                    list2.add(1, row.getCell(dayOfMonth + 7).getStringCellValue());
                }
            }
            // 排序
            list.sort((o1, o2) -> Double.compare((double) o2.get(0), (double) o1.get(0)));
            StringBuffer stringBuffer2 = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                stringBuffer.append(list.get(i).get(1).toString()).append("、");
                if (i < 3) {
                    stringBuffer2.append(list.get(i).get(1).toString()).append("、");
                }
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            stringBuffer2.deleteCharAt(stringBuffer2.length() - 1);
            stringBuffer.append("</font>未达到目标值，<font color=#FF0000>")
                    .append(stringBuffer2.toString())
                    .append("</font>排名靠后");

            // 1号忽略重复投诉率
            if (day.endsWith("01")) {
                stringBuffer.append("。\n\n客户端-移网网络体验：投诉问题解决满意率：<font color=#FF0000>");
            } else {
                stringBuffer.append("；重复投诉率：<font color=#FF0000>");
                sheet = workbook.getSheet("管理端-重复投诉率");
                stringBuffer.append(sheet.getRow(3).getCell(0).getStringCellValue()).append("、")
                        .append(sheet.getRow(4).getCell(0).getStringCellValue()).append("、")
                        .append(sheet.getRow(5).getCell(0).getStringCellValue())
                        .append("</font>增长较快。\n\n客户端-移网网络体验：投诉问题解决满意率：<font color=#FF0000>");
            }

            sheet = workbook.getSheet("客户端-投诉问题解决满意度");
            stringBuffer.append(sheet.getRow(13).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(12).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(11).getCell(0).getStringCellValue())
                    .append("</font>较低，与达标值差距较大；投诉问题解决率：<font color=#FF0000>");

            sheet = workbook.getSheet("客户端-投诉问题解决率");
            stringBuffer.append(sheet.getRow(13).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(12).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(11).getCell(0).getStringCellValue())
                    .append("</font>较低，与达标值差距较大；投诉问题响应率：<font color=#FF0000>");

            sheet = workbook.getSheet("客户端-投诉问题响应率");
            stringBuffer.append(sheet.getRow(13).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(12).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(11).getCell(0).getStringCellValue())
                    .append("</font>较低，与达标值差距较大。\n\n投诉处理时长、超时工单概况：超时工单：<font color=#FF0000>");

            sheet = workbook.getSheet("投诉处理时长、超时工单概况");
            stringBuffer.append(sheet.getRow(2).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(3).getCell(0).getStringCellValue()).append("、")
                    .append(sheet.getRow(4).getCell(0).getStringCellValue())
                    .append("</font>分公司超时工单占比较高，<font color=#FF0000>");
            list = new ArrayList<>();
            for (int i = 2; i < 14; i++) {
                List<Object> list2 = new ArrayList<>();
                list.add(list2);
                list2.add(0, sheet.getRow(i).getCell(2).getNumericCellValue());
                list2.add(1, sheet.getRow(i).getCell(0).getStringCellValue());
            }
            list.sort((o1, o2) -> Double.compare((double) o2.get(0), (double) o1.get(0)));
            stringBuffer.append(list.get(0).get(1).toString()).append("、")
                    .append(list.get(1).get(1).toString()).append("、")
                    .append(list.get(2).get(1).toString())
                    .append("</font>超时工单数量较多。平均处理时长：本月相对较长的地市为<font color=#FF0000>");

            list = new ArrayList<>();
            for (int i = 2; i < 14; i++) {
                List<Object> list2 = new ArrayList<>();
                list.add(list2);
                list2.add(0, sheet.getRow(i).getCell(8).getNumericCellValue());
                list2.add(1, sheet.getRow(i).getCell(6).getStringCellValue());
            }
            list.sort((o1, o2) -> Double.compare((double) o2.get(0), (double) o1.get(0)));
            stringBuffer.append(list.get(0).get(1).toString()).append("、")
                    .append(list.get(1).get(1).toString()).append("、")
                    .append(list.get(2).get(1).toString()).append("</font>；与")
                    .append(sheet.getRow(1).getCell(7).getStringCellValue()).append("比<font color=#FF0000>")
                    .append(sheet.getRow(2).getCell(6).getStringCellValue()).append("</font>时长增幅较大。");
        }

        return stringBuffer.toString();
    }

    /**
     * 下载xlsx文件
     * 
     * @param day
     */
    public void download(String day) {
        SftpUtil sftpUtil = new SftpUtil().setHost(remoteHost)
                .setPort(remotePort)
                .setUser(remoteUser)
                .setPassword(remotePassword);

        String remotePath = remoteDir + "/" + day;
        String localPath = localDir + "/" + day;

        File localFile = new File(localPath);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }

        try {
            sftpUtil.connect();
            List<String> files = sftpUtil.ls(remotePath);
            for (String fileName : files) {
                sftpUtil.get(remotePath + "/" + fileName, localPath + "/" + fileName);
            }
        } catch (JSchException | SftpException | IOException e) {
            e.printStackTrace();
        } finally {
            sftpUtil.disconnect();
        }
    }
}
