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

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.MediaResources;
import cn.com.countrygarden.bi.main.model.dup.SiteResources;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.MediaResourcesService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 。媒体资源web
 * </pre>
 * 
 * @author developer developer@meicloud.com
 * @version 1.00.00
 * 
 *          <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 */

@RestController()
@RequestMapping("/api/fenghuang/MediaResourcesController")
public class MediaResourcesController {
	
	 @SuppressWarnings("unused")
	private final Logger logger = LoggerFactory.getLogger(MediaResourcesController.class);
	
	 @Resource
	 private MediaResourcesService  mediaResourcesService;
	 
	 @Autowired
	 private AccessTokenService accessTokenService;
	 
	 /**
	  * 查询媒体资源
	  * @param mediaResources
	  * @return
	  */
	 @RequestMapping(value = "/findMediaResourcesAlllike", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public  Result findMediaResourcesAlllike(MediaResources mediaResources) {
		return Response.response(mediaResourcesService.findMediaResourcesAlllike(mediaResources));
	 }
	 
	 /**
	  * 新增媒体资源
	  * @param mediaResources
	  * @return
	  */
	 @RequestMapping(value = "/addMediaResources", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public  boolean addMediaResources(MediaResources mediaResources) {
			return mediaResourcesService.addMediaResources(mediaResources);
		}
	 
	 /**
	  * 修改媒体资源
	  * @param mediaResources
	  * @return
	  */
	 @RequestMapping(value = "/updateMediaResources", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public  boolean updateMediaResources(MediaResources mediaResources) {
			return mediaResourcesService.updateMediaResources(mediaResources);
		}
	 
	 /**
	  * 删除媒体资源
	  * @param str
	  * @return
	  */
	 @RequestMapping(value = "/deleteMediaResources", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	 public  boolean deleteMediaResources(SiteResources siteResources) {
			return mediaResourcesService.deleteMediaResources(siteResources);
		}
	 
	 /**
	  * 媒体资源导出
	 * @throws ParseException 
	  */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportNoImport", produces = "multipart/form-data",  method = RequestMethod.GET)
	 public void ContractStatisticalNoImportExport(MediaResources mediaResources, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		 	Workbook workbook = new XSSFWorkbook();
	        Sheet sheet = workbook.createSheet();
	        ExcelHelper helper = new ExcelHelper();
	        helper.createMediaResourcesHeader(workbook,sheet);//创建表头
	        helper.createMediaResourcesBody((List<MediaResources>)mediaResourcesService.findMediaResourcesAlllike(mediaResources).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){

	            }
	        }
	 }
		
	@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");
        }
        mediaResourcesService.excelToObject(multipartFile,fileName,token.getUserCode());

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

    }

	/**
	 * 下载导入模板
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/download", produces = "multipart/form-data",  method = RequestMethod.GET)
	public ResponseEntity<byte[]> downloadSign(HttpServletResponse response,
											   @RequestParam(value = "fileKey", defaultValue = "", required = true) String fileKey) throws IOException {
		// todo 定义为常量
		Map<String, List<String>> map = new HashMap<>();
		List<String> mediaResources = new ArrayList<>();
		mediaResources.add("/excel/sqfz/mediaResources.xlsx");
		mediaResources.add("媒体资源.xlsx");
		map.put("mediaResources", mediaResources);

		List<String> siteResources = new ArrayList<>();
		siteResources.add("/excel/sqfz/siteResources.xlsx");
		siteResources.add("场地资源.xlsx");
		map.put("siteResources", siteResources);

		String path=this.getClass().getClassLoader().getResource("/").getPath() + map.get(fileKey).get(0);
		//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(map.get(fileKey).get(1).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);

	}
}
