package cn.com.countrygarden.bi.main.controller.project;


import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.countrygarden.bi.main.controller.project.imports.ProjectSignInfoImports;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.project.ProjectTargetService;
import cn.com.countrygarden.bi.main.util.ProjectTargetExcel;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@RestController("ProjectTargetController")
@RequestMapping("/api/project/target")
public class ProjectTargetController {
	 @Autowired
	 private ProjectTargetService projectTarget;
	 @Autowired
	    private AccessTokenService accessTokenService;
	 
	 @RequestMapping(value = "/list", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	 public Object search(@RequestParam(value = "year", required = false, defaultValue = "") String year,
			 @RequestParam(value = "skip", required = false, defaultValue = "") Integer page,
			 @RequestParam(value = "limit", required = false, defaultValue = "") Integer size
			 
			 ) {
		 if(null == year || "".equals(year)) {
			 throw new ServiceException("年份不能为空");
		 }
		return Response.response(projectTarget.select(year,page,size));
	 }
	 @RequestMapping(value = "/delete/{id}", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	 public Object delete(@PathVariable Integer id) {
		 return Response.response(projectTarget.delete(id));
	 }
	 @ResponseBody
	    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	    public Result upload(@RequestParam(value = "name", defaultValue = "1", required = true) String name,
	                         @RequestParam(value = "uploadfile", defaultValue = "", required = true) MultipartFile multipartFile,
	                         @RequestParam(value = "year", defaultValue = "", required = true) String year,
	                         HttpServletRequest request, HttpServletResponse response) throws ServiceException, IOException {
	        String accessToken = request.getParameter("AccessToken");
	        AccessToken token = accessTokenService.findByToken(accessToken);
	        if (multipartFile == null) {
	            throw new ServiceException("请选择需要上传的文件");
	        }else if(name == null){
	            throw new ServiceException("请输入文件名");
	        }
	        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
	        if (commonsMultipartFile.isEmpty()) {
	            return Response.responseFail("上传文件为空文件");
	        }
	        String fileName = commonsMultipartFile.getOriginalFilename();
//	        if (fileName.indexOf(".xlsx") <= 0 || fileName.indexOf(".xls") <= 0) {
//	            return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
//	        }
	        projectTarget.excelToObject(multipartFile,name,token.getUserCode(),year);

	        return Response.response("导入成功");

	    }
	 @SuppressWarnings("unchecked")
		@RequestMapping(value = "/download", produces = "multipart/form-data",  method = RequestMethod.GET)
		public  ResponseEntity<byte[]>  downloadSign(HttpServletResponse response) throws IOException {
			String path=this.getClass().getClassLoader().getResource("/").getPath() + "/excel/target.xlsx";
			//this.getClass().getClassLoder().getResource(path).getPath()
			String relativelyPath=System.getProperty("user.dir");
			System.out.println(relativelyPath);
			 File file=new File(path);  
		        HttpHeaders headers = new HttpHeaders();  
		        String fileName = "";
		      
					fileName=new String("目标管理.xlsx".getBytes("UTF-8"),"iso-8859-1");
				
					headers.setContentDispositionFormData("attachment", fileName); 
					//application/octet-stream ： 二进制流数据（最常见的文件下载）。
					headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
					return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
		                headers, HttpStatus.CREATED);  
		        
		}
}
