package com.xxfc.platform.activity.biz;

import cn.hutool.core.bean.BeanUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.activity.dto.ApLogDTO;
import com.xxfc.platform.activity.dto.QueryLogDto;
import com.xxfc.platform.activity.entity.ActivityPopularizeLog;
import com.xxfc.platform.activity.mapper.ActivityPopularizeLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户参与推广活动（邀请有礼）的活动记录的记录（日志）
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-07-05 15:23:04
 */
@Service
@Slf4j
public class ActivityPopularizeLogBiz extends BaseBiz<ActivityPopularizeLogMapper,ActivityPopularizeLog>{

    @Autowired
    ActivityPopularizeItemBiz activityPopularizeItemBiz;

    @Autowired
	UserFeign userFeign;

	@Autowired
	HttpServletRequest request;

    public ApLogDTO selectOneApLogDTO(ActivityPopularizeLog entity){
        ActivityPopularizeLog apl = mapper.selectOne(entity);
        if(null != apl) {
            ApLogDTO apLogDTO = BeanUtil.toBean(apl, ApLogDTO.class);
            apLogDTO.setItem(activityPopularizeItemBiz.selectById(apLogDTO.getItemId()));
            return apLogDTO;
        }else {
            return null;
        }
    }

    public ActivityPopularizeLog selectByUserIdAndPopularIdAndItemId(ActivityPopularizeLog entity) {
		Example example = new Example(ActivityPopularizeLog.class);
		example.createCriteria().andEqualTo("userId", entity.getUserId()).andEqualTo("itemId", entity.getItemId()).andEqualTo("popularizeId", entity.getPopularizeId());
		return mapper.selectOneByExample(example);
	}
    public PageDataVO<ApLogDTO> selectByUserId(QueryLogDto queryLogDto) {
		String token = request.getHeader("Authorization");
		AppUserDTO appUserDTO = null;
		if (StringUtils.isNotBlank(token)) {
			appUserDTO = userFeign.userDetailByToken(token).getData();
		} else {
			return new PageDataVO<>();
		}

		Integer page = queryLogDto.getPage() == null ? 1 : queryLogDto.getPage();
		Integer limit = queryLogDto.getLimit() == null ? 5 : queryLogDto.getLimit();
		queryLogDto.setUserId(appUserDTO.getUserid());
		queryLogDto.setPage(page);
		queryLogDto.setLimit(limit);
		Query query = new Query(queryLogDto);
		PageDataVO<ApLogDTO> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByUserId(query.getSuper()));
		if (pageDataVO.getData() != null) {
			pageDataVO.getData().parallelStream().forEach(result -> {
				result.setItem(activityPopularizeItemBiz.selectById(result.getItemId()));
			});
		}
		return pageDataVO;
	}



}