package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.dao.elasticsearch.UserGrowthLogRepository;
import com.liangjian.dataplatform.member.entity.po.elasticsearch.UserGrowthLog;
import com.liangjian.dataplatform.member.service.IUserGrowthLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/16
 */
@Service
public class UserGrowthLogService implements IUserGrowthLogService {
    @Autowired
    private UserGrowthLogRepository userGrowthLogRepository;

    @Override
    public Page<UserGrowthLog> queryBySecretPhone(String secretPhone, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size, Sort.Direction.DESC,"crtDate");
        return userGrowthLogRepository.findBySecretPhone(secretPhone,pageable);
    }

    @Override
    public Page<UserGrowthLog> queryBySecretPhoneAndIncrease(String secretPhone, boolean increase, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size, Sort.Direction.DESC,"crtDate");
        return userGrowthLogRepository.findBySecretPhoneAndIncrease(secretPhone,increase,pageable);
    }

    @Override
    public UserGrowthLog getLastLog(String secretPhone) {
        Page<UserGrowthLog> logs = queryBySecretPhone(secretPhone, 0, 1);
        List<UserGrowthLog> list = logs.getContent();
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Integer getPointBalance(String secretPhone) {
        UserGrowthLog log = getLastLog(secretPhone);
        return log == null ? 0 : log.getBalance();
    }

    @Override
    public boolean addLog(UserGrowthLog log) {
        try {
            log.setLastUpdate(new Date());
            userGrowthLogRepository.save(log);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
