package com.goafanti.news.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
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.RestController;

import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.constant.PageConstants;
import com.goafanti.common.controller.BaseApiController;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.KnowledgeBaseFields;
import com.goafanti.common.enums.NewsCacheKey;
import com.goafanti.common.model.News;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.JDBCIdGenerator;
import com.goafanti.news.bo.InputNews;
import com.goafanti.news.enums.NewsFields;
import com.goafanti.news.service.NewsService;

/**
 * 新闻
 */
@RestController
@RequestMapping(value = "/api/admin/news")
public class AdminNewsApiController extends BaseApiController {
	@Resource
	private NewsService		newsService;
	@Autowired
	private JDBCIdGenerator	idGenerator;

	
	/**
	 * 新闻列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result list(Integer type, String title, String author, String startCreateTime, String endCreateTime,
			String source, Integer hot, String pageSize, String pageNo,String auditStatus,String releaseStatus,String publishPage) {
		Result res = new Result();
//		if (null == type) {
//			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻类型"));  
//			return res;
//		}
		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(newsService.listNews(type, title, author, startCreateTime, endCreateTime, source, hot, pNo, pSize,auditStatus,releaseStatus,publishPage,null)); 
		return res;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result add(@Valid InputNews news, BindingResult bindingResult, String createTimeFormattedDate) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					NewsFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		res = disposeInputNews(res, news, createTimeFormattedDate);
		if (!res.getError().isEmpty()) {
			return res;
		}
		newsService.save(idGenerator.generateId(), (News) res.getData()); 
		return res;
	}
	
/*
 * 新增
 * 
 * */
	@RequestMapping(value="/apply",method=RequestMethod.POST)
public Result apply(@Valid InputNews news,BindingResult bindingResult,String[] publishPages) {
		Result result=new Result();
		if (bindingResult.hasErrors()) {
			result.getError().add(
					buildErrorByMsg(bindingResult.getFieldError()
							.getDefaultMessage(), NewsFields 
							.getFieldDesc(bindingResult.getFieldError()
									.getField())));
			return result;
		}
		List<String>webPages=new ArrayList<>();
		List<String>appPages=new ArrayList<>();
		PageConstants.putNews(publishPages, webPages, appPages);
		checkApplyParams(news,webPages,appPages,result);
		if(result.getError().size()>0) {
			return result;
		}
		news.setCreateTime(new Date());
		if(news.getAuditStatus() == 2) {
			news.setReleaseDate(new Date());
		}
		news.setId(idGenerator.generateId());
		News news2=new News();
		if(news.getType()==null)
		news.setType(0);
		BeanUtils.copyProperties(news, news2);
		result.setData(newsService.save( news2,webPages,appPages)); 
		return result;
	}
	
	/*
	 * 修改
	 * 
	 * */
		@RequestMapping(value="/updateNews",method=RequestMethod.POST)
	public Result updateNews(@Valid InputNews news,BindingResult bindingResult,String[] publishPages) {
			Result result=new Result();
			
			if (bindingResult.hasErrors()) {
				result.getError().add(
						buildErrorByMsg(bindingResult.getFieldError()
								.getDefaultMessage(), NewsFields 
								.getFieldDesc(bindingResult.getFieldError()
										.getField())));
				return result;
			}
			List<String>webPages=new ArrayList<>();
			List<String>appPages=new ArrayList<>();
			PageConstants.putNews(publishPages, webPages, appPages);
			checkApplyParams(news,webPages,appPages,result);
			if(result.getError().size()>0) {
				return result;
			}
			news.setCreateTime(new Date());
			if(news.getAuditStatus() == 2) {
				news.setReleaseDate(new Date());
			}
			News news2=new News();
			BeanUtils.copyProperties(news, news2);
			result.setData(newsService.updateSelectively( news2,webPages,appPages)); 
			//publishPages
			return result;
		}
	

	/*
	 * 变更发布状态、发布时间
	 * */
		@RequestMapping(value="/updateStatus",method=RequestMethod.POST)
		public Result updateStatus(Long id,Integer auditStatus,Integer refresh) {
			Result result=new Result();
			if(id==null) {
				result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","未找到该新闻,"));
				return result;
			}
			News news=newsService.findNewsDetail(id);
			if(news==null) {
				result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","未找到该新闻,"));
				return result;
			}
			if(refresh!=null &&refresh==1)
				{
				if(auditStatus!=2 && news.getAuditStatus()!=2) {
					result.getError().add(buildError("","","当前未发布"));
					return result;
				}
				news.setReleaseDate(new Date());}
			if(auditStatus!=null) {
				news.setAuditStatus(auditStatus); 
			if(auditStatus ==2){
				news.setReleaseDate(new Date());
				
				newsService.updateJtCollectSearch(news);
				newsService.addJtCollectSearch(news);
				}
			if(auditStatus ==4){
				newsService.updateJtCollectSearch(news);
				}
			}
			
			result.setData(newsService.updateSelectivelyWithoutPages(news));  
			return result;
			
		}
		
		
	private void checkApplyParams(InputNews news, List<String>webPages,List<String>appPages, Result result) {
	/*if(webPages.size()<1 && appPages.size()<1)
	{
		result.getError().add(buildError(ErrorConstants.PARAM_ERROR,"","发布位置"));
		return;
	}*/
	if(news ==null || StringUtils.isBlank(news.getTitle())) {
		result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","标题"));
		return;
	}
	if(StringUtils.isBlank(news.getSource())) {
		result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","来源"));
		return;
	}
	if(StringUtils.isBlank(news.getContent())) {
		result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","内容"));
		return;
	}
	if(news.getHot() ==null)
	{
		result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","是否热门"));
		return;
	}
	
}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Result update(InputNews news, BindingResult bindingResult, String createTimeFormattedDate) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					NewsFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (null == news.getId()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻Id"));
			return res;
		}

		res = disposeInputNews(res, news, createTimeFormattedDate);
		if (!res.getError().isEmpty()) {
			return res;
		}
		newsService.update(news.getId(), (News) res.getData());
		return res;
	}

	/**
	 * 详情
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public Result detail(Long id) {
		Result res = new Result();
		if (null == id) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻Id"));
			return res;
		}
		res.setData(newsService.findNewsDetail(id));  
		return res;
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Result delete(@RequestParam(name = "ids[]", required = false) String[] ids) {
		Result res = new Result();
		if (ids == null || ids.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
		} else {
			res.setData(newsService.batchDeleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}
	/**
	 * 删除
	 */
	@RequestMapping(value = "/deleteById", method = RequestMethod.POST)
	public Result deleteById(Long id) {
		Result res = new Result();
		if (id == null) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
		} else {
			res.setData(newsService.deleteByPrimaryKey(id)); 
		}
		return res;
	}
	/**
	 * 新闻图片上传
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result upload(HttpServletRequest req, String sign) {
		Result res = new Result();
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.NEWS_TITLE_PICTURE
				|| attachmentType == AttachmentType.NEWS_CONTENT_PICTURE) {
			Calendar c = Calendar.getInstance();
			res.setData(handleFile(res, false, req, sign, String.valueOf(c.get(Calendar.YEAR)),
					String.valueOf(c.get(Calendar.MONTH) + 1), idGenerator.generateId().toString()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 清除缓存
	 */
	@RequestMapping(value = "/cleanCache", method = RequestMethod.POST)
	public Result cleanCache(String cacheKey) {
		Result res = new Result();
		if (StringUtils.isBlank(cacheKey)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "缓存标记"));
			return res;
		}
		if (NewsCacheKey.NEWS_LIST_CACHE_KEY.getCode().equals(cacheKey)) {
			newsService.cleanList(); // 清除策源地页面新闻列表缓存
		} else if (NewsCacheKey.NEWS_PORTAL_LIST_CACHE_KEY.getCode().equals(cacheKey)) {
			newsService.cleanPortalList(); // 清除新闻列表页列表缓存
		} else if (NewsCacheKey.NEWS_INDEX_LIST_CACHE_KEY.getCode().equals(cacheKey)){
			newsService.cleanIndexNewsList(); //清除首页新闻缓存
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "缓存标记"));
		}
		return res;
	}
	

	private Result disposeInputNews(Result res, InputNews news, String createTimeFormattedDate) {
		if (StringUtils.isBlank(news.getTitle())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻标题"));
			return res;
		}

		if (StringUtils.isBlank(createTimeFormattedDate)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻时间"));
			return res;
		}

		if (null == news.getType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻类型"));
			return res;
		}
		if(null == news.getSource())
		{
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新闻来源"));
			return res;
		}

		News n = new News();
		BeanUtils.copyProperties(news, n);
		try {
			n.setCreateTime(DateUtils.parseDate(createTimeFormattedDate, AFTConstants.YYYYMMDD));
		} catch (ParseException e) {
		}
		res.setData(n);
		return res;
	}

}
