package com.ruoyi.ibs.task.service.impl;


import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.ibs.task.domain.entity.ImportExportTask;
import com.ruoyi.ibs.task.mapper.ImportExportTaskMapper;
import com.ruoyi.ibs.task.service.ImportExportTaskService;
import com.ruoyi.system.enums.OssFileEnum;
import com.ruoyi.system.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class ImportExportTaskServiceImpl implements ImportExportTaskService {

    @Resource
    private ImportExportTaskMapper importExportTaskMapper;

    @Resource
    private OssFileService ossFileService;

    @Override
    public List<ImportExportTask> getTaskList() {
        return importExportTaskMapper.taskList(SecurityUtils.getUsername());
    }

    @Override
    public <T> String exportExcelAndUpload(List<T> dataList, Class<T> clazz, String fileName, OssFileEnum fileEnum, String userName) {
        ImportExportTask task = new ImportExportTask();
        String taskId = IdUtils.randomUUID();
        task.setId(taskId);
        task.setStatus("0");
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(now);
        task.setFileName(formattedDate + fileName);
        task.setUserName(userName);
        task.setCreateTime(now);
        importExportTaskMapper.insert(task);
        File tempFile = null;
        try {
            tempFile = File.createTempFile(fileName, ".xlsx");
            EasyExcel.write(tempFile, clazz).sheet(fileName).doWrite(dataList);
            String ossUUId = ossFileService.uploadFileToOss(fileEnum, tempFile, fileName + taskId + ".xlsx", userName);
//            ImportExportTask task1 = importExportTaskMapper.selectById(taskId);
            task.setStatus("1");
            task.setFileUrl(ossUUId);
            task.setFinishTime(new Date());
            importExportTaskMapper.updateById(task);
            return ossUUId;
        }catch (Exception e){
            task.setStatus("2");
            task.setFinishTime(new Date());
            task.setErrorMsg(e.getMessage());
            importExportTaskMapper.updateById(task);
            return "";
        }finally {
            //删除临时文件
            if (Objects.nonNull(tempFile)){
                boolean deleted = tempFile.delete();
                if (!deleted){
                    log.error("临时文件删除失败" + tempFile.getAbsolutePath());
                }
            }
        }
    }

}
