package com.haha.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.enums.CommonStatus;
import com.haha.common.vo.Result;
import com.haha.entity.DataPermission;
import com.haha.mapper.DataPermissionMapper;
import com.haha.service.DataPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据权限服务实现类
 */
@Slf4j
@Service
public class DataPermissionServiceImpl extends ServiceImpl<DataPermissionMapper, DataPermission> implements DataPermissionService {

    @Autowired
    private DataPermissionMapper dataPermissionMapper;

    @Override
    public Result<List<DataPermission>> getAllPermissions() {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectAllEnabled();
            return Result.success("查询成功", permissions);
        } catch (Exception e) {
            log.error("查询所有权限失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, List<DataPermission>>> getPermissionsGroupByModule() {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectAllGroupByModule();
            
            Map<String, List<DataPermission>> groupedPermissions = new LinkedHashMap<>();
            for (DataPermission permission : permissions) {
                String moduleName = permission.getModuleName();
                if (!groupedPermissions.containsKey(moduleName)) {
                    groupedPermissions.put(moduleName, new ArrayList<>());
                }
                groupedPermissions.get(moduleName).add(permission);
            }
            
            return Result.success("查询成功", groupedPermissions);
        } catch (Exception e) {
            log.error("查询分组权限失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Map<String, Object>>> getPermissionsTree() {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectAllGroupByModule();
            
            Map<String, Map<String, Object>> moduleMap = new LinkedHashMap<>();
            long moduleId = -1;
            
            for (DataPermission permission : permissions) {
                String moduleCode = permission.getModuleCode();
                String moduleName = permission.getModuleName();
                
                if (!moduleMap.containsKey(moduleCode)) {
                    moduleId--;
                    Map<String, Object> moduleNode = new LinkedHashMap<>();
                    moduleNode.put("id", moduleId);
                    moduleNode.put("name", moduleName);
                    moduleNode.put("children", new ArrayList<Map<String, Object>>());
                    moduleMap.put(moduleCode, moduleNode);
                }
                
                Map<String, Object> permissionNode = new LinkedHashMap<>();
                permissionNode.put("id", permission.getId());
                permissionNode.put("name", permission.getPermissionName());
                permissionNode.put("permissionCode", permission.getPermissionCode());
                permissionNode.put("operationType", permission.getOperationType());
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> children = (List<Map<String, Object>>) moduleMap.get(moduleCode).get("children");
                children.add(permissionNode);
            }
            
            List<Map<String, Object>> tree = new ArrayList<>(moduleMap.values());
            return Result.success("查询成功", tree);
        } catch (Exception e) {
            log.error("查询权限树失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<DataPermission>> getPermissionsByModule(String moduleCode) {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectByModuleCode(moduleCode);
            return Result.success("查询成功", permissions);
        } catch (Exception e) {
            log.error("查询模块权限失败, moduleCode={}", moduleCode, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<DataPermission>> getPermissionsByRoleId(Long roleId) {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectByRoleId(roleId);
            return Result.success("查询成功", permissions);
        } catch (Exception e) {
            log.error("查询角色权限失败, roleId={}", roleId, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<String>> getPermissionCodesByRoleId(Long roleId) {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectByRoleId(roleId);
            List<String> codes = new ArrayList<>();
            for (DataPermission permission : permissions) {
                codes.add(permission.getPermissionCode());
            }
            return Result.success("查询成功", codes);
        } catch (Exception e) {
            log.error("查询角色权限编码失败, roleId={}", roleId, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> getPermissionCodesByRoleIds(List<Long> roleIds) {
        if (roleIds == null || roleIds.isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return dataPermissionMapper.selectPermissionCodesByRoleIds(roleIds);
        } catch (Exception e) {
            log.error("查询角色权限编码失败, roleIds={}", roleIds, e);
            return new ArrayList<>();
        }
    }

    @Override
    public boolean existsByPermissionCode(String permissionCode) {
        DataPermission permission = dataPermissionMapper.selectByPermissionCode(permissionCode);
        return permission != null && permission.getStatus() == CommonStatus.ENABLED.getCode();
    }

    @Override
    public Result<Void> createPermission(DataPermission permission) {
        try {
            // 检查权限编码是否已存在
            DataPermission exist = dataPermissionMapper.selectByPermissionCode(permission.getPermissionCode());
            if (exist != null) {
                return Result.error(400, "权限编码已存在");
            }

            permission.setCreateTime(LocalDateTime.now());
            permission.setUpdateTime(LocalDateTime.now());
            if (permission.getStatus() == null) {
                permission.setStatus(CommonStatus.ENABLED.getCode());
            }

            boolean success = this.save(permission);
            return success ? Result.success("创建成功", null) : Result.error(500, "创建失败");
        } catch (Exception e) {
            log.error("创建权限失败", e);
            return Result.error(500, "创建失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> updatePermission(DataPermission permission) {
        try {
            DataPermission exist = this.getById(permission.getId());
            if (exist == null) {
                return Result.error(404, "权限不存在");
            }

            // 如果修改了编码，检查是否重复
            if (!exist.getPermissionCode().equals(permission.getPermissionCode())) {
                DataPermission check = dataPermissionMapper.selectByPermissionCode(permission.getPermissionCode());
                if (check != null) {
                    return Result.error(400, "权限编码已存在");
                }
            }

            permission.setUpdateTime(LocalDateTime.now());
            boolean success = this.updateById(permission);
            return success ? Result.success("更新成功", null) : Result.error(500, "更新失败");
        } catch (Exception e) {
            log.error("更新权限失败", e);
            return Result.error(500, "更新失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> deletePermission(Long id) {
        try {
            DataPermission exist = this.getById(id);
            if (exist == null) {
                return Result.error(404, "权限不存在");
            }

            boolean success = this.removeById(id);
            return success ? Result.success("删除成功", null) : Result.error(500, "删除失败");
        } catch (Exception e) {
            log.error("删除权限失败, id={}", id, e);
            return Result.error(500, "删除失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> togglePermissionStatus(Long id, Integer status) {
        try {
            DataPermission exist = this.getById(id);
            if (exist == null) {
                return Result.error(404, "权限不存在");
            }

            if (status != CommonStatus.DISABLED.getCode() && status != CommonStatus.ENABLED.getCode()) {
                return Result.error(400, "状态值无效");
            }

            exist.setStatus(status);
            exist.setUpdateTime(LocalDateTime.now());
            boolean success = this.updateById(exist);
            return success ? Result.success("状态更新成功", null) : Result.error(500, "状态更新失败");
        } catch (Exception e) {
            log.error("切换权限状态失败, id={}", id, e);
            return Result.error(500, "状态更新失败: " + e.getMessage());
        }
    }
}
