package cn.palmte.work.utils.excel;

import cn.palmte.work.config.ConfigProperties;
import cn.palmte.work.model.ExportExcelBean;
import cn.palmte.work.service.ExcelEventService;
import cn.palmte.work.utils.InterfaceUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.jfunc.common.utils.IoUtil;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ZM
 * @date 2018/9/21
 */
@Component
public class ExportExcelKit {
    private static final Logger logger = LoggerFactory.getLogger(ExportExcelKit.class);

    @Autowired
    ExcelEventService excelEventService;

    @Autowired
    private ConfigProperties configProperties;

    private EntityManagerFactory emf;

    @PersistenceUnit//使用这个标记来注入EntityManagerFactory
    public void setEntityManagerFactory(EntityManagerFactory emf) {
        this.emf = emf;
    }


    public JSONObject postExportEvent(String sql, String[] headers, String[] columns, String filePrefix) {
        String name = generateFileName(filePrefix);
        String filePath = getFilePath(name);
        String exportFileUrl = getExportFileUrl(name);
        logger.info(filePath);
        logger.info(exportFileUrl);
        JSONObject jo = null;
        try{
            String taskId = getUUID();
            //异步执行导出
            excelEventService.exportExcel(
                    new ExportExcelBean(taskId,
                            headers,
                            columns,
                            sql,
                            name,
                            filePath,
                            exportFileUrl,
                            InterfaceUtil.getAdminId(),
                    InterfaceUtil.getAdmin().getRealName()));
            jo = createDownloadBegingJSONObject(taskId);
        }
        catch(Exception e){
            logger.error(e.getMessage() , e);
        }
        return jo;
    }

    /**
     * 报表导出开始的返回信息，传入taskId，现在报表的导出异步化
     * @param taskId
     * @return
     */
    public static JSONObject createDownloadBegingJSONObject(String taskId){
        JSONObject jo = new JSONObject();
        jo.put("status", 1);
        jo.put("message", "导出开始，点击去下载，若没有则稍后刷新，也可以到\"报表中心/导出文件下载\"，任务号是 " + taskId);
        jo.put("taskId", taskId);
        return jo;
    }

    /**
     * @Description:获取文件名，根据日期创建导出文件名
     * @return String:文件名
     */
    public   String generateFileName(String prefix){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        return prefix + curTime + ".xlsx";
    }

    /**
     * @Description:获取保存文件路径
     * @param fileName:文件名
     */
    public  String getFilePath(String fileName){
        String filePath = "";
        String fileDir = configProperties.getUploadPath();
        if(!StringUtils.isEmpty(fileDir)){
            filePath = String.format("%s/file/%s", fileDir, fileName);
        }
        return filePath;
    }

    /**
     * 报表导出的URL下载地址
     */
    public  String getExportFileUrl(String fileName){
        return configProperties.getAdminDomain() + configProperties.getUploadPrefix() + "/file/" + fileName;
    }

    public  String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18) + uuid.substring(19, 23) + uuid.substring(24);
    }

    public void exportData(String[] headers,String[] columns,String sql,String exportFilePath) throws IOException {
        FileOutputStream fos = null;
        try {
            File file = new File(exportFilePath);
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(exportFilePath);
            EntityManager em = emf.createEntityManager();
            //加了这句就不会报错
            em.getTransaction().begin();
            Query query = null;
            query =  em.createNativeQuery(sql);
            List objecArraytList = query.getResultList();
            exportToExcel(headers, columns, objecArraytList, fos);
        } catch (IOException e) {
        }finally {
            IoUtil.close(fos);
        }
    }

    public <T> void exportToExcel(String[] headers , String[] columns , List<T> list, FileOutputStream fos) throws IOException {
        ExportUtils exportUtils = new ExportUtils(headers);
        long s1 = System.currentTimeMillis();
        exportUtils.exportExcel(columns,list,"yyyy-MM-dd HH:mm:ss",1);
        if( null!= fos) {
            exportUtils.write(fos);
        }
        long s2 = System.currentTimeMillis();
        logger.info("--------------------------导出耗时===={}秒   {} 毫秒  数据共  {}",(s2 - s1)/ 1000,(s2 - s1),list.size());
    }

}
