package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.SysTenant;
import com.ruoyi.system.domain.SysTenantUsrRel;
import com.ruoyi.system.mapper.SysTenantMapper;
import com.ruoyi.system.mapper.SysTenantUsrRelMapper;
import com.ruoyi.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service("sysTenantServiceImpl")
@ConditionalOnProperty(prefix = "ruoyi.tenant", name = "enable", havingValue = "true")
public class SysTenantServiceImpl implements ISysTenantService {

    @Autowired
    private SysTenantMapper sysTenantMapper;

    @Autowired
    private SysTenantUsrRelMapper sysTenantUsrRelMapper;

    @Override
    public List<SysTenant> selectTenantList(SysTenant sysTenant) {
        return sysTenantMapper.selectTenantList(sysTenant);
    }

    @Override
    public SysTenant selectTenantById(Long id) {
        return sysTenantMapper.selectTenantById(id);
    }

    @Override
    public int insertTenant(SysTenant sysTenant) {
        return sysTenantMapper.insertTenant(sysTenant);
    }

    @Override
    public int updateTenant(SysTenant sysTenant) {
        return sysTenantMapper.updateTenant(sysTenant);
    }

    /**
     * 批量删除租户
     *
     * @param ids 需要删除的租户主键
     * @return 结果
     */
    @Override
    public int deleteSysTenantByIds(Long[] ids) {
        return sysTenantMapper.deleteSysTenantByIds(ids);
    }

    /**
     * 删除租户信息
     *
     * @param id 租户主键
     * @return 结果
     */
    @Override
    public int deleteSysTenantById(Long id) {
        return sysTenantMapper.deleteSysTenantById(id);
    }

    @Override
    public int deleteSysTenantUsrByUsrId(Long usrId) {
        return sysTenantUsrRelMapper.deleteTenantUsrRelByUsrId(usrId);
    }

    @Override
    public int deleteSysTenantUsrByUsrIds(Long[] usrIds) {
        return sysTenantUsrRelMapper.deleteTenantUsrRelByUsrIds(usrIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUsrTenant(Long userId) {
        sysTenantUsrRelMapper.deleteTenantUsrRelByUsrId(userId);
        sysTenantUsrRelMapper.insertTenantUsrRel(new SysTenantUsrRel() {{
            setUsrId(userId);
        }});
    }

    @Override
    public SysTenant selectTenantByUsrId(Long usrId) {
        SysTenantUsrRel sysTenantUsrRel = sysTenantUsrRelMapper.selectTenantUsrByUsrId(usrId);
        if (ObjectUtils.isEmpty(sysTenantUsrRel)) {
            return new SysTenant();
        }
        return sysTenantMapper.selectTenantById(sysTenantUsrRel.getTenantId());
    }
}
