package lingtao.net.controller;

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

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

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lingtao.net.bean.Msg;
import lingtao.net.bean.MyFile;
import lingtao.net.service.MyFileService;

@Controller
public class FileController {

	@Autowired
	private MyFileService fileService;

	/**
	 * 上传文件
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/fileUpload")
	@ResponseBody
	public Msg uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		return fileService.fileUpload(file, request);
	}

	/**
	 * 查询文件列表
	 * @param page
	 * @param limit
	 * @param myFile
	 * @param session
	 * @return
	 */
	@RequestMapping("getAllFiles")
	@ResponseBody
	public Msg FileList(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "limit", defaultValue = "10") Integer limit, MyFile myFile, HttpSession session) {
		PageHelper.startPage(page, limit);
		List<MyFile> fileList = fileService.getFileList(myFile, session);
		PageInfo<MyFile> filesInfo = new PageInfo<MyFile>(fileList);
		return Msg.success().add("fileList", filesInfo);
	}

	/**
	 * 根据id删除文件
	 * 
	 */
	@RequestMapping("/deleteFile")
	@ResponseBody
	public Msg deleteFile(@Param("fileId") Integer fileId) {
		return fileService.deleteFile(fileId);
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 */
	@ResponseBody
	@RequestMapping("/deleteFiles")
	public Msg deleteBatch(@RequestParam(value = "ids") String ids, @RequestParam(value = "fileNames") String fileNames,
			HttpServletRequest request) {
		String[] arrIds = ids.split(",");
		String[] fileNameArr = fileNames.split(";");
		List<Integer> del_ids = new ArrayList<Integer>();
		String hasFileload = request.getSession().getServletContext().getRealPath("/") + "/deptFile/";
		for (int i = 0; i < fileNameArr.length; i++) {
			del_ids.add(Integer.parseInt(arrIds[i]));
			fileService.deleteBatch(del_ids);
			fileService.deleteFile(hasFileload + fileNameArr[i]);
		}
		return Msg.success();
	}
}
