/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:tgaWebsite
 * File Name:NewsInfoService.java
 * Package Name:ccpit.business.newsManage
 * Date:2017年3月21日下午2:46:53
 * Copyright (c) 2017, dingwei@ccpit.org All Rights Reserved.
 *
 */

package org.ccpit.business.newsManage;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.ccpit.base.controller.Convert;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageBo;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.logManage.LogInfoService;
import org.ccpit.base.user.User;
import org.ccpit.base.utils.DateConvert;
import org.ccpit.base.utils.StringUtil;
import org.ccpit.base.utils.page.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * ClassName:NewsInfoService <br/>
 * Function: TODO 新闻信息管理逻辑层. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2017年3月21日 下午2:46:53 <br/>
 * 
 * @author dingwei
 * @version
 * @since JDK 1.8.0
 * @see
 */
@Transactional
@Service
public class NewsInfoService {

	@Autowired
	private NewsInfoDao newsInfoDao;
	@Autowired
	private LogInfoService logInfoService;


	public boolean addOrUpdateNewsInfo(NewsInfo newsInfo, String operate,
                                       String newsInfoId, User user, HttpServletRequest request) {
		boolean flag = false;
		if ("add".equals(operate)) {
			newsInfo.setCreateTime(new Date());
			newsInfo.setCreator(user);
			flag = newsInfoDao.save(newsInfo);
			if (flag) {
				// 记录用户操作日志信息
				logInfoService.recordLog(request, "新增新闻数据信息");
			}
		} else if ("edit".equals(operate)) {
			NewsInfo newsInfo1 = queryNewsInfoById(Long.parseLong(newsInfoId));
			PageUtil.setterValues(newsInfo, newsInfo1);
			newsInfo1.setModifyTime(new Date());
			newsInfo1.setModifyBy(user);
			flag = newsInfoDao.update(newsInfo1);
			if (flag) {

				logInfoService.recordLog(request, "修改新闻数据信息");
			}
		}
		return flag;
	}

	public boolean deleteNewsInfoById(String jsonIds) {
		JSONArray jsonArray = JSONArray.fromObject(jsonIds);
		Object[] ids = jsonArray.toArray();
		boolean flag = false;
		for (Object metadataId : ids) {
			NewsInfo newsInfo = newsInfoDao.queryById(Long.valueOf(String
					.valueOf(metadataId)));
			newsInfo.setDeleted(true);
			flag = newsInfoDao.update(newsInfo);
		}
		return flag;
	}

	public NewsInfo queryNewsInfoById(long id) {
		return newsInfoDao.queryById(id);
	}

	/**
	 * 
	 * isExistNewsInfo:(根据标题判断新闻信息是否存在). <br/>
	 * 
	 * @author dingwei
	 * @param title
	 * @return Date:2017年3月22日上午9:30:39
	 * @since JDK 1.8.0
	 */
	public boolean queryNewsInfoByTitle(String title) {
		if (null != title && !"".equals(title)) {
			try {
				title = java.net.URLDecoder.decode(title, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		List<NewsInfo> newsInfoList = newsInfoDao.query(
				"from NewsInfo where title = '" + title + "'", null);
		if (null != newsInfoList && newsInfoList.size() > 0) {
			return true;
		}
		return false;
	}
	
	public Page<NewsInfo> queryNewsInfos(PageRequest pageRequest, String title,
                                         String newsType) {
		StringBuffer hql = new StringBuffer("from NewsInfo where 1=1");
		if (title != null && !"".equals(title)) {
			hql.append(" and title like '%" + title + "%'");
		}
		if (newsType != null && !"".equals(newsType)) {
			hql.append(" and newsType = " + Integer.parseInt(newsType));
		}
		hql.append(" order by createTime desc");
		return newsInfoDao.findPage(pageRequest, hql.toString(), null);
	}

	public Map<String, Object> convertToMap(NewsInfo newsInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (newsInfo == null) {
			return map;
		}
		map.put("id", newsInfo.getId());
		map.put("title", newsInfo.getTitle());
		map.put("introduction", newsInfo.getIntroduction());
		map.put("imagePath", newsInfo.getImagePath());
		map.put("newsSource", newsInfo.getNewsSource());
		map.put("newsType",
				0 == newsInfo.getNewsType() ? ""
						: 1 == newsInfo.getNewsType() ? "中心要闻" : "港澳新闻");
		map.put("infotatus", 0 == newsInfo.getInfotatus() ? "编辑中" : "编辑完成");
		map.put("createTime",
				StringUtil.DATE_FORMATE.format(newsInfo.getCreateTime()));
		map.put("clickVolume", newsInfo.getClickVolume());
		map.put("creator", newsInfo.getCreator().getUsername());

		return map;
	}

	public PageBo<NewsInfo> convert(Page<NewsInfo> page) {
		return new PageBo<NewsInfo>(page, new Convert<NewsInfo>() {
			@Override
			public Map<String, Object> convert(NewsInfo obj) {
				return convertToMap(obj);
			}
		});
	}
	
	public void setNoHead () {
		String headSql = "update tga_NewsInfo set carousel = '否'";
		newsInfoDao.currentSession().createSQLQuery(headSql).executeUpdate();
	}
	
	public void addClickVolume (NewsInfo newsInfo) {
		newsInfo.setClickVolume((newsInfo.getClickVolume())+1);
		newsInfoDao.save(newsInfo);
	}

	public List<Field> createNewsInfosIndex(NewsInfo newsInfo) {
		List<Field> fields = new ArrayList<Field>();
		Field id = new Field("id", "n" + newsInfo.getId(), Store.YES,
				Index.NOT_ANALYZED);
		fields.add(id);
		Field title = new Field("title", newsInfo.getTitle(), Store.YES,
				Index.ANALYZED);
		fields.add(title);
		Field createTime = new Field("createTime",
				DateConvert.convertDateWithoutHms(newsInfo.getCreateTime()),
				Store.YES, Index.NO);
		fields.add(createTime);
		return fields;
	}
}
