package com.ssj.service.weixin.story.service.impl;

import com.ssj.bean.weixin.story.bean.StoryTaskIntegral;
import com.ssj.bean.weixin.story.bean.StoryTaskTopic;
import com.ssj.dao.weixin.story.dao.StoryTaskTopicDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.service.weixin.story.service.StoryTaskIntegralService;
import com.ssj.service.weixin.story.service.StoryTaskTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/** 
 * @author  ZhangCaibao 
 * @version 2018年3月21日 上午11:04:51 
 * 类说明 
 */
@Service
@Transactional
public class StoryTaskTopicServiceImpl extends BaseServiceImpl<StoryTaskTopic, String> implements StoryTaskTopicService{
	@Autowired
	private StoryTaskTopicDao storyTaskTopicDao;
	@Autowired
	private StoryTaskIntegralService storyTaskIntegralService;
	
	@Override
	public PagingAndSortingRepository<StoryTaskTopic, String> getDao() {
		return storyTaskTopicDao;
	}

	@Override
	public List<StoryTaskTopic> findByStoryTaskId(String storyTaskId) {
		return storyTaskTopicDao.findByStoryTaskId(storyTaskId);
	}
	@Override
	public List<StoryTaskTopic> randomTopic(String userId) {
		
		List<StoryTaskIntegral> list=storyTaskIntegralService.findByUserId(userId);
		if(list !=null && list.size()>0){
             for (StoryTaskIntegral storyTaskIntegral : list) {
            	 //获取一次，题目数量加一
            	 storyTaskIntegral.setTotal(storyTaskIntegral.getTotal()+1);
			 }
		}else{
			    list =new ArrayList<StoryTaskIntegral>();
				list.add(new StoryTaskIntegral(1, 1, userId));
				list.add(new StoryTaskIntegral(1, 2, userId));
				list.add(new StoryTaskIntegral(1, 3, userId));
				list.add(new StoryTaskIntegral(1, 4, userId));
		}
		storyTaskIntegralService.save(list);
		List<StoryTaskTopic> topicList=	new ArrayList<StoryTaskTopic>();
		for (int i = 1; i < 5; i++) {
			StoryTaskTopic top = storyTaskTopicDao.randomTopic(i);
			if(top!=null){
				topicList.add(top);
			}
		}
		//获取题目这里需要改
		return topicList;
	}

	@Override
	public Page<StoryTaskTopic> findByPage(Map<String, Object> params,
			Pageable sp) {
		Map<String, SearchFilter> filters = SearchFilter.parse(params);
		Specification<StoryTaskTopic> specification = DynamicSpecifications.bySearchFilter(filters.values(), StoryTaskTopic.class);    
		return  storyTaskTopicDao.findAll(specification, sp);
	}

}
