package org.matrix.database.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.matrix.database.entity.DynamicVariable;
import org.matrix.database.mapper.DynamicVariableMapper;
import org.matrix.database.service.IDynamicVariableService;
import org.matrix.database.vo.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author matrix
 * @since 2022-01-15
 */
@Service
public class DynamicVariableServiceImpl extends ServiceImpl<DynamicVariableMapper, DynamicVariable> implements IDynamicVariableService {

    private final DynamicVariableMapper mapper;

    public DynamicVariableServiceImpl(DynamicVariableMapper dynamicVariableMapper) {
        this.mapper = dynamicVariableMapper;
    }

    /**
     * 根据变量名称获取变量
     *
     * @param name      变量名
     * @param projectId 项目id
     * @return 变量
     */
    @Override
    public Optional<DynamicVariable> getByName(String name, Long projectId) {
        return Optional.ofNullable(mapper.selectOne(Wrappers.lambdaUpdate(DynamicVariable.class)
                .eq(DynamicVariable::getName, name)
                .eq(DynamicVariable::getProjectId, projectId)));
    }

    @Override
    public int insertDynamicVariable(DynamicVariable dynamicVariable) {
        return mapper.insert(dynamicVariable);
    }

    @Override
    public int updateDynamicVariable(DynamicVariable dynamicVariable) {
        return mapper.updateById(dynamicVariable);
    }

    @Override
    public int deleteDynamicVariable(Integer id) {
        return mapper.deleteById(id);
    }

    @Override
    public List<DynamicVariable> findByProjectIdDynamicVariable(Integer projectId) {
        QueryWrapper<DynamicVariable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        return mapper.selectList(queryWrapper);
    }

    @Override
    public PageResult pageAll(PageResult pageResult) {
        IPage ipage = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        boolean flage = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flage, "name", pageResult.getQuery());
        //执行分页查询，返回值依然是分页的对象
        ipage = mapper.selectPage(ipage, queryWrapper);
        long total = ipage.getTotal();
        List<DynamicVariable> rows = ipage.getRecords();
        //回传5个参数 total/分页后的数据
        return pageResult.setTotal(total).setRows(rows);
    }

}
