package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sample.common.util.SecurityUtils; // 修正导入包
import com.dji.sample.manage.dao.IUserOrgMapper;
import com.dji.sample.manage.model.dto.UserOrgDTO;
import com.dji.sample.manage.model.entity.UserOrgEntity;
import com.dji.sample.manage.service.IOrgService;
import com.dji.sample.manage.service.IUserOrgService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

import static com.dji.sample.common.util.SecurityUtils.getWorkspaceId;

@Service
public class UserOrgServiceImpl extends ServiceImpl<IUserOrgMapper, UserOrgEntity> implements IUserOrgService {

    @Autowired
    private IUserOrgMapper userOrgMapper;

    @Autowired
    private IOrgService orgService;

    @Override
    public Optional<UserOrgEntity> getUserOrg(String userId, String orgId) {
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrgEntity::getUserId, userId)
                .eq(UserOrgEntity::getOrgId, orgId)
                .eq(UserOrgEntity::getStatus, 1);

        UserOrgEntity entity = getOne(queryWrapper);
        return Optional.ofNullable(entity);
    }

    @Override
    public List<UserOrgDTO> getUserOrgs(String userId) {
        return userOrgMapper.selectUserOrgs(userId);
    }

    @Override
    public List<String> getUserIdsByOrgId(String orgId) {
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrgEntity::getOrgId, orgId)
                .eq(UserOrgEntity::getStatus, 1)
                .select(UserOrgEntity::getUserId);

        return this.list(queryWrapper)
                .stream()
                .map(UserOrgEntity::getUserId)
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, Integer> getUserRoleMapByOrgId(String orgId) {
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrgEntity::getOrgId, orgId)
                .eq(UserOrgEntity::getStatus, 1)
                .select(UserOrgEntity::getUserId, UserOrgEntity::getRoleType);

        return this.list(queryWrapper)
                .stream()
                .collect(Collectors.toMap(
                        UserOrgEntity::getUserId,
                        UserOrgEntity::getRoleType
                ));
    }

    @Override
    public boolean addUserToOrg(String userId, String orgId, Integer roleType) {
        // 检查是否已存在
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrgEntity::getUserId, userId)
                .eq(UserOrgEntity::getOrgId, orgId);

        UserOrgEntity entity = getOne(queryWrapper);
        if (entity != null) {
            // 如果已存在但被禁用，则启用
            if (entity.getStatus() == 0) {
                entity.setStatus(1);
                entity.setRoleType(roleType);
                // entity.setUpdateTime(System.currentTimeMillis());
                return updateById(entity);
            }
            // return false; // 已存在且启用状态
            throw new RuntimeException("user had join the org!");
        }

        // 创建新关联
        String workspaceId = orgService.getWorkspaceIdByOrgId(orgId);
        if (!StringUtils.hasText(workspaceId)) {
            workspaceId = getWorkspaceId();
        }
        if (!StringUtils.hasText(workspaceId)) {
            throw new RuntimeException("workspaceId is null");
        }

        UserOrgEntity userOrg = new UserOrgEntity();
        userOrg.setUserId(userId);
        userOrg.setWorkspaceId(workspaceId);
        userOrg.setOrgId(orgId);
        userOrg.setRoleType(roleType);
        userOrg.setStatus(1);
        userOrg.setCreateTime(System.currentTimeMillis());
        userOrg.setUpdateTime(System.currentTimeMillis());

        // 创建新关联时设置创建者和更新者信息
        String currentUserId = SecurityUtils.getUserId();
        String currentUserName = SecurityUtils.getUsername();

        userOrg.setCreatorId(currentUserId);
        userOrg.setCreatorName(currentUserName);
        userOrg.setUpdaterId(currentUserId);
        userOrg.setUpdaterName(currentUserName);

        return save(userOrg);
    }

    @Override
    public boolean removeUserFromOrg(String userId, String orgId) {
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrgEntity::getUserId, userId)
                .eq(UserOrgEntity::getOrgId, orgId);

        // 使用逻辑删除（将状态设置为禁用）
        UserOrgEntity entity = getOne(queryWrapper);
        if (entity != null) {
            entity.setStatus(0);
            // entity.setUpdateTime(System.currentTimeMillis());
            return updateById(entity);
        }
        return false;
    }

    @Override
    public boolean updateUserOrgRole(String userId, String orgId, Integer roleType) {
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrgEntity::getUserId, userId)
                .eq(UserOrgEntity::getOrgId, orgId);

        UserOrgEntity entity = getOne(queryWrapper);
        if (entity != null) {
            entity.setRoleType(roleType);
            // entity.setUpdateTime(System.currentTimeMillis());

            // 设置更新者信息
            entity.setUpdaterId(SecurityUtils.getUserId());
            entity.setUpdaterName(SecurityUtils.getUsername());

            return updateById(entity);
        }
        return false;
    }
}
