package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.frog.dao.SignInStatDao;
import com.sonic.frog.domain.entity.SignInStat;
import com.sonic.frog.service.SignInStatService;
import com.sonic.frog.utils.DateConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 签到统计数据表
 * @author zzhan
 */
@Slf4j
@Service
public class SignInStatServiceImpl extends ServiceImpl<SignInStatDao, SignInStat> implements SignInStatService {

    @Autowired
    private SignInStatDao signInStatDao;

    @Override
    public SignInStat get(Long currentUserId) {
        SignInStat signInStat = getOne(Wrappers.<SignInStat>lambdaQuery()
                .eq(SignInStat::getUserId, currentUserId));
        return signInStat;
    }

    @Override
    public SignInStat init(Long currentUserId) {
        SignInStat signInStat = null;
        try {
            signInStat = new SignInStat();
            signInStat.setUserId(currentUserId);
            //获取PST时间的yyyy-MM-dd 七天的起止时间
            signInStat.setStartDay(DateConvertUtils.formatYearMonthDay(DateConvertUtils.getDateLaTime()));
            signInStat.setEndDay(DateConvertUtils.formatYearMonthDay(DateConvertUtils.getDateLaTime().plusDays(6)));
            signInStat.setAllDays(0);
            signInStat.setCreateTime(LocalDateTime.now());
            signInStat.setEditTime(LocalDateTime.now());
            //保存到数据库中
            save(signInStat);
        } catch (Exception e) {
            log.error("SignInStatServiceImpl init：", e);
            //查询数据并返回
            signInStat = getOne(Wrappers.<SignInStat>lambdaQuery().eq(SignInStat::getUserId, currentUserId));
        }
        return signInStat;
    }

    @Override
    public void updateStartEndDayAndDays(Long id, String startDay, String endDay) {
        update(Wrappers.<SignInStat>lambdaUpdate()
                .set(SignInStat::getStartDay, startDay)
                .set(SignInStat::getEndDay, endDay)
                .eq(SignInStat::getId, id));
    }

    @Override
    public void updateStat(Long id, Integer days) {
        update(Wrappers.<SignInStat>lambdaUpdate()
                .set(days != null, SignInStat::getAllDays, days)
                .eq(SignInStat::getId, id));
    }

}
