package com.yizhi.application.lecturer.Service;

import com.alibaba.fastjson.JSON;
import com.yizhi.application.course.util.OssUpload;
import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.lecturer.application.vo.LecturerListVO;
import com.yizhi.util.application.date.DateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lly
 * @date 2019-4-29
 */

@Component
public class LecturerExportService extends AbstractDefaultTask<String, Map<String, Object>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(LecturerExportService.class);

    @Value("${ACTIVE}")
    public String active;


    @Override
    protected String execute(Map<String, Object> map) {

        LOGGER.info("讲师导出异步处理开始");
        String upload = null;

        Long companyId = (Long) map.get("companyId");
        Long siteId = (Long) map.get("siteId");
        String taskLogSerialNo = (String) map.get("taskLogSerialNo");
        Long taskId = System.currentTimeMillis();
        Long accountId = (Long) map.get("accountId");
        String taskName = "讲师库导出任务";
//        Date submitTime = new Date();
        List<LecturerListVO> list = (List<LecturerListVO>) map.get("list");
        LOGGER.info("讲师导出异步处理开始:" + list);

        //任务id   任务名字   操作人id  操作时间
//        TaskContext taskContext = new TaskContext(taskId, taskName, accountId, submitTime, siteId, companyId);
        TaskContext taskContext = new TaskContext(taskId, taskLogSerialNo, "讲师库导出", accountId, new Date(), siteId,
                companyId);
        LOGGER.info("taskContext:" + taskContext);
        working(taskContext);

        try {


            String[] headers = new String[]{"姓名","编码","手机号", "头衔", "学历","所属单位","来源", "评分","评级","在线课程", "线下课程", "培训项目", "授课数", "创建时间", "是否启用"};
            StringBuffer fileNameSb = new StringBuffer().append("lecturer").append("_").append(System.currentTimeMillis()).append(".xls");
            String fileName = fileNameSb.toString();
            String path = new StringBuffer().append(FileConstant.SAVE_PATH).append(File.separator).append(fileNameSb).toString();
            File fileDir = new File(path);
            if (!fileDir.exists()) {
                fileDir.createNewFile();
            }

            HSSFWorkbook workBook = null;
            FileOutputStream os = null;
            File file = null;
            try {
                os = new FileOutputStream(path);
                // 创建新的Excel 工作簿
                workBook = new HSSFWorkbook();

                // 在Excel工作簿中建一工作表，其名为缺省值
                HSSFSheet sheet = workBook.createSheet("讲师库");

                // 第一行
                HSSFRow row = sheet.createRow(0);
                for (int i = 0; i < headers.length; i++) {
                    row.createCell(i).setCellValue(headers[i]);
                }

                LecturerListVO lecturerListVO = null;
                // 填充数据
                for (int i = 0; i < list.size(); i++) {
                    lecturerListVO = list.get(i);
                    row = sheet.createRow(1 + i);
                    row.createCell(0).setCellValue(lecturerListVO.getLecturerName());
                    row.createCell(1).setCellValue(lecturerListVO.getCode());
                    row.createCell(2).setCellValue(lecturerListVO.getMobile());
                    row.createCell(3).setCellValue(lecturerListVO.getTitle());
                    row.createCell(4).setCellValue(lecturerListVO.getEdu());
                    row.createCell(5).setCellValue(lecturerListVO.getCompanyName());
                    row.createCell(6).setCellValue("inner".equals(lecturerListVO.getSourceCode()) ? "内部讲师" : "外部讲师");
                    row.createCell(7).setCellValue(lecturerListVO.getScore());
                    row.createCell(8).setCellValue(lecturerListVO.getGradeName());
                    row.createCell(9).setCellValue(lecturerListVO.getCourseCount());
                    row.createCell(10).setCellValue(lecturerListVO.getOfflineCount());
                    row.createCell(11).setCellValue(lecturerListVO.getTrainingCount());
                    row.createCell(12).setCellValue(lecturerListVO.getCourseCount()+lecturerListVO.getOfflineCount()+lecturerListVO.getTrainingCount());
                    row.createCell(13).setCellValue(DateUtil.format(lecturerListVO.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                    row.createCell(14).setCellValue((lecturerListVO.getStatus() == 1) ? "启用" : "停用");

//                    taskDetail(taskId, "导出数据第" + (i+1) + "行成功");
                }
                workBook.write(os);
                upload = OssUpload.upload(path, fileName, active);
                file = new File(path);
                success(taskContext, upload);
                System.out.println(upload);
            } catch (Exception e1) {
                fail(taskContext, upload);
                LOGGER.info(JSON.toJSONString(e1));
            } finally {
                if (os != null) {
                    os.close();
                }
                if (workBook != null) {
                    workBook.close();
                }
                if (file != null) {
                    file.delete();
                }
            }
            //阿里云返回url
        } catch (IOException e1) {

            fail(taskContext, upload);
            LOGGER.info(JSON.toJSONString(e1));
        }
        LOGGER.info("讲师库导出异步处理结束");
        return upload;
    }


}
