package com.docus.server.archivefile.infrastructure.dao.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.db.dao.impl.BaseDaoImpl;
import com.docus.infrastructure.web.request.SearchRequest;
import com.docus.infrastructure.web.response.PageResult;
import com.docus.server.archivefile.infrastructure.dao.ITaskConfigDao;
import com.docus.server.archivefile.infrastructure.mapper.TaskConfigMapper;
import com.docus.server.entity.TaskConfig;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TaskConfigDaoImpl extends BaseDaoImpl<TaskConfigMapper, TaskConfig> implements ITaskConfigDao {

    @Override
    public PageResult<TaskConfig> searchTaskConfig(SearchRequest searchRequest) {
        PageHelper.startPage(searchRequest.getPageNum(), searchRequest.getPageSize());

        LambdaQueryWrapper<TaskConfig> query = Wrappers.lambdaQuery();
        //时间范围，默认按createTime
        if (searchRequest.getBeginTime() != null) {
            query.ge(TaskConfig::getCreateTime, searchRequest.getBeginTime());
        }
        if (searchRequest.getEndTime() != null) {
            query.le(TaskConfig::getCreateTime, searchRequest.getEndTime());
        }
        if (searchRequest.getParams("state") != null) {
            query.eq(TaskConfig::getState, searchRequest.getParams("state"));
        }
        if (Func.isNotBlank(searchRequest.getKeyword())) {
            query.like(TaskConfig::getName, String.format("%s%s%s", "%", searchRequest.getKeyword(), "%"));
        }
        if (searchRequest.getParams("type") != null) {
            query.eq(TaskConfig::getType, searchRequest.getParams("type"));
        }

        //默认createTime倒序排序
        query.orderByDesc(TaskConfig::getCreateTime);
        List<TaskConfig> list = super.find(query);
        return new PageResult<>(list);
    }

    @Override
    public int findByNameAndIdAndKey(Long id, String name, String retryKey) {
        LambdaQueryWrapper<TaskConfig> query = Wrappers.lambdaQuery();
        if (id != null) {
            query.ne(TaskConfig::getId, id);
        }
        if (Func.isNotBlank(name)) {
            query.eq(TaskConfig::getName, name);
        }
        if (Func.isNotBlank(retryKey)) {
            query.eq(TaskConfig::getRetryKey, retryKey);
        }
        return baseMapper.selectCount(query);
    }


}
