package top.continew.admin.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.continew.admin.business.mapper.DeptPlatformMapper;
import top.continew.admin.business.model.entity.DeptPlatformDO;
import top.continew.admin.business.model.req.DeptPlatformReq;
import top.continew.admin.business.service.DeptPlatformService;
import top.continew.admin.common.model.dto.LoginUser;
import top.continew.admin.common.util.helper.LoginHelper;
import top.continew.starter.extension.crud.model.entity.BaseIdDO;

import java.util.Collections;
import java.util.List;

/**
 * 部门与平台绑表业务实现
 *
 * @author 张波
 * @since 2024/10/20 14:49
 */
@Service
public class DeptPlatformServiceImpl extends ServiceImpl<DeptPlatformMapper, DeptPlatformDO> implements DeptPlatformService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bind(DeptPlatformReq req) {
        // 查询现有绑定关系
        List<DeptPlatformDO> list = lambdaQuery().eq(DeptPlatformDO::getDeptId, req.getDeptId()).list();

        // 筛选出数据库中存在 新绑定不存在的 进行删除
        List<Long> removeIds = list.stream()
            .filter(d -> !req.getPlatforms().contains(d.getPlatform()))
            .map(BaseIdDO::getId)
            .toList();
        if (CollUtil.isNotEmpty(removeIds)) {
            removeBatchByIds(removeIds);
        }

        if (CollUtil.isNotEmpty(req.getPlatforms())) {
            // 筛选出新列表存在 数据库中不存在的 进行新增
            List<DeptPlatformDO> saveList = req.getPlatforms()
                .stream()
                .filter(p -> list.stream().noneMatch(d -> p.equals(d.getPlatform())))
                .map(i -> {
                    DeptPlatformDO temp = new DeptPlatformDO();
                    temp.setDeptId(req.getDeptId());
                    temp.setPlatform(i);
                    return temp;
                })
                .toList();
            saveBatch(saveList);
        }
    }

    @Override
    public List<String> getPlatforms() {
        // 获取当前登录用户信息
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long deptId = loginUser.getDeptId();

        // 如果不存在部门ID，则返回空
        if (deptId == null) {
            return Collections.emptyList();
        }

        // 根据登录用户所在部门查询可见操作平台
        return lambdaQuery().eq(DeptPlatformDO::getDeptId, deptId)
            .list()
            .stream()
            .map(DeptPlatformDO::getPlatform)
            .toList();
    }

    @Override
    public List<String> getPlatformByDept(Long deptId) {
        return lambdaQuery().eq(DeptPlatformDO::getDeptId, deptId)
            .list()
            .stream()
            .map(DeptPlatformDO::getPlatform)
            .toList();
    }
}
