package com.sonic.bear.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.bear.dao.UserCommonlyUsedLogDao;
import com.sonic.bear.domain.entity.UserCommonlyUsedLog;
import com.sonic.bear.service.UserCommonlyUsedLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author code
 */
@Slf4j
@Service
public class UserCommonlyUsedLogServiceImpl extends ServiceImpl<UserCommonlyUsedLogDao, UserCommonlyUsedLog> implements UserCommonlyUsedLogService {

    @Override
    public void addData(Long userId, Integer dataType, String dataValue) {
        try {
            //查询数据库，再写入数据
            UserCommonlyUsedLog queryUserCommonlyUsedLog = getOne(Wrappers.<UserCommonlyUsedLog>lambdaQuery()
                    .select(UserCommonlyUsedLog::getId, UserCommonlyUsedLog::getUseCount, UserCommonlyUsedLog::getDataValue)
                    .eq(UserCommonlyUsedLog::getUserId, userId)
                    .eq(UserCommonlyUsedLog::getDataType, dataType)
                    .eq(UserCommonlyUsedLog::getDataValue, dataValue));
            if(queryUserCommonlyUsedLog != null) {
                //更新数据
                queryUserCommonlyUsedLog.setUseCount(queryUserCommonlyUsedLog.getUseCount() + 1);
                updateById(queryUserCommonlyUsedLog);
                return;
            }
            UserCommonlyUsedLog userCommonlyUsedLog = new UserCommonlyUsedLog();
            userCommonlyUsedLog.setUserId(userId);
            userCommonlyUsedLog.setDataType(dataType);
            userCommonlyUsedLog.setDataValue(dataValue);
            userCommonlyUsedLog.setUseCount(1);
            userCommonlyUsedLog.setCreateTime(LocalDateTime.now());
            userCommonlyUsedLog.setEditTime(LocalDateTime.now());
            save(userCommonlyUsedLog);
        } catch (Exception e) {
            log.error("===> UserCommonlyUsedLog addData error : ", e);
        }
    }

    @Override
    public List<UserCommonlyUsedLog> queryData(List<Long> userIdList, List<String> dataValueList) {
        List<UserCommonlyUsedLog> list = list(Wrappers.<UserCommonlyUsedLog>lambdaQuery()
                .select(UserCommonlyUsedLog::getUserId, UserCommonlyUsedLog::getDataType, UserCommonlyUsedLog::getDataValue)
                .in(UserCommonlyUsedLog::getUserId, userIdList)
                .in(UserCommonlyUsedLog::getDataValue, dataValueList));
        return list;
    }

}
