package com.cool.bang.common.base;

import com.cool.bang.common.web.request.PageDomain;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Base Service Implements (基础服务实现类)
 *
 * @author PeiZhi Guo
 * 2021-2-27 10:59
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T> implements BaseIService<T> {

    @Autowired
    protected M baseMapper;

    @Override
    public M getBaseMapper() {
        return baseMapper;
    }

    @Override
    public PageInfo<T> page(PageDomain page, T param) {
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<T> list = baseMapper.selectByParam(param);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<T> page(PageDomain page, Map<String, Object> map) {
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<T> list = baseMapper.selectByMap(map);
        return new PageInfo<>(list);
    }

    @Override
    public List<T> list(T param) {
        return baseMapper.selectByParam(param);
    }

    @Override
    public List<T> list(Map<String, Object> map) {
        return baseMapper.selectByMap(map);
    }

    @Override
    public T queryById(Serializable id) {
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(T param) {
        return baseMapper.insert(param) > 0;
    }

    @Override
    public boolean saveBatch(List<T> params) {
        return baseMapper.insertBatch(params) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(T param) {
        return baseMapper.update(param) > 0;
    }

    @Override
    public boolean updateBatch(List<T> params) {
        return baseMapper.updateBatch(params) > 0;
    }

    @Override
    public boolean updateStatus(String businessNumber, Integer status) {
        Map<String, Object> map = new HashMap<>();
        map.put("businessNumber", businessNumber);
        map.put("status", status);
        return baseMapper.updateStatus(map) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        return baseMapper.delete(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<? extends Serializable> ids) {
        return baseMapper.deleteBatch(ids) > 0;
    }
}
