package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysTenant;
import org.dromara.system.domain.bo.SysUserTenantBO;
import org.dromara.system.domain.vo.SysUserTenantVO;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysTenantMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.system.domain.SysUserTenant;
import org.dromara.system.mapper.SysUserTenantMapper;
import org.dromara.system.service.ISysUserTenantService;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserTenantServiceImpl extends ServiceImpl<SysUserTenantMapper, SysUserTenant> implements ISysUserTenantService {

    private final SysTenantMapper sysTenantMapper;

    private final SysDeptMapper sysDeptMapper;

    @Override
    public void save(SysUserTenantBO userTenantBO) {
        List<String> tenantIds = userTenantBO.getTenantIds();
        this.remove(Wrappers.lambdaQuery(SysUserTenant.class).eq(SysUserTenant::getUserId, userTenantBO.getUserId()));
        if(CollUtil.isNotEmpty(tenantIds)){
            List<SysUserTenant> list = tenantIds.stream().map(tenantId -> SysUserTenant.builder().userId(userTenantBO.getUserId()).tenantId(tenantId).build()).toList();
            this.saveBatch(list);
        }
    }

    @Override
    public Page<SysUserTenantVO> getUserTenantList(Long userId, int type, PageQuery pageQuery) {
        List<Long> deptIdList = sysDeptMapper.selectList().stream().map(SysDept::getDeptId).toList();
        // 获取当前登录用户所属租户创建的指定类型租户
        Page<SysTenant> tenantPage = sysTenantMapper.selectByTenantTypeAndCreateDept(pageQuery.build(), type, deptIdList);
        // 转换为SysUserTenantVO分页数据
        List<SysTenant> records = tenantPage.getRecords();
        List<String> tenantIds = records.stream().map(SysTenant::getTenantId).toList();
        // 获取指定用户关联的租户
        Map<String, SysUserTenant> userTenantMap = baseMapper.selectList(new LambdaQueryWrapper<SysUserTenant>()
            .eq(SysUserTenant::getUserId, userId)
            .in(SysUserTenant::getTenantId, tenantIds)
        ).stream().collect(Collectors.toMap(SysUserTenant::getTenantId, o -> o));
        List<SysUserTenantVO> userTenantVOList = records.stream()
            .map(sysTenant -> SysUserTenantVO.builder()
                .tenantId(sysTenant.getTenantId())
                .tenantName(sysTenant.getStoreName())
                .has((LoginHelper.isTenantAdmin() && userId.equals(LoginHelper.getUserId())) || userTenantMap.containsKey(sysTenant.getTenantId()))
                .build())
            .toList();
        // 构建新的分页结果
        Page<SysUserTenantVO> resultPage = new Page<>(tenantPage.getCurrent(), tenantPage.getSize(), tenantPage.getTotal());
        resultPage.setRecords(userTenantVOList);
        return resultPage;
    }
}
