package com.yeejoin.equipmanage.service.impl;

import java.io.IOException;

import javax.annotation.Resource;

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 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.UploadFile;
import com.yeejoin.equipmanage.mapper.UploadFileMapper;
import com.yeejoin.equipmanage.common.utils.FileTypeException;
import com.yeejoin.equipmanage.common.utils.FileUploadFactory;
import com.yeejoin.equipmanage.common.utils.FileUploadTypeEnum;
import com.yeejoin.equipmanage.common.utils.ImportFile;
import com.yeejoin.equipmanage.common.utils.UploadException;
import com.yeejoin.equipmanage.service.IUploadFileService;

/**
 *  服务实现类
 *
 * @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;
	}
}
