package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.UserRoleNodeMapper;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.manager.dao.repository.UserRoleNodeRepository;
import com.crm.manager.dao.mapper.SysNodeMapper;
import com.crm.rely.backend.core.pojo.table.UserRoleNodeTable;
import com.crm.rely.backend.core.pojo.view.SysNodeView;
import com.crm.manager.service.UserRoleNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author houn
 */
@Service
public class UserRoleNodeServiceImpl implements UserRoleNodeService {

    @Autowired
    private UserRoleNodeRepository userRoleNodeRepository;

    @Autowired
    private UserRoleNodeMapper userRoleNodeMapper;

    @Autowired
    private SysNodeMapper shopNodeMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void update(List<UserRoleNodeTable> sellerRoleNodeTables, Long roleId) throws ServiceException {

        List<UserRoleNodeTable> deleteSellerRoleDetailTables = userRoleNodeMapper.findAllByRoleId(roleId);

        if (deleteSellerRoleDetailTables != null && deleteSellerRoleDetailTables.size() > 0) {
            userRoleNodeMapper.delete(deleteSellerRoleDetailTables);
        }
        if (sellerRoleNodeTables != null && sellerRoleNodeTables.size() > 0) {
            userRoleNodeRepository.save(sellerRoleNodeTables);
        }

    }

    @Override
    public List<SysNodeView> getSysNodesByRoleId(Long roleId) throws ServiceException {

        List<SysNodeView> sysNodeViews = shopNodeMapper.getSysNodesByRoleId(roleId);

        return sysNodeViews;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void deleteRoleNodeByRoleId(Long roleId) throws ServiceException {
        List<UserRoleNodeTable> sellerRoleNodeTables = userRoleNodeRepository.findAllByRoleId(roleId);
        if (sellerRoleNodeTables == null || sellerRoleNodeTables.size() == 0) {
            return;
        }
        userRoleNodeRepository.delete(sellerRoleNodeTables);
    }
}
