package com.yizhi.application.course.util;

import com.alibaba.fastjson.JSON;
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.course.application.vo.domain.MaterialEntityVo;
import com.yizhi.system.application.system.remote.SiteClient;
import com.yizhi.system.application.vo.SiteVO;
import com.yizhi.util.application.date.DateUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


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

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

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

    @Autowired
	SiteClient siteClient;


	@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 siteName = "素材库素材下载_下载结果数据";
		Long taskId = System.currentTimeMillis();
		Long accountId = (Long) map.get("accountId");
		String taskName = "素材导出任务";
		Date submitTime = new Date();
		List<MaterialEntityVo> list = (List<MaterialEntityVo>) map.get("list");
		String[] types = new String[]{"音频","视频","文本","富媒体","Scrom","考试"};
		String[] soures = new String[]{"外部采购", "外部定制", "内部定制", "做课"};

        List<Long> ids = new ArrayList<>();
        ids.add(siteId);
        List<SiteVO> siteVOS = siteClient.selectByIds(ids);
        if (null != siteVOS && siteVOS.size() > 0) {
            siteName = siteVOS.get(0).getName();
        }

        StringBuffer a=new StringBuffer().append(siteName).append("_").append(taskName);
        taskName=a.toString();
		//创建任务

		//任务id   任务名字   操作人id  操作时间
		TaskContext taskContext = new TaskContext(taskId, taskName, Long.valueOf(String.valueOf(accountId)), submitTime, Long.valueOf(String.valueOf(siteId)), Long.valueOf(String.valueOf(companyId)));
		working(taskContext);

		try {


			String[] headers = new String[]{"素材编号", "素材名称", "素材类型", "素材来源", "创建时间", "素材时长"};
			StringBuffer fileNameSb = new StringBuffer().append(siteName).append("_").append("素材库导出").append("_").append(System.currentTimeMillis()).append(".xls");
			String fileName = fileNameSb.toString();
			String path = new StringBuffer().append(FileConstant.SAVE_PATH).append(File.separator).append(fileNameSb).toString();
//			String path = new StringBuffer().append("D:\\test").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);
				CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 5); // 起始行, 终止行, 起始列, 终止列
				sheet.addMergedRegion(cra);
				HSSFCell cell = row.createCell((short) 0);
				cell.setCellValue(map.get("siteName")  + "-" + "素材清单"  + cn.hutool.core.date.DateUtil.format(submitTime, "yyyyMMddHHmmss"));

				row = sheet.createRow(1);
				for (int i = 0; i < headers.length; i++) {
					row.createCell(i).setCellValue(headers[i]);
				}

				MaterialEntityVo evo1 = null;
				// 填充数据
				for (int i = 0; i < list.size(); i++) {
					evo1 = list.get(i);
					row = sheet.createRow(2 + i);
					row.createCell(0).setCellValue(evo1.getCode());
					row.createCell(1).setCellValue(evo1.getName());
					row.createCell(2).setCellValue(types[evo1.getType()-1]);
					row.createCell(3).setCellValue(soures[evo1.getSource()-1]);
					row.createCell(4).setCellValue(DateUtil.format(evo1.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
					if (evo1.getTextHour() != null || evo1.getTextMinute() != null || evo1.getTextHour() != null) {
						String hour = evo1.getTextHour() == null? "0" : String.valueOf(evo1.getTextHour());
						String minute = evo1.getTextMinute() == null? "0" : String.valueOf(evo1.getTextMinute());
						String second = evo1.getTextSecond() == null? "0" : String.valueOf(evo1.getTextSecond());
						row.createCell(5).setCellValue(hour + "时" + minute + "分" + second + "秒");
					} else {
						row.createCell(5).setCellValue("--");
					}
					taskDetail(taskId, "导出数据第+" + i + "+行成功");
				}
				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) {
			// TODO Auto-generated catch block
			fail(taskContext, upload);
			LOGGER.info(JSON.toJSONString(e1));
		}
		LOGGER.info("素材导出异步处理结束");
		return upload;
	}






}
