package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.dao.primary.SqlEntityRepository;
import com.liangjian.dataplatform.member.entity.po.primary.SqlEntity;
import com.liangjian.dataplatform.member.service.ISqlEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: 黄子奇
 * @Date: 2019/10/21
 */
@Service
public class SqlEntityService implements ISqlEntityService {

    @Autowired
    private SqlEntityRepository sqlEntityRepository;

    @Override
    public SqlEntity queryById(String id) {
        try {
            return sqlEntityRepository.queryById(id);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    @Override
    public Page<SqlEntity> queryByDescription(String desc, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size,  Sort.Direction.DESC,"lastUpdate");
        if (desc == null || desc.isEmpty()) {
            return sqlEntityRepository.findAll(pageable);
        } else {
            return sqlEntityRepository.queryByDescriptionLike("%"+desc+"%",pageable);
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean addSqlEntity(SqlEntity sqlEntity) {
        try{
            sqlEntityRepository.saveWithCycle(sqlEntity);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateSqlEntity(SqlEntity sqlEntity) {
        try{
            sqlEntityRepository.saveWithCycle(sqlEntity);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteSqlEntity(String id) {
        try {
            sqlEntityRepository.deleteById(id);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
