package com.usky.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.system.RemoteDeptService;
import com.usky.system.domain.SysTenant;
import com.usky.system.domain.SysTenantConfig;
import com.usky.system.domain.SysUserRole;
import com.usky.system.domain.SysUserTenant;
import com.usky.system.mapper.SysTenantConfigMapper;
import com.usky.system.mapper.SysUserRoleMapper;
import com.usky.system.mapper.SysUserTenantMapper;
import com.usky.system.service.SysTenantConfigService;
import com.usky.system.service.SysTenantService;
import com.usky.system.service.SysUserTenantService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.system.service.vo.TenantPlatformVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author han
 * @since 2024-09-11
 */
@Service
public class SysUserTenantServiceImpl extends AbstractCrudService<SysUserTenantMapper, SysUserTenant> implements SysUserTenantService {

    @Autowired
    private SysTenantService sysTenantService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysTenantConfigMapper sysTenantConfigMapper;

    /**
     * 企业邀请用户
     *
     * @param sysUserTenant
     */
    @Override
    @Transactional
    public void insertInviteUser(SysUserTenant sysUserTenant) {
        int userCount = baseMapper.checkUserIdUnique(sysUserTenant.getTenantId(), sysUserTenant.getUserId());
        if (userCount > 0) {
            throw new BusinessException("用户已绑定，无法重复绑定！");
        } else {
            // SysUserRole sysUserRole = sysUserRoleMapper.selectOne(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, sysUserTenant.getUserId()).eq(SysUserRole::getTenantId, sysUserTenant.getTenantId()));
            // if (sysUserRole == null) {
            //     SysUserRole sysUserRole1 = new SysUserRole();
            //     sysUserRole1.setUserId(sysUserTenant.getUserId());
            //     sysUserRole1.setTenantId(sysUserTenant.getTenantId());
            //     sysUserRoleMapper.insert(sysUserRole1);
            // }
            this.save(sysUserTenant);
        }
    }

    /**
     * 企业解绑用户
     *
     * @param tenantId 租户ID
     * @param userId 用户ID
     */
    @Override
    @Transactional
    public void deleteUserTenant(Integer tenantId, Long userId) {
        baseMapper.deleteUserTenant(tenantId, userId);
        Long[] userIds = new Long[]{userId};
        sysUserRoleMapper.deleteUserRole(userIds, tenantId);
    }

    /**
     * 根据用户查询企业下拉框
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysTenant> getTenantByUser(Long userId) {
        LambdaQueryWrapper<SysUserTenant> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserTenant::getUserId, userId);
        List<SysUserTenant> userTenants = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(userTenants)) {
            return new ArrayList<>();
        }

        List<Integer> tenantIdList = userTenants.stream()
                .map(SysUserTenant::getTenantId)
                .collect(Collectors.toList());

        // 租户列表（仅启用状态）
        LambdaQueryWrapper<SysTenant> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.in(SysTenant::getId, tenantIdList).eq(SysTenant::getStatus, 0);
        List<SysTenant> tenantList = sysTenantService.list(queryWrapper1);
        if (CollectionUtils.isEmpty(tenantList)) {
            return tenantList;
        }

        // 租户配置（用于 logo）
        LambdaQueryWrapper<SysTenantConfig> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.in(SysTenantConfig::getTenantId, tenantIdList);
        List<SysTenantConfig> tenantConfigList = sysTenantConfigMapper.selectList(queryWrapper2);

        // 用 Map 做 O(1) 查找，避免嵌套循环
        Map<Integer, SysUserTenant> tenantIdToUserTenant = userTenants.stream()
                .collect(Collectors.toMap(SysUserTenant::getTenantId, ut -> ut, (a, b) -> a));
        Map<Integer, SysTenantConfig> tenantIdToConfig = tenantConfigList.stream()
                .collect(Collectors.toMap(SysTenantConfig::getTenantId, c -> c, (a, b) -> a));

        for (SysTenant tenant : tenantList) {
            SysUserTenant ut = tenantIdToUserTenant.get(tenant.getId());
            if (ut != null) {
                tenant.setIsDefault(ut.getIsDefault());
            }
            SysTenantConfig config = tenantIdToConfig.get(tenant.getId());
            if (config != null) {
                tenant.setTenantLogo(config.getMiddleLogo());
            }
        }
        return tenantList;
    }

    @Override
    @Transactional
    public Boolean getIdByUser(Integer tenantId, Long userId) {
        LambdaQueryWrapper<SysUserTenant> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserTenant::getUserId, userId)
                .eq(SysUserTenant::getTenantId, tenantId);
        List<SysUserTenant> userTenants = this.list(queryWrapper);
        return userTenants.get(0).getIsDefault();
    }

    @Override
    @Transactional
    public Integer getIsDefaultByUser(Long userId) {
        LambdaQueryWrapper<SysUserTenant> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserTenant::getUserId, userId)
                .eq(SysUserTenant::getIsDefault, 1);
        List<SysUserTenant> userTenants = this.list(queryWrapper);
        return userTenants.get(0).getTenantId();
    }

    @Override
    @Transactional
    public void updateUserTenant(SysUserTenant userTenant) {
        LambdaUpdateWrapper<SysUserTenant> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysUserTenant::getIsDefault, 0)
                .eq(SysUserTenant::getUserId, userTenant.getUserId())
                .eq(SysUserTenant::getIsDefault, 1);
        this.update(updateWrapper);
        LambdaUpdateWrapper<SysUserTenant> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.set(SysUserTenant::getIsDefault, 1)
                .eq(SysUserTenant::getUserId, userTenant.getUserId())
                .eq(SysUserTenant::getTenantId, userTenant.getTenantId());
        this.update(updateWrapper1);
    }
}
