package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.UserRoleDetailMapper;
import com.crm.manager.dao.repository.UserRoleDetailRepository;
import com.crm.rely.backend.core.pojo.table.UserRoleDetailTable;
import com.crm.manager.service.UserRoleDetailService;
import com.crm.rely.backend.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author houn
 */
@SuppressWarnings("Duplicates")
@Service
public class UserRoleDetailServiceImpl implements UserRoleDetailService {

    @Autowired
    private UserRoleDetailRepository userRoleDetailRepository;

    @Autowired
    private UserRoleDetailMapper userRoleDetailMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void update(List<UserRoleDetailTable> sellerRoleDetailTables, Long roleId) throws ServiceException {

        List<UserRoleDetailTable> deleteSellerRoleDetailTables = userRoleDetailMapper.findAllByRoleId(roleId);

        if (deleteSellerRoleDetailTables != null && deleteSellerRoleDetailTables.size() > 0) {
            userRoleDetailMapper.delete(deleteSellerRoleDetailTables);
        }

        if (sellerRoleDetailTables != null && sellerRoleDetailTables.size() > 0) {
            userRoleDetailRepository.save(sellerRoleDetailTables);
        }
    }

    @Override
    public List<UserRoleDetailTable> getUserRoleDetailsByRoleId(Long roleId) throws ServiceException {

        List<UserRoleDetailTable> roleDetailTables = userRoleDetailRepository.findAllByRoleId(roleId);

        return roleDetailTables;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void deleteRoleDetailByRoleId(Long roleId) throws ServiceException {
        List<UserRoleDetailTable> sellerRoleDetailTables = userRoleDetailRepository.findAllByRoleId(roleId);
        if (sellerRoleDetailTables == null || sellerRoleDetailTables.size() == 0) {
            return;
        }
        userRoleDetailRepository.delete(sellerRoleDetailTables);
    }
}
