package com.ifish.serviceImpl;

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

import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ifish.dao.UserActivityDao;
import com.ifish.dao.UserAssetDao;
import com.ifish.dao.UserDao;
import com.ifish.dto.PageingDto;
import com.ifish.dto.UserActivityDto;
import com.ifish.entity.Grade;
import com.ifish.entity.User;
import com.ifish.entity.UserActivity;
import com.ifish.entity.UserAsset;
import com.ifish.hibernate.Pagination;
import com.ifish.service.CacheService;
import com.ifish.service.UserActivityService;
import com.ifish.util.ResultUtil;
import com.ifish.validator.PageParam;

/**
 * 用户动态
 *
 * @author Administrator
 *
 */
@Service
@Transactional
public class UserActivityServiceImpl implements UserActivityService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserAssetDao userAssetDao;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private UserActivityDao userActivityDao;

    /**
     * 分页获取用户动态
     */
    @Override
    public PageingDto<?> getUserActivityByPage(Integer pageSize, Integer firstResult) {
        //分页获取数据
        Pagination<UserActivity> page = userActivityDao.findByCriteria(firstResult, pageSize, Order.desc("activityId"));
        List<UserActivity> list = page.getList();
        firstResult += list.size();
        //返回数据
        List<UserActivityDto> dtoList = new ArrayList<UserActivityDto>();
        for (UserActivity userActivity : list) {
            Integer userId = userActivity.getUserId();
            User user = userDao.get(userId);
            if (user != null) {
                UserActivityDto dto = new UserActivityDto(userActivity.getActivityId(), userId, userActivity.getActivityType(), userActivity.getCreateTime());
                dtoList.add(dto);
                dto.setNickName(user.getNickName());
                dto.setUserImg(user.getUserImg());
                UserAsset userAsset = userAssetDao.get(userId);
                if (userAsset != null) {
                    //经验值
                    Integer gradeValue = userAsset.getGradeValue();
                    //等级
                    for (Grade grade : cacheService.getGradeList()) {
                        if (gradeValue >= grade.getMinValue() && gradeValue < grade.getMaxValue()) {
                            dto.setGradeNum(grade.getGradeNum());
                            break;
                        }
                    }
                }
            }
        }
        //分页数据封装
        return ResultUtil.success(firstResult, page.getTotalCount(), dtoList);
    }

}
