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

import java.io.File;
import java.io.FileOutputStream;
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.HashMap;
import java.util.List;
import java.util.Map;

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

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
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 cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.exception.ServiceCodeException;
import cn.com.countrygarden.bi.main.model.dup.SiteResources;
import cn.com.countrygarden.bi.main.model.mediaResource.AdvertisingFileDirectory;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.SiteResourcesService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;


/**
 * 
 * 
 * <pre>
 * 。场地资源web
 * </pre>
 * 
 * @author developer developer@meicloud.com
 * @version 1.00.00
 * 
 *          <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 */
@Slf4j
@RestController()
@RequestMapping("/api/fenghuang/SiteResourcesController")
public class SiteResourcesController {
	 private final Logger logger = LoggerFactory.getLogger(ContractStatisticalController.class);
	 
	 @Resource
	 private SiteResourcesService siteResourcesService;
	 
	 @Resource
	 private  AccessTokenService accessTokenService;
	 
	 @Autowired
	 private Environment env;
	 /**
	  * 查询所有
	 * @throws ParseException 
	  */
	 @RequestMapping(value = "/findAllSiteResourcesControllerLike", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public Result findAllSiteResourcesControllerLike(SiteResources siteResources,HttpServletRequest request) {
		    try {
	               return Response.response(siteResourcesService.findAllSiteResourcesControllerLike(siteResources,request));
	            } catch (ServiceCodeException e) {
	                return ResultGenerator.genFailureResult(e.getMessage());
	            } catch (Exception e) {
				log.error("{}", e);
	                e.printStackTrace();
	                return ResultGenerator.genFailResult("查询失败");
	            }
	 }
	 
	 
	   /**
      * 返回资源编号
     * @throws ParseException 
      */
     @RequestMapping(value = "/getResourcesId", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
     public Result getResourcesId(SiteResources siteResources,HttpServletRequest request) {
            try {
                   return Response.response(siteResourcesService.generateId(siteResources));
                } catch (ServiceCodeException e) {
                    return ResultGenerator.genFailureResult(e.getMessage());
                } catch (Exception e) {
				log.error("{}", e);
                    e.printStackTrace();
                    return ResultGenerator.genFailResult("生成资源编号失败");
                }
     }
	 
	 
	 /**
	  * 新增和更新场地资源
	  * @param siteResources
	  * @return
	 * @throws ParseException 
	  */
	 @RequestMapping(value = "/insertSiteResources", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public Result insertSiteResources(SiteResources siteResources,HttpServletRequest request)throws IOException {
		   try {
		       return siteResourcesService.insertResources(siteResources,request);
	        } catch (ServiceCodeException e) {
	            return ResultGenerator.genFailureResult(e.getMessage());
	        } catch (Exception e) {
			   log.error("{}", e);
	            e.printStackTrace();
	            return ResultGenerator.genFailResult("保存场地信息错误");
	        }

	 }
	 
	 
	   /**
      * 查询字典值
      * @param
      * @return
     * @throws ParseException 
      */
     @RequestMapping(value = "/findByDictCode", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
     public Result findByDictCode(@RequestParam("code")String  code) throws ParseException {
         try {
             return new Result().setResultCode(ResultCode.OK).setResultMsg(AdvertisingFileDirectory.SUCESS).setData(siteResourcesService.findByDictCode(code));
            } catch (Exception e) {
			 log.error("{}", e);
                e.printStackTrace();
                return ResultGenerator.genFailResult("查询字典值出错");
            }
     }
	 
	 /**
	  * 更新
	  * @param siteResources
	  * @return
	  */
/*	 @RequestMapping(value = "/updateSiteResources", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public boolean updateSiteResources(SiteResources siteResources) {
			return siteResourcesService.updateResources(siteResources);
	 }*/
	 
	 /**
	  * 删除
	  * @param siteResources
	  * @return
	  */
	 @RequestMapping(value = "/deleteSiteResources", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public Result deleteSiteResources(SiteResources siteResources) {
	       try {
	             return siteResourcesService.deleteResources(siteResources);
	            } catch (Exception e) {
			   log.error("{}", e);
	                e.printStackTrace();
	                return ResultGenerator.genFailResult("删除资源错误");
	            }
	 }
	 
/*	 @ResponseBody
	 @RequestMapping(value = "/fileUpload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	  public Result fileUpload(@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(".jpg") <= 0 || fileName.indexOf(".png") <= 0) {
	            return Response.responseFail("上传文件应为excel文件格式为：jpg 或 png");
	        }
	        Map<String, Object> resultMap = new HashMap<>();
	        
	        resultMap.put("files", fileName.toString());

	        return Response.response(resultMap);
	    }*/
	 
	 /**
	  * 字符串转日期
	 * @throws ParseException 
	  */
	 private Date StringChangeDate(String str) throws ParseException {	  
		  Date date=null; 
		  SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		  return date=formatter.parse(str); 
	 }
	 
	 /**
	  * 场地资源导出
	 * @throws ParseException 
	  */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportNoImport",method = RequestMethod.GET)
	 public Result ContractStatisticalNoImportExport(SiteResources siteResources, HttpServletRequest request, HttpServletResponse response){
	    Workbook workbook = new XSSFWorkbook();
	    try {
	        
	        List<Map<String, String>> resourceType = siteResourcesService.findByDictCode("RESOURCE_TYPE");
	        List<Map<String, String>> resourceName = siteResourcesService.findByDictCode("RESOURCE_NAME");
	        List<Map<String, String>> useStatus = siteResourcesService.findByDictCode("USE_STATUS");
	        List<Map<String, String>> commCityLevel = siteResourcesService.findByDictCode("COMM_CITY_LEVEL");
	           List<Map<String, String>> siteUnit = siteResourcesService.findByDictCode("SITE_UNIT");
	        Map<String,List<Map<String, String>>> map=new HashMap<>();
	        map.put("resourceType",resourceType);
	        map.put("resourceName",resourceName);
	        map.put("useStatus",useStatus);
	        map.put("commCityLevel",commCityLevel);
	        map.put("siteUnit",siteUnit);
	        
            Sheet sheet = workbook.createSheet();
            ExcelHelper helper = new ExcelHelper();
            helper.createSiteResourcesHeader(workbook,sheet);//创建表头
            helper.createSiteResourcesBody((List<SiteResources>)siteResourcesService.findAllSiteResources(siteResources,request),workbook,sheet,map);
            response.setContentType("multipart/form-data");
            
            String fileName = getFileName(request,"场地资源.xlsx");

             response.setHeader("Content-Disposition", "attachment;fileName="+fileName);

            OutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);
            
/*            FileOutputStream fileOutputStream=new FileOutputStream("E:\\场地资原型设计\\rrrrr.xlsx");
            workbook.write(fileOutputStream);*/
             return Response.response();
         } catch (ServiceCodeException e) {
             return ResultGenerator.genFailureResult(e.getMessage());
         } catch (Exception e) {
			log.error("{}", e);
             e.printStackTrace();
             return ResultGenerator.genFailResult("导出失败");
         }finally {
                try{
                    workbook.close();
                } catch (Exception ex){

                }
            }
	 }
	
	
	public String getFileName(HttpServletRequest request,String fileName) throws UnsupportedEncodingException{
	       final String userAgent = request.getHeader("USER-AGENT");

           if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
               fileName = URLEncoder.encode(fileName,"UTF8");
           }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
               fileName = new String(fileName.getBytes(), "ISO8859-1");
           }else{
               fileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
           }
           return fileName;
	}
	
	@ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "name", defaultValue = "1", required = true) String fileName,
                         @RequestParam(value = "uploadfiles", defaultValue = "", required = true) MultipartFile multipartFile,
                         HttpServletRequest request, HttpServletResponse response) throws Exception{
	    try {
            return siteResourcesService.excelToObject(multipartFile,request,fileName);
           } catch (ServiceCodeException e) {
               return ResultGenerator.genFailureResult(e.getMessage());
           } catch (Exception e) {
			log.error("{}", e);
               e.printStackTrace();
               return ResultGenerator.genFailResult("批量导入错误");
           }
	   
    }
	
	/**
	 * 图片上传
	 * @param file
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	   @ResponseBody
	    @RequestMapping(value = "/uploadImage", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public  Result uploadImage(@RequestParam(value = "file",required = true)MultipartFile file,HttpServletRequest request) throws IOException{  
	       try {
	            return Response.response(siteResourcesService.uploadFile(file,request));
	           } catch (ServiceCodeException e) {
	               return ResultGenerator.genFailureResult(e.getMessage());
	           } catch (Exception e) {
			   log.error("{}", e);
	               e.printStackTrace();
	               return ResultGenerator.genFailResult("上传图片错误");
	           }
    }
	
	
	
}
