package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.dto.permission.CreatePermissionDTO;
import com.lesingle.creation.dto.permission.UpdatePermissionDTO;
import com.lesingle.creation.entity.Permission;
import com.lesingle.creation.mapper.PermissionMapper;
import com.lesingle.creation.service.PermissionService;
import com.lesingle.creation.vo.permission.PermissionDetailVO;
import com.lesingle.creation.vo.permission.PermissionListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

/**
 * 权限服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private final PermissionMapper permissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PermissionDetailVO create(CreatePermissionDTO dto, Long tenantId, Long operatorId) {
        log.info("开始创建权限，权限编码：{}", dto.getCode());

        // 检查权限编码是否已存在
        Permission existingPermission = permissionMapper.selectByCode(tenantId, dto.getCode());
        if (existingPermission != null) {
            throw new BusinessException("权限编码已存在");
        }

        // 检查资源 + 操作组合是否已存在
        Permission existingResource = permissionMapper.selectByResourceAction(tenantId, dto.getResource(), dto.getAction());
        if (existingResource != null) {
            throw new BusinessException("该资源的操作类型已存在");
        }

        // 创建权限
        Permission permission = new Permission();
        permission.setTenantId(tenantId);
        permission.setName(dto.getName());
        permission.setCode(dto.getCode());
        permission.setResource(dto.getResource());
        permission.setAction(dto.getAction());
        permission.setDescription(dto.getDescription());
        permission.setValidState(1);
        permission.setCreateBy(String.valueOf(operatorId));

        permissionMapper.insert(permission);
        log.info("权限创建成功，权限 ID: {}", permission.getId());

        return convertToDetailVO(permission);
    }

    @Override
    public Page<PermissionListVO> pageList(Long tenantId, int page, int pageSize) {
        log.info("分页查询权限列表，租户 ID: {}, 页码：{}, 每页大小：{}", tenantId, page, pageSize);

        Page<Permission> permissionPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getTenantId, tenantId)
                .eq(Permission::getValidState, 1)
                .orderByAsc(Permission::getResource, Permission::getAction);

        Page<Permission> resultPage = permissionMapper.selectPage(permissionPage, wrapper);

        // 转换为 VO
        List<PermissionListVO> voList = resultPage.getRecords().stream()
                .map(this::convertToListVO)
                .collect(Collectors.toList());

        Page<PermissionListVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public PermissionDetailVO detail(Long id) {
        log.info("查询权限详情，权限 ID: {}", id);

        Permission permission = permissionMapper.selectById(id);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }

        return convertToDetailVO(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PermissionDetailVO update(Long id, UpdatePermissionDTO dto, Long tenantId) {
        log.info("更新权限，权限 ID: {}", id);

        Permission existingPermission = permissionMapper.selectById(id);
        if (existingPermission == null) {
            throw new BusinessException("权限不存在");
        }

        // 如果更新了 code，检查是否冲突
        if (StringUtils.hasText(dto.getCode())) {
            Permission conflictPermission = permissionMapper.selectByCodeExclude(tenantId, dto.getCode(), id);
            if (conflictPermission != null) {
                throw new BusinessException("权限编码已存在");
            }
        }

        // 如果更新了资源 + 操作，检查是否冲突
        if (StringUtils.hasText(dto.getResource()) && StringUtils.hasText(dto.getAction())) {
            Permission conflictResource = permissionMapper.selectByResourceActionExclude(tenantId, dto.getResource(), dto.getAction(), id);
            if (conflictResource != null) {
                throw new BusinessException("该资源的操作类型已存在");
            }
        }

        // 更新权限信息
        Permission permission = new Permission();
        permission.setId(id);
        permission.setName(dto.getName());
        permission.setCode(dto.getCode());
        permission.setResource(dto.getResource());
        permission.setAction(dto.getAction());
        permission.setDescription(dto.getDescription());

        permissionMapper.updateById(permission);
        log.info("权限更新成功，权限 ID: {}", id);

        return convertToDetailVO(permissionMapper.selectById(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        log.info("删除权限，权限 ID: {}", id);

        Permission permission = permissionMapper.selectById(id);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }

        // 删除权限（逻辑删除）
        permissionMapper.deleteById(id);
        log.info("权限删除成功，权限 ID: {}", id);
    }

    @Override
    public List<PermissionListVO> list(Long tenantId) {
        log.info("查询权限列表，租户 ID: {}", tenantId);

        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getTenantId, tenantId)
                .eq(Permission::getValidState, 1)
                .orderByAsc(Permission::getResource, Permission::getAction);

        List<Permission> permissions = permissionMapper.selectList(wrapper);

        return permissions.stream()
                .map(this::convertToListVO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为详情 VO
     */
    private PermissionDetailVO convertToDetailVO(Permission permission) {
        PermissionDetailVO vo = new PermissionDetailVO();
        vo.setId(permission.getId());
        vo.setTenantId(permission.getTenantId());
        vo.setName(permission.getName());
        vo.setCode(permission.getCode());
        vo.setResource(permission.getResource());
        vo.setAction(permission.getAction());
        vo.setDescription(permission.getDescription());
        vo.setValidState(permission.getValidState());
        vo.setCreateBy(permission.getCreateBy());
        vo.setCreateTime(permission.getCreateTime());
        vo.setUpdateBy(permission.getUpdateBy());
        vo.setUpdateTime(permission.getUpdateTime());
        return vo;
    }

    /**
     * 转换为列表 VO
     */
    private PermissionListVO convertToListVO(Permission permission) {
        PermissionListVO vo = new PermissionListVO();
        vo.setId(permission.getId());
        vo.setTenantId(permission.getTenantId());
        vo.setName(permission.getName());
        vo.setCode(permission.getCode());
        vo.setResource(permission.getResource());
        vo.setAction(permission.getAction());
        vo.setDescription(permission.getDescription());
        vo.setValidState(permission.getValidState());
        vo.setCreateTime(permission.getCreateTime());
        return vo;
    }
}
