package com.quant.controller;

import java.io.File;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.quant.comm.ReadPro;
import com.quant.comm.Template;
import com.quant.dao.NewsMapper;
import com.quant.dao.ProductMapper;
import com.quant.dao.SettingMapper;
import com.quant.entity.Attachment;
import com.quant.entity.CommonSubclass;
import com.quant.entity.News;
import com.quant.entity.Tablefield;
import com.quant.vo.NewsPageVo;
import com.quant.dao.TablefieldMapper;

/**
 * 处理资讯的控制层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/operation/news")
@SessionAttributes("newsPageVo")
public class NewsController extends BaseController{
	
	@Resource
	NewsMapper newsMapper;
	@Resource
	private ReadPro readPro;
	@Resource
	private SettingMapper settingMapper;
	
	@Resource
	private TablefieldMapper tablefieldMapper;
		
	@Resource
	private ProductMapper productMapper;
	
	@RequestMapping("/listNews.do")
	public String findNews(ModelMap map,NewsPageVo pageVo){
		
		//默认情况下使用request传递该变量的值，使用注解@SessionAttributes("newsPageVo")
		//后使用session传递
		List<News> news = new ArrayList<News>();
		Integer first=pageVo.getFirst();
		Integer second=pageVo.getSecond();
		if(second==null||second==0){
			if(first==null||first==0){
				int rows=newsMapper.findRowsByNewsPageVo(pageVo);
				pageVo.setRows(rows);
				news=newsMapper.findNewsByPage(pageVo);
			}else{
				
				Integer rows=0;
				List<Integer> type=new ArrayList<Integer>();
				List<CommonSubclass> newsType = settingMapper.findCommonSubclassByPid(first);
				if(newsType!=null){
					for (CommonSubclass commonSubclass : newsType) {
						type.add(commonSubclass.getSubclassId());
					}
					pageVo.setSelect(null);
					pageVo.setType(type);
					rows=newsMapper.findRowsByNewsPageVo(pageVo);
					pageVo.setRows(rows);
					news=newsMapper.findNewsByPage(pageVo);
				}else{
					pageVo.setSelect(first);
					rows+=newsMapper.findRowsByNewsPageVo(pageVo);
					pageVo.setRows(rows);
					news=newsMapper.findNewsByPage(pageVo);
				}
				
				 
				 map.addAttribute("type", newsType);
			}
		}else{
			pageVo.setSelect(second);
			int rows=newsMapper.findRowsByNewsPageVo(pageVo);
			pageVo.setRows(rows);
			 news=newsMapper.findNewsByPage(pageVo);
			 List<CommonSubclass> newsType = settingMapper.findCommonSubclassByPid(first);
			 map.addAttribute("type", newsType);
		}
		
		map.put("news", news);
		map.addAttribute("newsPageVo", pageVo);
		
		Integer categoryId=Integer.parseInt(readPro.readProperties("新闻资讯"));
		List<CommonSubclass> list=settingMapper.findCommonSubclassByCategoryId(categoryId);
		map.put("newsType", list);
		
			List<Tablefield> _list = tablefieldMapper.getTablefield();

			map.put("types", _list);
		
		return "news/news";
	}
	
	@RequestMapping("/newsSort.do")
	public String newsSort(Integer categoryId,ModelMap map){
		List<CommonSubclass> list=newsMapper.findNewsTypesByCategoryId(categoryId);
		map.put("newsType", list);
		return "news/news_sort";
	}
	
	@RequestMapping("/toPubNews.do")
	public String toNewsPub(ModelMap map){
		Integer categoryId=Integer.parseInt(readPro.readProperties("新闻资讯"));
		List<CommonSubclass> list=settingMapper.findCommonSubclassByCategoryId(categoryId);
		map.put("newsType", list);
		Integer maxId = newsMapper.findNewsMaxId();
		if(maxId==null){
			maxId=Integer.parseInt(readPro.readProperties("news_id_min"));
		}
		maxId+=1;
		map.put("relationId",maxId);
		return "news/news_pub";
	}
	@RequestMapping("/pubNews.do")
	public String newsPub(String attachmentTitle,Attachment attachment,News news,String editorValue,
			HttpServletRequest request,Integer select1,Integer select2){
		news.setContent(editorValue);
		if(select2==null||select2==0){
			news.setNewsType(select1);			
		}else{
			news.setNewsType(select2);
		}
		news.setPubTime(new Timestamp(System.currentTimeMillis()));
		news.setStatus(1);
		Integer maxId=newsMapper.findNewsMaxId();
		if(maxId==null){
			maxId=Integer.parseInt(readPro.readProperties("news_id_min"));
		}
		news.setViewCount(new Random().nextInt(199)+300);
		news.setNewsId(maxId+1);
		if (attachment.getUri() != null && attachment.getUri() != "") {
			attachment.setAttachmentType(1);
			attachment.setRelationId(maxId + 1);
			attachment.setTitle(attachmentTitle);
			productMapper.addAttachment(attachment);
		}
		newsMapper.addNews(news);	
		List<News> bestList = newsMapper.findThirtyBestNews();
		List<HashMap<String, String>> hashBest  = new ArrayList<HashMap<String,String>>();
		List<HashMap<String, String>> hashMore  = new ArrayList<HashMap<String,String>>();
		
		DateFormat sdf = new SimpleDateFormat("MM-dd"); 
		for(News bestNews:bestList){
			HashMap<String, String> map = new HashMap<String, String>();
			String dateStr = sdf .format(bestNews.getPubTime());
			String name = getTablefield(bestNews.getNewsType());
			map.put("title", bestNews.getTitle().replace("\r\n", ""));
			map.put("newsId", bestNews.getNewsId().toString());
			map.put("mthumbnail", bestNews.getMthumbnail().replace("\r\n", ""));
			map.put("pubTime", dateStr);
			map.put("viewCount", bestNews.getViewCount().toString());
			map.put("summary", bestNews.getSummary().replace("\r\n", ""));
			map.put("newsTypeName", name);
			hashBest.add(map);
		}
 		String srcBestNews = readPro.readProperties("srcBestNews");
		String dstBestNews = readPro.readProperties("dstBestNews");
		String temp=request.getServletContext().getRealPath("");
	    temp=temp.substring(0, temp.lastIndexOf(File.separator)+1);
		
		Template.createTemplate(temp+srcBestNews, temp+dstBestNews, hashBest);
		
		List<News> moreList = newsMapper.findThirtyMoreNews();
		
		for(News moreNews:moreList){
			HashMap<String, String> map = new HashMap<String, String>();
			String dateStr = sdf .format(moreNews.getPubTime());
			String name = getTablefield(moreNews.getNewsType());
			map.put("title", moreNews.getTitle().replace("\r\n", ""));
			map.put("newsId", moreNews.getNewsId().toString());
			map.put("mthumbnail", moreNews.getMthumbnail().replace("\r\n", ""));
			map.put("pubTime", dateStr);
			map.put("viewCount", moreNews.getViewCount().toString());
			map.put("summary", moreNews.getSummary().replace("\r\n", ""));
			map.put("newsTypeName", name);
			hashMore.add(map);
		}
		String srcMoreNews = readPro.readProperties("srcMoreNews");
		String dstMoreNews = readPro.readProperties("dstMoreNews");
		
		Template.createTemplate(temp+srcMoreNews, temp+dstMoreNews, hashMore);
		return "redirect:listNews.do";
	}
	
	@RequestMapping("/toUpdateNews.do")
	public String toUpdateNews(Integer newsId,ModelMap map){
		Integer categoryId=Integer.parseInt(readPro.readProperties("新闻资讯"));
		List<CommonSubclass> list=newsMapper.findNewsTypesByCategoryId(categoryId);
		News news=newsMapper.findNewsByNewsId(newsId);
		Integer pid = 0;
		for(CommonSubclass css: list) {
			if (css.getSubclassId().equals(news.getNewsType())) {
				pid = css.getPid();
				if(pid==null){
					pid=news.getNewsType();
				}
				break;
			}
		}
		map.addAttribute("news", news);
		map.addAttribute("pid", pid);
		map.put("newsType", list);
		return "news/news_update";
	}
	@RequestMapping("/updateNews.do")
	public String updateNews(Attachment attachment,String attachmentTitle,
			News news ,String editorValue,HttpServletRequest request,Integer newsTypePid){
		if (news.getStatus() == null) {
			news.setStatus(0);
		}
		if(news.getNewsType()==null||news.getNewsType()==0){
			news.setNewsType(newsTypePid);
		}
		news.setContent(editorValue);
		attachment.setTitle(attachmentTitle);
		attachment.setRelationId(news.getNewsId());
		attachment.setPostTime(new Timestamp(System.currentTimeMillis()));
		productMapper.updateAttachmentByrelationId(attachment);
		newsMapper.updateNews(news);
		
		List<News> bestList = newsMapper.findThirtyBestNews();
		List<HashMap<String, String>> hashBest  = new ArrayList<HashMap<String,String>>();
		List<HashMap<String, String>> hashMore  = new ArrayList<HashMap<String,String>>();
		DateFormat sdf = new SimpleDateFormat("MM-dd"); 
		for(News bestNews:bestList){
			HashMap<String, String> map = new HashMap<String, String>();
			String name = getTablefield(bestNews.getNewsType());
			String dateStr = sdf .format(bestNews.getPubTime());
			map.put("title", bestNews.getTitle().replace("\r\n", ""));
			map.put("newsId", bestNews.getNewsId().toString());
			map.put("mthumbnail", bestNews.getMthumbnail().replace("\r\n", ""));
			map.put("pubTime", dateStr);
			map.put("viewCount", bestNews.getViewCount().toString());
			map.put("summary", bestNews.getSummary().replace("\r\n", ""));
			map.put("newsTypeName",name);
			hashBest.add(map);
		}
 		String srcBestNews = readPro.readProperties("srcBestNews");
		String dstBestNews = readPro.readProperties("dstBestNews");
		
		String temp=request.getServletContext().getRealPath("");
	    temp=temp.substring(0, temp.lastIndexOf(File.separator)+1);
		
		Template.createTemplate(temp+srcBestNews, temp+dstBestNews, hashBest);
		
		List<News> moreList = newsMapper.findThirtyMoreNews();
		
		for(News moreNews:moreList){
			HashMap<String, String> map = new HashMap<String, String>();
			String name = getTablefield(moreNews.getNewsType());
			String dateStr = sdf .format(moreNews.getPubTime());
			map.put("title", moreNews.getTitle().replace("\r\n", ""));
			map.put("newsId", moreNews.getNewsId().toString());
			map.put("mthumbnail", moreNews.getMthumbnail().replace("\r\n", ""));
			map.put("pubTime", dateStr);
			map.put("viewCount", moreNews.getViewCount().toString());
			map.put("summary", moreNews.getSummary().replace("\r\n", ""));
			map.put("newsTypeName", name);
			hashMore.add(map);
		}
		String srcMoreNews = readPro.readProperties("srcMoreNews");
		String dstMoreNews = readPro.readProperties("dstMoreNews");
		
		Template.createTemplate(temp+srcMoreNews, temp+dstMoreNews, hashMore);
		
		return "redirect:listNews.do";
	}
	@RequestMapping("deleteNews.do")
	public String deleteNews(Integer newsId){
		newsMapper.deleteNews(newsId);
		return "redirect:listNews.do";
	}
	@RequestMapping(value="findNewsTypeByPid.do",produces="application/json")
	@ResponseBody
	public List<CommonSubclass> findNewsTypeByPid(Integer newsType){
		List<CommonSubclass> news = settingMapper.findCommonSubclassByPid(newsType);
		return news;
	}
	
	@RequestMapping("checkTitle.do")
	@ResponseBody
	public Map<String,String> checkTitle(String checkTitle){
		List<String> title = newsMapper.findAllTitle();
		Map<String, String> result = new HashMap<String, String>();
		for(String titles:title){
			if(titles.equals(checkTitle)){
			result.put("msg", "已有");
			break;
			}else{
				result.put("msg", "没有");
			}
		}
		return result;
	}
}
