package com.cab.controller;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

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

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cab.model.Content;
import com.cab.model.ContentType;
import com.cab.service.ContentServiceImpl;
import com.cku.core.PageBeanResult;
import com.cku.core.RESTResponse;
import com.cku.core.ZAErrorCode;
import com.cku.upyun.ImageFtp;
import com.cku.upyun.VideoInfoService;
import com.cku.util.Debugger;
import com.cku.util.HttpClientUtil;
import com.cku.util.HttpResult;
import com.cku.util.JSONUtils;
import com.cku.util.PageBean;
import com.cku.util.PathUtils;
import com.cku.util.ServletUtils;
import com.cku.util.StreamUtils;

@Controller
@RequestMapping(value="publish")
public class ContentPublishController {
	private static final Logger logger = Logger.getLogger(ContentPublishController.class);
	
	@Autowired
	public ContentServiceImpl contentService;
	//添加
	@RequestMapping(value="/view")
	public ModelAndView viewEntry(HttpServletResponse response,HttpServletRequest request, ModelMap modelMap) {
		try{
			List<ContentType> s = contentService.getContentTypeList();		
			List<ContentType> l1 = new ArrayList<ContentType>();
			List<ContentType> l2 = new ArrayList<ContentType>();
			List<ContentType> l3 = new ArrayList<ContentType>();
			
//			ContentType empty = new ContentType();
//			empty.setLevel(-1);
//			empty.setId("000000");
//			empty.setName("全部");
//			empty.setParentTypeId("000000");
//			
//			l3.add(empty);

			for (ContentType ctm : s)
			{
				if (ctm.getLevel() == 1) l1.add(ctm);
				else if (ctm.getLevel() == 2) l2.add(ctm);
				else l3.add(ctm);
			}
			
			modelMap.addAttribute("contentTypeList1", l1);
			modelMap.addAttribute("contentTypeList2", l2);
			modelMap.addAttribute("contentTypeList3", l3);
			ModelAndView mv = new ModelAndView("jsp/index", modelMap);
			
			return mv;
		}
		catch (Exception e)
		{
			logger.error(e.getMessage());
			return null;				
		}
	}
	/**
	 * 修改图文信息
	 * @throws IOException 
	 * @Author chaixueteng
	 * @2016年4月26日上午9:48:17
	 */
	@RequestMapping("/toedit")
	public ModelAndView toedit(HttpServletResponse response,HttpServletRequest request, ModelMap modelMap) throws IOException{
		try{
			Integer id = ServletUtils.getParameterInt(request, "id");
			List<ContentType> s = contentService.getContentTypeList();		
			List<ContentType> l1 = new ArrayList<ContentType>();
			List<ContentType> l2 = new ArrayList<ContentType>();
			List<ContentType> l3 = new ArrayList<ContentType>();
			for (ContentType ctm : s)
			{
				if (ctm.getLevel() == 1) l1.add(ctm);
				else if (ctm.getLevel() == 2) l2.add(ctm);
				else l3.add(ctm);
			}
			modelMap.addAttribute("contentTypeList1", l1);
			modelMap.addAttribute("contentTypeList2", l2);
			modelMap.addAttribute("contentTypeList3", l3);
			//通过id查询出图文的信息,进行回显操作
			Content content=contentService.selectById(id);
			String htmlUrl = content.getUrl();
			//用httpclient获取网页地址 抓取返回网页的全部内容 给富文本显示用
			HttpResult post = HttpClientUtil.get(null, htmlUrl, null);
			String responseBody = post.getResponseBody();
			content.setUrl(responseBody);
			modelMap.addAttribute("content", content);
			ModelAndView mv = new ModelAndView("jsp/update",modelMap);
			return mv;
		}catch (Exception e){
			logger.error(e.getMessage());
			return null;
		}
	}
	/**
	 * 管理图文
	 * @param response
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="/list")
	public ModelAndView showList(HttpServletResponse response,HttpServletRequest request, ModelMap modelMap) {
		try{
			String contentType1 = ServletUtils.getParameter(request, "contentType1",null);
			String contentType2 = ServletUtils.getParameter(request, "contentType2",null);
			String contentType3 = ServletUtils.getParameter(request, "contentType3",null);
			String title = ServletUtils.getParameter(request, "title",null);
			String isFirstFlag = ServletUtils.getParameter(request, "isFirst","all");
			String isTopFlag = ServletUtils.getParameter(request, "isTop","all");
			String isCreateFlag = ServletUtils.getParameter(request, "isCreate","all");
			PageBean pb = ServletUtils.getParameterBean(request);
			List<ContentType> s = contentService.getContentTypeList();	
			PageBeanResult<Content> conList = contentService.getContentPage(contentType1,contentType2,contentType3,title,isFirstFlag,isTopFlag,isCreateFlag,pb);
			
			List<ContentType> l1 = new ArrayList<ContentType>();
			List<ContentType> l2 = new ArrayList<ContentType>();
			List<ContentType> l3 = new ArrayList<ContentType>();

//			ContentType empty = new ContentType();
//			empty.setLevel(-1);
//			empty.setId("000000");
//			empty.setName("全部");
//			empty.setParentTypeId("000000");
//			
//			l3.add(empty);

			for (ContentType ctm : s)
			{
				if (ctm.getLevel() == 1) l1.add(ctm);
				else if (ctm.getLevel() == 2) l2.add(ctm);
				else l3.add(ctm);
			}
			for(Content c : conList.getList()){
				String showContentTypeName = "";
				if(c.getContentType()!=null && !"".equals(c.getContentType())){
					for(ContentType ct : l1){
						if(ct.getId().equals(c.getContentType())){
							showContentTypeName=ct.getName();
							break;
						}
					}
					
				}
				if(c.getContentType2()!=null && !"".equals(c.getContentType2())){
					for(ContentType ct2 : l2){
						if(ct2.getId().equals(c.getContentType2())){
							showContentTypeName+="-"+ct2.getName();
							break;
						}
					}
				}
				if(c.getContentType3()!=null && !"".equals(c.getContentType3())){
					for(ContentType ct3 : l3){
						if(ct3.getId().equals(c.getContentType3())){
							showContentTypeName+="-"+ct3.getName();
							break;
						}
					}
				}
				c.setShowContentTypeName(showContentTypeName);
			}
			modelMap.addAttribute("contentTypeList1", l1);
			modelMap.addAttribute("contentTypeList2", l2);
			modelMap.addAttribute("contentTypeList3", l3);
			modelMap.addAttribute("contentList",conList);
			ModelAndView mv = new ModelAndView("jsp/list", modelMap);
			
			return mv;
		}
		catch (Exception e)
		{
			logger.error(e.getMessage());
			return null;				
		}
	}
	/**
	 * 置顶，首页 添加和删除
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/changeStatus")
	public void changeStatus(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = new RESTResponse();
		try{
			Integer id = ServletUtils.getParameterInt(request, "id");
			String type = ServletUtils.getParameter(request, "type");
			Integer isVal = ServletUtils.getParameterInt(request, "isVal",0);
			contentService.changeStatus(id,type,isVal);
			
		}catch (Exception e){
			result = new RESTResponse(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 图文上传文件方法   
	 * @param request
	 * @param response
	 * @param file
	 * @param type
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadFile")
	public void uploadFile(HttpServletRequest request, HttpServletResponse response,
							@RequestParam(value = "file",required = false) MultipartFile file,
							@RequestParam(value = "type",required = false) String type) throws IllegalStateException, IOException{
		RESTResponse result = null;
		String fileName = file.getOriginalFilename();
		int lastIndex = fileName.lastIndexOf(".");
		String fileNameEnd = fileName.substring(lastIndex);
		String newFileName = UUID.randomUUID()+fileNameEnd;
		String resultOra = "";
		try {
			if("video".equals(type)){
				String filePath = request.getRealPath("/uploadfile");
				File videoFile = new File(filePath+File.separator+newFileName);
				file.transferTo(videoFile);
				resultOra = ImageFtp.UPYUNWEBURL+ImageFtp.VIDEO_PATH_TEST+"/"+newFileName;
			}else if("image".equals(type)){
				resultOra = ImageFtp.uploadBytes(ImageFtp.IMAGE_PATH_TEST, newFileName, file.getBytes());
			}
			result = new RESTResponse("items", resultOra);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 删除
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/del")
	public void del(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = new RESTResponse();
		try{
			Integer id = ServletUtils.getParameterInt(request, "id");
			contentService.del(id);
		}catch (Exception e){
			result = new RESTResponse(e);
		}
		
		ServletUtils.writeResponse(response, result);
	}
	private void _writeHtmlBuffer(String title, String html, ByteArrayOutputStream baos) throws IOException
	{
		OutputStreamWriter osw = null;
		try
		{
			osw = new OutputStreamWriter(baos, "utf-8");
			osw.write("<html><head>");
			osw.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
			osw.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">");
			osw.write("<style> body img {width:100%;} </style>");
			//正则匹配swiper
//	        Pattern pattern = Pattern.compile("<swiper>.*</swiper>");
//	        Matcher matcher = pattern.matcher(html);
//	         if(matcher.find()){
//	        	 String repStr = matcher.group();
//	        	 String endStr = repStr.replaceAll("\\(", "<").replaceAll("\\)", ">").replaceAll("&quot;", "");
//	        	 endStr = endStr.substring(8, endStr.length()-9);
//	        	 //System.out.println(endStr);
//	        	 //System.out.println(matcher.replaceAll(endStr));
//	        	 html=matcher.replaceAll(endStr);
//	        	osw.write("<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/css/swiper.min.css\">");
//				osw.write("<script src=\"http://code.jquery.com/jquery-1.8.0.min.js\"></script>");
//				osw.write("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/js/swiper.min.js\"></script>");
//				osw.write("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/js/swiper.jquery.min.js\"></script>");
//	         }
			osw.write("</head><body>");
			osw.write("<title>" + title + "</title>");
			osw.write(html.toCharArray());  
//			osw.write("<script>window.onload=function(){");
//			osw.write("var swiper = new Swiper('.swiper-container', {");
//			osw.write("pagination: '.swiper-pagination',");
//			osw.write("nextButton: '.swiper-button-next',");
//			osw.write("prevButton: '.swiper-button-prev',");
//			osw.write("paginationClickable: true,");
//			osw.write("spaceBetween: 30,");
//			osw.write("centeredSlides: true,");
//			osw.write("autoplay: 2500,");
//			osw.write("autoplayDisableOnInteraction: false");
//			osw.write("}); }");   
//			osw.write("</script>");
			osw.write("</body></html>");
			osw.flush();  
			osw.close(); 
		}
		finally
		{
			try { if (osw != null) osw.close(); } catch (Exception e) {}
		}
	}
	
	private AtomicLong _atomic = new AtomicLong();
	private String _genHtmlName(){
		long newValue = _atomic.getAndIncrement();
		Date d = new Date();
		String name = String.format("%d-%d.htm", d.getTime(), newValue);
		return name;
	}
	@RequestMapping(value = "/showHtml")
	public void showHtml(HttpServletResponse response,HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try
		{
			JSONObject jo = StreamUtils.readJSONFromInputStream(request.getContentLength(), request.getInputStream());
			String title = JSONUtils.tryGetString(jo, "title");
			String html = JSONUtils.tryGetString(jo, "html");
			String realPath = request.getRealPath("/");
			String filePath = File.separator+"jsp"+File.separator+"show.html";
			StringBuffer data = new StringBuffer();
			data.append("<html>");
			data.append("<head>");
			data.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
			data.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\" />");
			data.append("<style> body img {width:100%;} </style>");
			data.append("</head>");
			data.append("<title>"+title+"</title>");
			data.append("<body>");
			data.append(html);
			data.append("</body>");
			data.append("</html>");
			File  f= new File(realPath+filePath);
	      try {
			//true = append file
			OutputStreamWriter writerStream = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
			BufferedWriter bufferWritter = new BufferedWriter(writerStream);
			bufferWritter.write(data.toString());
			bufferWritter.close();
		} catch (Exception e) {
			System.out.println(e);
		}
			result = new RESTResponse();
		}
		catch (Exception e)
		{
			result = new RESTResponse(e);
		}
		ServletUtils.writeResponse(response, result);
	}

	/**
	 * 添加 内容管理方法
	 * @param response
	 * @param request
     */
	@RequestMapping(value = "/commit")
	public void commitEntry(HttpServletResponse response,HttpServletRequest request) 
	{
		RESTResponse result = new RESTResponse();
		try
		{
			JSONObject jo = StreamUtils.readJSONFromInputStream(request.getContentLength(), request.getInputStream());
			String contentType1 = JSONUtils.tryGetString(jo, "contentType1");
			String contentType2 = JSONUtils.tryGetString(jo, "contentType2");
			String contentType3 = JSONUtils.tryGetString(jo, "contentType3");
			String title = JSONUtils.tryGetString(jo, "title");
			String html = JSONUtils.tryGetString(jo, "html");
			String subTitle = JSONUtils.tryGetString(jo, "subTitle");
			String contentBrief = JSONUtils.tryGetString(jo, "contentBrief");
			String headerBanner = JSONUtils.tryGetString(jo, "headerBanner");
			String videoUrl = JSONUtils.tryGetString(jo, "videoUrl");
			String thumb = JSONUtils.tryGetString(jo, "thumb");
			String thumbMin = JSONUtils.tryGetString(jo, "thumbMin");
			Integer isFirst = JSONUtils.tryGetInt(jo, "isFirst");
			Integer isTop = JSONUtils.tryGetInt(jo, "isTop");
			Integer isCreate = JSONUtils.tryGetInt(jo, "isCreate");
			//正则匹配
//			Matcher matcher1 = Pattern.compile("<img src=\"(.*?)\"/>").matcher(html);
//	         while(matcher1.find()){
//	        	String imgStr = matcher1.group();
//	        	Matcher matcher2 = Pattern.compile("\"http://chongaibao(.*?)\"").matcher(imgStr);
//	        	if(matcher2.find()){
//	        		String urlStr = matcher2.group();
//	        		if("".equals(thumb)){
//	        			thumb = urlStr.substring(1, urlStr.length()-1);
//	        		}else{
//	        			thumb += ","+urlStr.substring(1, urlStr.length()-1);
//	        		}
//	        	}
//	         };
			Content ctm = new Content();
			ctm.setContentType(contentType1);
			ctm.setContentType2(contentType2);
			ctm.setContentType3(contentType3);
			ctm.setCreateTime(new Date());
			ctm.setStatus(1);
			ctm.setTitle(title);
			ctm.setSubTitle(subTitle);
			ctm.setContentBrief(contentBrief);
			ctm.setUserId("1");
			ctm.setThumb(thumb);
			ctm.setVideoUrl(videoUrl);
			ctm.setHeaderBanner(headerBanner);
			ctm.setIsFirst(isFirst);
			ctm.setIsTop(isTop);
			ctm.setIsCreate(isCreate);
			ctm.setThumbMin(thumbMin);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			String htmlName = PathUtils.specFilename() + ".html";
			
			_writeHtmlBuffer(title, html, baos);			
			String url = ImageFtp.uploadBytes(ImageFtp.WEB_CONTENT_TEST, htmlName, baos.toByteArray());
			
			ctm.setUrl(url);
			int insertCount = contentService.insert(ctm);
			System.out.println(ctm.getId()+"=============================================");
			Thread th = new Thread(new UploadVideoToYun(ctm.getId(),contentService,request.getRealPath("/uploadfile"),videoUrl.substring(videoUrl.lastIndexOf("/")+1, videoUrl.length())));
			th.start();
			
			Debugger.doAssert(insertCount == 1, ZAErrorCode.ZA_ERC_SQL, "Failed to insert content '%s'", title);
		}
		catch (Exception e)
		{
			result = new RESTResponse(e);
		}
		
		try {
			ServletUtils.writeResponse(response, result);
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 * 修改 内容管理方法
	 * @param response
	 * @param request
	 * @throws IOException 
     */
	@RequestMapping(value = "/updateToCommit")
	public void commitUpdateEntry(HttpServletResponse response,HttpServletRequest request) throws IOException 
	{
		RESTResponse result = new RESTResponse();
		try
		{
			JSONObject jo = StreamUtils.readJSONFromInputStream(request.getContentLength(), request.getInputStream());
			String id= JSONUtils.tryGetString(jo,"id");
			String contentType1 = JSONUtils.tryGetString(jo, "contentType1");
			String contentType2 = JSONUtils.tryGetString(jo, "contentType2");
			String contentType3 = JSONUtils.tryGetString(jo, "contentType3");
			String title = JSONUtils.tryGetString(jo, "title");
			String html = JSONUtils.tryGetString(jo, "html");
			String subTitle = JSONUtils.tryGetString(jo, "subTitle");
			String contentBrief = JSONUtils.tryGetString(jo, "contentBrief");
			String headerBanner = JSONUtils.tryGetString(jo, "headerBanner");
			String videoUrl = JSONUtils.tryGetString(jo, "videoUrl");
			String thumb = JSONUtils.tryGetString(jo, "thumb");
			String thumbMin = JSONUtils.tryGetString(jo, "thumbMin");
			Integer isFirst = JSONUtils.tryGetInt(jo, "isFirst");
			Integer isTop = JSONUtils.tryGetInt(jo, "isTop");
			Integer isCreate = JSONUtils.tryGetInt(jo, "isCreate");
			Content ctm = contentService.selectById(Integer.parseInt(id));
			//得到旧的图文图片  把云服务图片上删掉
			Content oldContent = new Content();
			oldContent.setThumb(ctm.getThumb());
			oldContent.setThumbMin(ctm.getThumbMin());
			oldContent.setVideoUrl(ctm.getVideoUrl());
			
			ctm.setContentType(contentType1);
			ctm.setContentType2(contentType2);
			ctm.setContentType3(contentType3);
			ctm.setStatus(1);
			ctm.setTitle(title);
			ctm.setSubTitle(subTitle);
			ctm.setContentBrief(contentBrief);
			ctm.setUserId("1");
			ctm.setThumb(thumb);
			ctm.setVideoUrl(videoUrl);
			ctm.setHeaderBanner(headerBanner);
			ctm.setIsFirst(isFirst);
			ctm.setIsTop(isTop);
			ctm.setIsCreate(isCreate);
			ctm.setThumbMin(thumbMin);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			String htmlName = PathUtils.specFilename() + ".html";
			
			_writeHtmlBuffer(title, html, baos);			
			String url = ImageFtp.uploadBytes(ImageFtp.WEB_CONTENT_TEST, htmlName, baos.toByteArray());
			
			ctm.setUrl(url);
			int insertCount = contentService.update(ctm,oldContent);
			System.out.println(ctm.getId()+"=============================================");
			Thread th = new Thread(new UploadVideoToYun(ctm.getId(),contentService,request.getRealPath("/uploadfile"),videoUrl.substring(videoUrl.lastIndexOf("/")+1, videoUrl.length())));
			th.start();
			
			Debugger.doAssert(insertCount == 1, ZAErrorCode.ZA_ERC_SQL, "Failed to insert content '%s'", title);
		}
		catch (Exception e)
		{
			result = new RESTResponse(e);
		}
		ServletUtils.writeResponse(response, result);
	}
}

class UploadVideoToYun implements Runnable{
	private static final Logger logger = Logger.getLogger(UploadVideoToYun.class);
	private String newFileName;
	private String videoFile;
	private Long conentId;
	private ContentServiceImpl contentService;


	public UploadVideoToYun(Long conentId,ContentServiceImpl contentService, String videoFile, String newFileName) {
		this.newFileName = newFileName;
		this.videoFile = videoFile;
		this.conentId = conentId;
		this.contentService = contentService;
	}

	@Override
	public void run() {
		try {
			logger.info("========================uploadstart:"+conentId+"============================"+System.currentTimeMillis());
			String result = ImageFtp.uploadFile(ImageFtp.VIDEO_PATH_TEST, newFileName, videoFile + File.separator + newFileName);
			String time = VideoInfoService.getVideoTime(result);
			contentService.updateTime(conentId,time);
			logger.info("========================uploadend:"+conentId+"============================"+System.currentTimeMillis());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
