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

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

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.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
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 cn.com.countrygarden.bi.main.controller.project.imports.ProjectSignInfoImports;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.dup.SiteResources;
import cn.com.countrygarden.bi.main.model.project.ProjectSign;
import cn.com.countrygarden.bi.main.model.project.ProjectSignInfo;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.project.ProjectSignInfoService;
import cn.com.countrygarden.bi.main.service.project.ProjectSignService;
import freemarker.core.ParseException;
import tk.mybatis.mapper.util.StringUtil;
/**
 * 签约明细 项目基本信息
 * 
 * <pre>
 * 。
 * </pre>
 * 
 * @author developer developer@meicloud.com
 * @version 1.00.00
 * 
 *          <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 */
@RestController("ProjectSignController")
@RequestMapping("/api/project/sign")
public class ProjectSignController {
	@Autowired
	ProjectSignService projectSignService;
	  @Autowired
	    private AccessTokenService accessTokenService;
	  @Autowired
	  private ProjectSignInfoService projectSignInfoService;
	@RequestMapping(value = "/list", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	public Object search(
			 @RequestParam(value = "name", required = false, defaultValue = "") String name
			) {
		ProjectSign ps = new ProjectSign();
		ps.setIsDelete(0);
		if(null != name && !"".equals(name)) {
			ps.setProjectName(name);
		}
		return Response.response(projectSignService.search(ps));
	}
	 @ResponseBody
	 @RequestMapping(value = "/findOne/{id}", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	public Object findOne(@PathVariable Integer id) {
		return Response.response(projectSignService.findOne(id));
	}
	 
	 @RequestMapping(value = "/delete/{id}", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	public Object delete(@PathVariable Integer id) {
		return Response.response(projectSignService.delete(id));
	}
	 @ResponseBody
	 @RequestMapping(value = "/save", method = {RequestMethod.POST}, produces = {"application/json;charset=utf-8"})
	public Object save(  
			
			  @RequestParam(value = "organName", required = false) String organName,
			  @RequestParam(value = "proposalOrganId", required = false, defaultValue = "0") String proposalOrganId,
			  @RequestParam(value = "projectName", required = false, defaultValue = "") String projectName,
			  @RequestParam(value = "province", required = false, defaultValue = "") String province,
			  @RequestParam(value = "signTime", required = false, defaultValue = "") @DateTimeFormat(pattern="yyyy-MM-dd")Date signTime,
			  @RequestParam(value = "endTime", required = false, defaultValue = "") @DateTimeFormat(pattern="yyyy-MM-dd")Date endTime,
			  @RequestParam(value = "inMonth", required = false, defaultValue = "") String inMonth,HttpServletRequest request, HttpServletResponse response
			  ) {
		 Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");  
		 Integer id = null;
		 String projectNature = null;
		 Integer isNew = null;
		 String corpType = null;
	
		 BigDecimal contractArea = null;
		 if( null != request.getParameter("id") &&pattern.matcher(request.getParameter("id")).matches() ) {
			 id = Integer.parseInt(request.getParameter("id"));
		 }
		 
			 projectNature = request.getParameter("projectNatureName");
		
		 if( pattern.matcher(request.getParameter("isNew")).matches() ) {
			 isNew = Integer.parseInt(request.getParameter("isNew"));
		 }
		
			 corpType = request.getParameter("corpTypeName");
		 
		 if( pattern.matcher(request.getParameter("contractArea")).matches() ) {
			 contractArea = new BigDecimal(request.getParameter("contractArea"));
		 }
		 SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd");
		 
		ProjectSign p = new ProjectSign();
		p.setSingTimeStr(dtf.format(signTime));
		p.setEndTimeStr(dtf.format(endTime));
		p.setId(id);
		p.setOrganName(organName);
		p.setProposalOrganId(proposalOrganId);
		p.setProjectName(projectName);
		p.setProjectNatureName(projectNature);
		
		p.setIsNew(isNew);
		p.setCorpTypeName(corpType);
		p.setContractArea(contractArea);
		p.setSignTime(signTime);
		p.setEndTime(endTime);
		p.setInMonth(inMonth);
		p.setProvince(province);
		p.setIsDelete(0);
		 String accessToken = request.getParameter("AccessToken");
		  AccessToken token = accessTokenService.findByToken(accessToken);
		return Response.response(projectSignService.save(p, token.getUserCode()));
	}

	 @RequestMapping(value = "/infoFrom", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	 public Object infoFrom(
			 @RequestParam(value = "year", required = false, defaultValue = "") String year,
			 @RequestParam(value = "skip", required = false, defaultValue = "") Integer page,
			 @RequestParam(value = "limit", required = false, defaultValue = "") Integer size
		) {

		return  Response.response(projectSignInfoService.search(year, page, size));
	 }
	 
	 @RequestMapping(value = "/statistical", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
	 public Object infoFrom(
			 @RequestParam(value = "year", required = false, defaultValue = "") String year
		) {
		 projectSignInfoService.statistical(year);
		
		return  Response.response(1);
	 }
	 
	 /**
	  * 导出
	 * @throws ParseException 
	  */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/export", produces = "multipart/form-data",  method = RequestMethod.GET)
	 public void ContractStatisticalNoImportExport(String year, HttpServletRequest request, HttpServletResponse response) throws ParseException {
//		 if(!StringUtil.isEmpty(siteResources.getAddDates())) {
//			 siteResources.setAddDate(StringChangeDate(siteResources.getAddDates()));
//			 }
		 	Workbook workbook = new XSSFWorkbook();
	        Sheet sheet = workbook.createSheet();
	        List<ProjectSignInfo> pList = projectSignInfoService.findListByYear(year);
	        ProjectSignInfoImports helper = new ProjectSignInfoImports();
	        helper.createHeader(workbook,sheet);//创建表头
	        helper.createBody(pList,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){

	            }
	        }
	 }
	@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() + ProjectSignInfoImports.PATH;
		//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);  
	        
	}
}
