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

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;

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

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.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;

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.model.dup.LastTransferDetail;
import cn.com.countrygarden.bi.main.model.dup.LastTransferDetailReports;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.LastTransferDetailService;
import cn.com.countrygarden.bi.main.service.dup.impl.LastTransferDetailServiceImpl;

/**
 * <pre>
 * 。尾盘移交明细Web
 * </pre>
 * 
 * @author developer developer@meicloud.com
 * @version 1.00.00
 * 
 *          <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 */
@RestController()
@RequestMapping("/api/biapp/LastTransferDetailController")
public class LastTransferDetailController {
	
	@Resource
	private LastTransferDetailService lastTransferDetailService;

	@Resource
	private AccessTokenService accessTokenService;
	
	/**
	 * 查询尾盘转移数据(支持模糊查询)
	 * @param lastTransferDetail
	 * @return
	 */
	@RequestMapping(value = "/findAllSellDataManagementControllerLike", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result findLastTransferDetailLike(LastTransferDetail lastTransferDetail) {
		return Response.response(lastTransferDetailService.findLastTransferDetailLike(lastTransferDetail));
	}
	
	/**
	 * 修改尾盘转移数据
	 * @param lastTransferDetail
	 * @return
	 */
	@RequestMapping(value = "/updataLastTransferDetail", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public boolean updataLastTransferDetail(LastTransferDetail lastTransferDetail) {
		return lastTransferDetailService.updataLastTransferDetail(lastTransferDetail);
	}
	
	/**
	 * 删除尾盘转移数据
	 * @param lastTransferDetail
	 * @return
	 */
	@RequestMapping(value = "/deleteLastTransferDetail", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public boolean deleteLastTransferDetail(LastTransferDetail lastTransferDetail) {
		return lastTransferDetailService.deleteLastTransferDetail(lastTransferDetail);
	}
	
	/**
	 * Excel尾盘转移数据
	 */
	@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 = "uploadfiles", defaultValue = "", required = true) MultipartFile multipartFile,
                         HttpServletRequest request, HttpServletResponse response) throws ServiceException {
		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");
		}
		lastTransferDetailService.excelToObject(multipartFile,fileName,token.getUserCode());
		return Response.response("导入成功");
	}
	
	
	/**
	 * 导出尾盘转移的数据
	 * @param siteResources
	 * @param request
	 * @param response
	 * @throws ParseException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportNoImport", produces = "multipart/form-data",  method = RequestMethod.GET)
	public void ContractStatisticalNoImportExport(LastTransferDetail lastTransferDetail, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		 	Workbook workbook = new XSSFWorkbook();
	        Sheet sheet = workbook.createSheet();
	        LastTransferDetailServiceImpl helper = new LastTransferDetailServiceImpl();
	        helper.createLastTransferDetailHeader(workbook,sheet);//创建表头
	        helper.createLastTransferDetailBody((List<LastTransferDetail>)lastTransferDetailService.findLastTransferDetailLike(lastTransferDetail).getData(),workbook,sheet);
	        response.setContentType("multipart/form-data");
	        String fileName = "export.xlsx";
	        try {
	            fileName = URLEncoder.encode("尾盘货量移交明细.xlsx","UTF-8");
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }
	        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);

	        OutputStream outputStream =null;
	        try{
	            outputStream = response.getOutputStream();
	            workbook.write(outputStream);
	        } catch (Exception ex){

	        } finally {
	            try{
	                workbook.close();
	            } catch (Exception ex){

	            }
	        }
	 }
	
	/**
	 * 查询尾盘转移数据报表(支持模糊查询)
	 * @param lastTransferDetail
	 * @return
	 */
	@RequestMapping(value = "/findLastTransferDetailLikeReports", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result findLastTransferDetailLikeReports(LastTransferDetailReports lastTransferDetailReports) {
		return Response.response(lastTransferDetailService.findLastTransferDetailLikeReports(lastTransferDetailReports));
	}
	
	@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/trans.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);  
	        
	}
}
