package lingtao.net.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import lingtao.net.bean.Msg;
import lingtao.net.bean.MyFile;
import lingtao.net.bean.MyFileExample;
import lingtao.net.bean.MyFileExample.Criteria;
import lingtao.net.dao.MyFileMapper;

@Service
public class MyFileService {

	@Autowired
	MyFileMapper fileMapper;

	// 文件上传
	public Msg fileUpload(MultipartFile file, HttpServletRequest request) {
		try {
			// 获取存放路径
			String path = request.getSession().getServletContext().getRealPath("/deptFile");
			// 判断路径是否存在
			File upfile = new File(path);
			if (!upfile.exists()) {
				upfile.mkdirs();
			}
			// 获得文件名
			String filename = file.getOriginalFilename();
			upfile = new File(path + "/" + filename);
			MyFile myFile = new MyFile();
			// 将文件移动到指定路径中
			file.transferTo(upfile);
			myFile.setFileName(filename);
			myFile.setFilePath(path);
			myFile.setCreateBy("admin");
			fileMapper.insertSelective(myFile);
			return Msg.success();
		} catch (IOException e) {
			return Msg.fail();
		}
	}

	// 获取所有的文件信息
	public List<MyFile> getFileList(MyFile myFile, HttpSession session) {
		return fileMapper.getFileList(myFile);
	}

	// 根据ID删除文件
	public Msg deleteFile(Integer fileId) {
		try {
			fileMapper.deleteByPrimaryKey(fileId);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail("删除失败");
		}
	}

	// 批量删除文件
	public Msg deleteBatch(List<Integer> del_ids) {
		MyFileExample example = new MyFileExample();
		Criteria criteria = example.createCriteria();
		criteria.andFileIdIn(del_ids);
		try {
			fileMapper.deleteByExample(example);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail();
		}
	}

	// 同时删除服务器中的文件
	public boolean deleteFile(String delFileName) {
		boolean flag = false;
		File file = new File(delFileName);
		// 判断目录或文件是否存在
		if (!file.exists()) { // 不存在返回 false
			return flag;
		} else {
			flag = true;
			file.delete();
		}
		return flag;
	}
}
