package com.haha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.vo.Result;
import com.haha.entity.Role;
import com.haha.entity.RolePermission;
import com.haha.mapper.RoleMapper;
import com.haha.mapper.RolePermissionMapper;
import com.haha.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 角色服务实现类
 */
@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public Result<IPage<Role>> getRoleList(int page, int pageSize, String name, String code) {
        try {
            LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
            
            // 条件查询
            if (StringUtils.hasText(name)) {
                wrapper.like(Role::getName, name);
            }
            if (StringUtils.hasText(code)) {
                wrapper.eq(Role::getCode, code);
            }
            
            // 按创建时间倒序
            wrapper.orderByDesc(Role::getCreateTime);
            
            // 分页查询
            Page<Role> pageObj = new Page<>(page, pageSize);
            IPage<Role> result = this.page(pageObj, wrapper);
            
            // 为每个角色添加用户数量
            result.getRecords().forEach(role -> {
                int userCount = baseMapper.countUsersByRoleId(role.getId());
                // 临时方案：将用户数量存储在description字段中，前端会单独获取
            });
            
            return Result.success("查询成功", result);
            
        } catch (Exception e) {
            log.error("查询角色列表失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<List<Role>> getAllRoles() {
        try {
            List<Role> roles = this.list(new LambdaQueryWrapper<Role>().orderByAsc(Role::getId));
            return Result.success("查询成功", roles);
        } catch (Exception e) {
            log.error("获取所有角色失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Void> addRole(Role role) {
        try {
            // 检查角色编码是否已存在
            Role existRole = baseMapper.selectByCode(role.getCode());
            if (existRole != null) {
                return Result.error(400, "角色编码已存在");
            }
            
            // 设置创建时间
            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());
            
            boolean success = this.save(role);
            return success ? Result.success("添加成功", null) : Result.error(500, "添加失败");
            
        } catch (Exception e) {
            log.error("添加角色失败", e);
            return Result.error(500, "添加失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Void> updateRole(Role role) {
        try {
            // 检查角色是否存在
            Role existRole = this.getById(role.getId());
            if (existRole == null) {
                return Result.error(404, "角色不存在");
            }
            
            // 如果修改了编码，检查是否重复
            if (!existRole.getCode().equals(role.getCode())) {
                Role checkRole = baseMapper.selectByCode(role.getCode());
                if (checkRole != null) {
                    return Result.error(400, "角色编码已存在");
                }
            }
            
            role.setUpdateTime(LocalDateTime.now());
            boolean success = this.updateById(role);
            return success ? Result.success("更新成功", null) : Result.error(500, "更新失败");
            
        } catch (Exception e) {
            log.error("更新角色失败", e);
            return Result.error(500, "更新失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Void> deleteRole(Long id) {
        try {
            // 检查角色是否存在
            Role role = this.getById(id);
            if (role == null) {
                return Result.error(404, "角色不存在");
            }
            
            // 检查是否有用户正在使用此角色
            int userCount = baseMapper.countUsersByRoleId(id);
            if (userCount > 0) {
                return Result.error(400, "该角色下还有" + userCount + "个用户，无法删除");
            }
            
            boolean success = this.removeById(id);
            return success ? Result.success("删除成功", null) : Result.error(500, "删除失败");
            
        } catch (Exception e) {
            log.error("删除角色失败", e);
            return Result.error(500, "删除失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Long>> getRolePermissionIds(Long roleId) {
        try {
            // 检查角色是否存在
            Role role = this.getById(roleId);
            if (role == null) {
                return Result.error(404, "角色不存在");
            }
            
            List<Long> permissionIds = rolePermissionMapper.selectPermissionIdsByRoleId(roleId);
            return Result.success("查询成功", permissionIds);
            
        } catch (Exception e) {
            log.error("获取角色权限失败, roleId={}", roleId, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateRolePermissions(Long roleId, List<Long> permissionIds) {
        try {
            // 检查角色是否存在
            Role role = this.getById(roleId);
            if (role == null) {
                return Result.error(404, "角色不存在");
            }
            
            // 先删除该角色的所有权限
            rolePermissionMapper.deleteByRoleId(roleId);
            
            // 如果有新权限，批量插入
            if (permissionIds != null && !permissionIds.isEmpty()) {
                for (Long permissionId : permissionIds) {
                    RolePermission rp = new RolePermission();
                    rp.setRoleId(roleId);
                    rp.setPermissionId(permissionId);
                    rp.setCreateTime(LocalDateTime.now());
                    rolePermissionMapper.insert(rp);
                }
            }
            
            return Result.success("权限配置成功", null);
            
        } catch (Exception e) {
            log.error("更新角色权限失败, roleId={}", roleId, e);
            return Result.error(500, "权限配置失败: " + e.getMessage());
        }
    }
}
