package com.cab.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cab.dao.ContentMapper;
import com.cab.dao.ContentPushMapper;
import com.cab.dao.ContentTypeMapper;
import com.cab.dao.CuRelationMapper;
import com.cab.model.Content;
import com.cab.model.ContentComment;
import com.cab.model.ContentPush;
import com.cab.model.ContentType;
import com.cab.model.CuRelationKey;
import com.cku.core.PageBeanResult;
import com.cku.upyun.ImageFtp;
import com.cku.util.PageBean;

@Service("contentService")
public class ContentServiceImpl{
	
	@Autowired
	public ContentTypeMapper contentTypeMapper;
	
	@Autowired
	public ContentPushMapper contentPushMapper;

	@Autowired
	public ContentMapper contentMapper;

	@Autowired
	public CuRelationMapper cuRelationMapper;

	@Autowired
	public ContentCommentServiceImpl contentCommentService;
	
	public static int CODE_ALIVE_TIME_MINUTE = 10; // 10 minutes actived for phone code.
	public static int CODE_APPLY_INTERVAL = 1 * 60 * 1000; // 1 minute for apply interval.
	
	public static String CONTENT_TYPE_PICTURE = "01";
	public static String CONTENT_TYPE_VIDEO = "02";

	public static int CU_TYPE_UP = 1;
	public static int CU_TYPE_FAVORITE = 2;

	private void _fillSubTypes(List<ContentType> result)
	{		
		ArrayList<String> parentList = new ArrayList<String>();
		for (ContentType ct : result)
		{
			parentList.add(ct.getId());
			ct.setSubTypeList(new ArrayList<ContentType>());
		}
		
		List<ContentType> subTypes = contentTypeMapper.selectByParentIdList(parentList);
		for (int i = 0; i < subTypes.size(); ++i)
		{
			ContentType ct = subTypes.get(i);
			for (ContentType ct2 : result)
			{
				if (ct2.getId().equals(ct.getParentTypeId()))
				{
					List<ContentType> subTypeList = ct2.getSubTypeList();
					subTypeList.add(ct);
				}
			}
		}
	}
	/**
	 * 得到一级分类下的数据
	 * @throws IOException
	 */
	public List<ContentType> GetPictureSuggest()
	{		
		ArrayList<ContentType> ar = new ArrayList<ContentType>();
		
		List<ContentPush> result = contentPushMapper.selectByContentTypeId(CONTENT_TYPE_PICTURE);
		for (int i = 0; i < result.size(); ++i)
		{
			ContentPush cp = result.get(i);
			ContentType ctFound = null;
			for (ContentType ct : ar)
			{
				if (ct.getId().equals(cp.getContentTypeId()))
				{
					ctFound = ct;
					break;
				}
			}
			
			if (ctFound == null)
			{
				ctFound = cp.getContentType();
				ctFound.setContentList(new ArrayList<Content>());
				ar.add(ctFound);
			}
			
			List<Content> l = ctFound.getContentList();
			
			Content c = new Content();
			c.setId(cp.getId());
			c.setTitle(cp.getTitle());
			c.setThumb(cp.getThumb());
			c.setUrl(cp.getUrl());
			
			l.add(c);
		}
		
		_fillSubTypes(ar);
		return ar;
	}
	
	public PageBeanResult<Content> GetByContentTypeId(String contentTypeId, PageBean bean)
	{
		List<Content> result = contentMapper.selectByContentType(contentTypeId, bean.get_start(), bean.get_limit());
		PageBeanResult<Content> pbr = new PageBeanResult<Content>();
		pbr.list = result;

		pbr.totalCount = Long.MAX_VALUE;
		if (bean.getNeedCount())
		{
			pbr.totalCount = contentMapper.selectCountByContentType(contentTypeId);
		}
		
		return pbr;
	}
	/**
	 * 得到消息详细
	 */
	public Content GetContentDetails(Long contentId, Long userId,PageBean pb) {
		Content c = new Content();
		c = contentMapper.selectByPrimaryKey(contentId);
		if (userId != null){
			CuRelationKey cr = new CuRelationKey();
			cr.setContentId(contentId);
			cr.setUserId(userId);
			List<CuRelationKey> ls = cuRelationMapper.selectByUserAndContent(cr);
			
			int isUp = 0, isFavorite = 0;
			for (CuRelationKey key : ls){
				if (key.getCuType() == CU_TYPE_UP){
					isUp = 1;
				}else if (key.getCuType() == CU_TYPE_FAVORITE){
					isFavorite = 1;
				}
			}
			c.setIsUp(isUp);
			c.setIsFavorite(isFavorite);
		}else{
			c.setIsFavorite(0);
			c.setIsUp(0);
		}
		List<ContentComment> commentList = contentCommentService.selectByContentId(contentId,pb);	
		//long count=contentCommentService.getCount(contentId);
		c.setCommentList(commentList);
		c.setCommentCount(new Long(commentList.size()));
		
		return c;
	}

	public void addAction(Long contentId, Long userId, int cuType) {
		CuRelationKey cu = new CuRelationKey();
		
		cu.setContentId(contentId);
		cu.setCuType(cuType);
		cu.setUserId(userId);
		
		int affected = cuRelationMapper.insertSelective(cu);		
		if (affected > 0)
		{
			if (cuType == CU_TYPE_UP)
			{
				contentMapper.increaseUpCount(contentId);
			}
			else
			{
				contentMapper.increaseFavCount(contentId);			
			}
		}
	}

	public void removeAction(Long contentId, Long userId, int cuType) {
		CuRelationKey cu = new CuRelationKey();
		
		cu.setContentId(contentId);
		cu.setCuType(cuType);
		cu.setUserId(userId);
		
		int affected = cuRelationMapper.deleteByPrimaryKey(cu);
		if (affected > 0)
		{
			if (cuType == CU_TYPE_UP)
			{
				contentMapper.decreaseUpCount(contentId);
			}
			else
			{
				contentMapper.decreaseFavCount(contentId);			
			}
		}
	}
	public List<ContentType> getContentTypeList() {
		List<ContentType> list = contentTypeMapper.selectAll();
		return list;
	}
	
	public int insert(Content content)
	{
		int result = contentMapper.insertSelective(content);
		return result;
	}
	/**
	 * 根据三级type分类获取分类下的信息
	 * @param contentTypeId
	 * @param title 
	 * @param bean
	 * @return
	 */
	public PageBeanResult<Content> getByContentType(String contentTypeParentId,String contentTypeId, String title, PageBean bean){
		if(contentTypeId!=null && !"".equals(contentTypeId)){
			contentTypeParentId=null;
		}else{
			contentTypeId = null;
		}
		List<Content> result = contentMapper.getByContentType(contentTypeParentId,contentTypeId,title, bean.get_start(), bean.get_limit());
		buildHeaderBanner(result);
		PageBeanResult<Content> pbr = new PageBeanResult<Content>();
		pbr.list = result;

		pbr.totalCount = Long.MAX_VALUE;
		if (bean.getNeedCount())
		{
			pbr.totalCount = contentMapper.getByContentTypeCount(contentTypeParentId,contentTypeId,title);
		}
		
		return pbr;
	}
	/**
	 * 得到图文大类下的所有首页信息
	 * @return
	 */
	public List<ContentType> getIsFirst(int type){		
		String paramsType = (type==0?"010000":"020000");
		List<ContentType> towTypeList = contentTypeMapper.getIsFirst(paramsType);
		List<Content> result = contentMapper.getIsFirst(paramsType);
		buildHeaderBanner(result);
		for(ContentType ct:towTypeList){
			List<Content> addList = new ArrayList<Content>();
			for(Content c:result){
				if(ct.getId().equals(c.getContentType2())){
					addList.add(c);
				}
			}
			ct.setContentList(addList);
		}

		_fillSubTypes(towTypeList);
		return towTypeList;
	}
	/**
	 * 得到专题三级分类
	 * @return
	 */
	public List<ContentType> getSubjectType(int type){
		String paramsType = (type==0?"030100":"030200");
		List<ContentType> list = contentTypeMapper.getIsFirst(paramsType);
		return list;
	}
	/**
	 * 得到所有分类信息
	 * @return
	 */
	public List<ContentType> getAllType(){
		List<ContentType> list = contentTypeMapper.selectAll();
		List<ContentType> nodeList = new ArrayList<ContentType>();
		for(ContentType ct:list){
			if((ct.getParentTypeId()==null  || "".equals(ct.getParentTypeId())) && ct.getLevel()==1){
				setChildNode(ct,list);
				nodeList.add(ct);
			}
		}
		return nodeList;
	}
	private void setChildNode(ContentType pct, List<ContentType> list) {
		List<ContentType> addList = new ArrayList<ContentType>();
		for (ContentType ct : list) {
			if (pct.getId().equals(ct.getParentTypeId())) {
				addList.add(ct);
				setChildNode(ct,list);
			}
		}
		pct.setSubTypeList(addList);
		}
	/**
	 * 得到所有推荐信息
	 * @param pb 
	 * @return
	 */
	public PageBeanResult<Content> getAllIsTop(PageBean pb){
		PageBeanResult<Content> pbr = new PageBeanResult<Content>();
		List<Content> list = contentMapper.getAllIsTop(pb.get_start(),pb.get_limit());
		buildHeaderBanner(list);
		pbr.list=list;
		if (pb.getNeedCount())
		{
			pbr.totalCount = contentMapper.getAllIsTopCount();
		}
		return pbr;
	}
	/**
	 * 根据content Id 得到信息详细
	 */
	public Content getContentInfoById(Long contentId,Long userId){
		Content content = contentMapper.getContentInfoById(contentId);
		return content;
	}
	public PageBeanResult<Content> getContentPage(String contentType1,String contentType2,String contentType3,String title,String isFirst,String isTop,String isCreate, PageBean pb){
		PageBeanResult<Content> pbr = new PageBeanResult<Content>();
		List<Content> list = contentMapper.getContentPage(contentType1,contentType2,contentType3,title,isFirst,isTop,isCreate,pb.get_start(),pb.get_limit());
		pbr.list = list;
		pbr.totalCount = contentMapper.getContentPageCount(contentType1,contentType2,contentType3,title,isFirst,isTop,isCreate);
		return pbr;
	}

	/**
	 * 更新状态
	 * @param id
	 * @param type
	 * @param isVal
     */
	public void changeStatus(Integer id,String type,Integer isVal){
		if("isTop".equals(type)){
			if(isVal==0){
				contentMapper.changeIsTop(id,1);
			}else{
				contentMapper.changeIsTop(id,0);
			}
		}else{
			if(isVal==0){
				contentMapper.changeIsFirst(id,1);
			}else{
				contentMapper.changeIsFirst(id,0);
			}
		}
		
	}
	/**
	 * 上传视频后解析时长存入数据库
	 * @param id
	 * @param time
	 */
	public void updateTime(Long id,String time){
		contentMapper.updateTime(id,time);
	}
	public void del(Integer id){
		Content content = contentMapper.selectByPrimaryKey((long)id);
		if(content.getThumb()!=null && !"".equals(content.getThumb())){
			if(content.getThumb().indexOf(ImageFtp.UPYUNWEBURL)==0){
				ImageFtp.deleteFile(content.getThumb().replace(ImageFtp.UPYUNWEBURL, ""));
			}
		}
		if(content.getVideoUrl()!=null && !"".equals(content.getVideoUrl())){
			if(content.getVideoUrl().indexOf(ImageFtp.UPYUNWEBURL)==0){
				ImageFtp.deleteFile(content.getVideoUrl().replace(ImageFtp.UPYUNWEBURL, ""));
			}
		}
		if(content.getUrl()!=null && !"".equals(content.getUrl())){
			if(content.getUrl().indexOf(ImageFtp.UPYUNWEBURL)==0){
				ImageFtp.deleteFile(content.getUrl().replace(ImageFtp.UPYUNWEBURL, ""));
			}
		}
		if(content.getHeaderBanner()!=null && !"".equals(content.getHeaderBanner())){
				String[] hl = content.getHeaderBanner().split(",");
				for(int j=0;j<hl.length;j++){
					if(hl[j].indexOf(ImageFtp.UPYUNWEBURL)==0){
						ImageFtp.deleteFile(hl[j].replace(ImageFtp.UPYUNWEBURL, ""));
					}
				}
		}
		contentMapper.del(id);
	}
	/**
	 * 构建headerBannerList
	 * @param list
	 */
	private void buildHeaderBanner(List<Content> list){
		String headerBanner;
		List<String> inl;
		if(list!=null && list.size()>0){
			for(Content c :list){
				inl = new ArrayList<String>();
				headerBanner = c.getHeaderBanner();
				if(headerBanner!=null && !"".equals(headerBanner)){
					String[] hl = headerBanner.split(",");
					for(int j=0;j<hl.length;j++){
						inl.add(hl[j]);
					}
				}
				c.setBannerList(inl);
				//c.setHeaderBanner(null);
			}
		}
	}
	/**
	 * 根据图文id查询出图文的信息
	 * @Author chaixueteng
	 * @2016年4月26日上午10:52:31
	 */
	public Content selectById(Integer id) {
		return this.contentMapper.selectByPrimaryKey((long)id);
	}
	/** 修改图文信息
	 * @Author chaixueteng
	 * @2016年4月27日下午2:27:00
	 */
	public int update(Content ctm,Content oldContent) {
		//判断旧图片和旧视频是否哈希和字符相同再做删除操作
		String thumb = oldContent.getThumb();
		//得到旧图文信息里的缩略图
		String thumbMin = oldContent.getThumbMin();
		//得到旧图文里的视频地址
		String videoUrl = oldContent.getVideoUrl();
		//得到旧图文信息里的图
		String newthumb = ctm.getThumb();
		//得到旧图文信息里的缩略图
		String newthumbMin = ctm.getThumbMin();
		//得到旧图文里的视频地址
		String newvideoUrl = ctm.getVideoUrl();
		//删除原有的图片
		int i = this.contentMapper.update(ctm);
		if(!newthumb.equals(thumb)&&i>0 && thumb!=null && !"".equals(thumb) && thumb.length()>ImageFtp.UPYUNWEBURL.length() &&thumb.startsWith(ImageFtp.UPYUNWEBURL)){
			//http://chongaibao.b0.upaiyun.com/
			ImageFtp.deleteFile(thumb.replace(ImageFtp.UPYUNWEBURL, ""));
		}
		//删除原有缩略图
		if(!newthumbMin.equals(thumbMin)&&i>0 && thumbMin!=null && !"".equals(thumbMin) && thumbMin.length()>ImageFtp.UPYUNWEBURL.length() &&thumbMin.startsWith(ImageFtp.UPYUNWEBURL)){
			ImageFtp.deleteFile(thumbMin.replace(ImageFtp.UPYUNWEBURL, ""));
		}
		//删除原有视频
		if(!newvideoUrl.equals(videoUrl)&&i>0 && videoUrl!=null && !"".equals(videoUrl) && videoUrl.length()>ImageFtp.UPYUNWEBURL.length() &&videoUrl.startsWith(ImageFtp.UPYUNWEBURL)){
			ImageFtp.deleteFile(videoUrl.replace(ImageFtp.UPYUNWEBURL, ""));
		}
		
		return i;
	}
}
