package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.UploadFile;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.mapper.UploadFileMapper;
import com.yeejoin.equipmanage.service.IUploadFileService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 *  服务实现类
 *
 * @author wujiang
 * @date 2020-07-07
 */
@Service
@Transactional
public class UploadFileServiceImpl extends ServiceImpl<UploadFileMapper, UploadFile> implements IUploadFileService {

	
	
	private FileUploadFactory factory;
	
	@Resource(name = "fileUploadFactory")
	public void setFactory(FileUploadFactory factory) {
		this.factory = factory;
	}
	

	@Override
	public long uploadFile(MultipartFile file,String type) throws UploadException, IOException{
		//验证文件
		String str= validateXLS(file);
		Workbook book=null;
		if(str.equals("xls")){
			 book = new HSSFWorkbook(file.getInputStream());
		}
		if(str.equals("xlsx")){
			book = new XSSFWorkbook(file.getInputStream());
		}
	    
		ImportFile up = factory.create(FileUploadTypeEnum.getEnum(type));
		
		Long count=up.importFile(book);
		return count;
	}
	
	public String validateXLS(MultipartFile file) throws FileTypeException {
		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
		if(!fileType.equals("xls")){
			if(!fileType.equals("xlsx")){
				throw new FileTypeException("文件格式不正确");
			}
			
		}
		return fileType;
	}
}
