package org.springblade.flow.datalog.service;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.flow.datalog.mapper.DataImportLogMapper;
import org.springblade.flow.datalog.model.DataImportLog;
import org.springblade.flow.visual.onlinedev.formdata.excel.ExcelFormParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 
 * @author William
 * @date 2022年11月17日 上午11:55:38
 */
@Service
@DS("bi")
public class DataImportLogService extends ServiceImpl<DataImportLogMapper, DataImportLog> {
	@Value("${blade.file.uploadPath}")
	private String uploadDir;

	/**
	 * 保存导入日志
	 * 
	 * @param params
	 * @param count
	 * @param cubeId
	 */
	public void saveLog(ExcelFormParam params, long count, Integer cubeId, float takeUpTime) {
		long fileSize = 0;
		String filePath = uploadDir + params.getFile().replace("uploads/", "");
		File excelFile = new File(filePath);
		if (excelFile != null && excelFile.exists()) {
			fileSize = excelFile.length();
		}

		DataImportLog bean = DataImportLog.builder()
				.count(count)
				.createTime(new Date())
				.cubeId(cubeId)
				.filePath(params.getFile())
				.fileSize(fileSize)
				.finishTime(new Date())
				.isTruncate(params.isTruncate() ? 1 : 0)
				.modelId(params.getModelId())
				.name(params.getName())
				.operatorId(SecureUtil.getUserId())
				.operator(SecureUtil.getNickName())
				.rule(JSON.toJSONString(params.getList()))
				.status(1)
				.takeUpTime(BigDecimal.valueOf(takeUpTime))
				.withHeader(params.getWithHeader() ? 1 : 0)
				.build();
		save(bean);
	}
}
