package com.sqx.modules.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.Result;
import com.sqx.modules.record.entity.Record;
import com.sqx.modules.record.dao.RecordDao;
import com.sqx.modules.record.service.RecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-01-18
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordDao, Record> implements RecordService {

    @Override
    public IPage<Record> getMyRecordList(Integer page, Integer limit, Record record) {
        Page<Record> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        if(record.getUserId()==null){
            return null;
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(record).orderByDesc("create_time"));
    }

    @Override
    public Result deleteRecord(Long userId, Long recordId) {
        if(recordId!=null){
            return Result.upStatus(baseMapper.deleteById(recordId));
        }else {
            return Result.upStatus(baseMapper.delete(new QueryWrapper<Record>().eq("user_id", userId)));
        }
    }
    @Override
    public void saveRecord(Long userId, String keyWord){
        Record hasRecord = baseMapper.selectOne(new QueryWrapper<Record>().eq("user_id", userId).eq("key_word", keyWord));
        if(hasRecord!=null){
            hasRecord.setCreateTime(LocalDateTime.now());
            baseMapper.updateById(hasRecord);
        }else {
            Record record = new Record();
            record.setUserId(userId);
            record.setKeyWord(keyWord);
            record.setCreateTime(LocalDateTime.now());
            baseMapper.insert(record);
        }
    }

    @Override
    public IPage<String> getHotKeyWord(Integer page, Integer limit) {
        Page<String> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getHotKeyWord(pages);


    }
}
