package org.linlinjava.jz.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.jz.db.dao.JzStorageMapper;
import org.linlinjava.jz.db.domain.JzStorage;
import org.linlinjava.jz.db.domain.JzStorageExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * 商场 上传信息（图片等）处理服务类
 *
 */
@Service
public class JzStorageService {
    @Autowired
    private JzStorageMapper storageMapper;

    public void deleteByKey(String key) {
        JzStorageExample example = new JzStorageExample();
        example.or().andKeyEqualTo(key);
        storageMapper.logicalDeleteByExample(example);
    }

    public void add(JzStorage storageInfo) {
        storageInfo.setAddTime(LocalDateTime.now());
        storageInfo.setUpdateTime(LocalDateTime.now());
        storageMapper.insertSelective(storageInfo);
    }

    public JzStorage findByKey(String key) {
        JzStorageExample example = new JzStorageExample();
        example.or().andKeyEqualTo(key).andDeletedEqualTo(false);
        return storageMapper.selectOneByExample(example);
    }

    public int update(JzStorage storageInfo) {
        storageInfo.setUpdateTime(LocalDateTime.now());
        return storageMapper.updateByPrimaryKeySelective(storageInfo);
    }

    public JzStorage findById(Integer id) {
        return storageMapper.selectByPrimaryKey(id);
    }

    public List<JzStorage> querySelective(String key, String name, Integer page, Integer limit, String sort, String order) {
        JzStorageExample example = new JzStorageExample();
        JzStorageExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return storageMapper.selectByExample(example);
    }

}
