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.text.SimpleDateFormat;
import java.util.Date;
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.SellDataManagement;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.SellDataManagementService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;

/**
 * <pre>
 * 。营销数据管理Web
 * </pre>
 * 
 * @author developer developer@meicloud.com
 * @version 1.00.00
 * 
 *          <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 *          </pre>
 */
@RestController()
@RequestMapping("/api/fenghuang/SellDataManagementController")
public class SellDataManagementController {

	@Resource
	private AccessTokenService accessTokenService;

	@Resource
	private SellDataManagementService sellDataManagementService;
	
	@Resource
	private TbSysUserService userService;
	/**
	 * 营销数据管理模糊查询
	 * @param sellDataManagement
	 * @return
	 */
	@RequestMapping(value = "/findAllSellDataManagementControllerLike", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result findAllSellDataManagementControllerLike(SellDataManagement sellDataManagement) {
		Result l = Response.response(sellDataManagementService.findAllSellDataManagementControllerLike(sellDataManagement));
		return l;
	}

	/**
	 * 更新营销数据管理--修改审核状态
	 * 
	 * @return
	 */
	@RequestMapping(value = "/updateSellDataManagement", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public boolean updateSellDataManagement(SellDataManagement sellDataManagement) {
		//获取当前用户为审核人
		TbSysUser sysUser = userService.getCurrentSysUser();
		sellDataManagement.setName(sysUser.getUserName());
		sellDataManagement.setVerifytype("1");
		sellDataManagement.setPurchasingDate(StringChangeDate(sellDataManagement.getPurchasingDates()));
		sellDataManagement.setSignatureDate(StringChangeDate(sellDataManagement.getSignatureDates()));
		return sellDataManagementService.updateSellDataManagement(sellDataManagement);
	}
	
	/**
	 * 删除 营销数据管理
	 * @param sellDataManagement
	 * @return
	 */
	@RequestMapping(value = "/deleteSellDataManagement", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public boolean deleteSellDataManagement(SellDataManagement sellDataManagement) {
		return sellDataManagementService.deleteSellDataManagement(sellDataManagement);
	}

	/**
	 * 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");
		}
		sellDataManagementService.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(SellDataManagement sellDataManagement, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		 	Workbook workbook = new XSSFWorkbook();
	        Sheet sheet = workbook.createSheet();;
	        ExcelHelper helper = new ExcelHelper();
	        helper.createSellDataManagementHeader(workbook,sheet);//创建表头
	        helper.createSellDataManagementBody((List<SellDataManagement>)sellDataManagementService.findAllSellDataManagementControllerLike(sellDataManagement).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){

	            }
	        }
	 }
	 /**
	  * 字符串转日期
	 * @throws ParseException 
	  */
	 private Date StringChangeDate(String str)  {	  
		  Date date=null; 
		  SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd"); 
		  try {
			return date=formatter.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date; 
	 }
	 
	 	/**
		 *返回总数
		 * @param sellDataManagement
		 * @return
		 */
		@RequestMapping(value = "/findtotalNumber", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
		public Result findtotalNumber(SellDataManagement sellDataManagement) {
			return Response.response(sellDataManagementService.findtotalNumber(sellDataManagement));
		}
		@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/sell.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);  
		        
		}
}
