package shop.alien.storeplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StorePlatformRole;
import shop.alien.entity.store.vo.RolePermissionTableVo;
import shop.alien.entity.store.vo.StorePlatformRoleVo;
import shop.alien.storeplatform.annotation.PlatformOperationLog;
import shop.alien.storeplatform.dto.CreateRoleDto;
import shop.alien.storeplatform.dto.UpdateRoleDto;
import shop.alien.storeplatform.service.StorePlatformRoleMenuService;
import shop.alien.storeplatform.service.StorePlatformRoleService;

import java.util.List;

/**
 * 平台角色信息表 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"平台-角色管理"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/platform/role")
@RequiredArgsConstructor
public class StorePlatformRoleController {

    private final StorePlatformRoleService storePlatformRoleService;
    private final StorePlatformRoleMenuService storePlatformRoleMenuService;

    @ApiOperation("分页查询角色列表（包含关联统计）")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "页容", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "roleName", value = "角色名称（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "角色描述（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "角色状态（0正常 1停用）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getRolePage")
    public R<IPage<StorePlatformRoleVo>> getRolePage(
            @RequestParam(name = "page", defaultValue = "1") int page,
            @RequestParam(name = "size", defaultValue = "10") int size,
            @RequestParam(value = "storeId", required = true) Integer storeId,
            @RequestParam(value = "roleName", required = false) String roleName,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "status", required = false) String status) {
        log.info("StorePlatformRoleController.getRolePage?page={}, size={}, storeId={}, roleName={}, description={}, status={}", 
                page, size, storeId, roleName, description, status);
        IPage<StorePlatformRoleVo> rolePage = storePlatformRoleService.getRolePageWithStats(page, size, storeId, roleName, description, status);
        return R.data(rolePage);
    }

    @ApiOperation("根据ID查询角色详情")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", dataType = "Long", paramType = "query", required = true)
    })
    @GetMapping("/getRoleById")
    public R<StorePlatformRole> getRoleById(@RequestParam("roleId") Long roleId) {
        log.info("StorePlatformRoleController.getRoleById?roleId={}", roleId);
        StorePlatformRole role = storePlatformRoleService.getRoleById(roleId);
        if (role == null) {
            return R.fail("未找到该角色信息");
        }
        return R.data(role);
    }

    @ApiOperation("新增角色")
    @ApiOperationSupport(order = 3)
    @PlatformOperationLog(
            module = "角色操作记录",
            type = "新增角色",
            content = "新增角色 #{#p0.roleName}（店铺ID=#{#p0.storeId}）"
    )
    @PostMapping("/saveRole")
    public R<String> saveRole(@RequestBody StorePlatformRole role) {
        log.info("StorePlatformRoleController.saveRole?role={}", role);
        // 检查角色名称是否已存在（同一店铺内不能重复）
        if (storePlatformRoleService.checkRoleNameExists(role.getStoreId(), role.getRoleName(), null)) {
            return R.fail("已有名称不允许重复添加");
        }
        boolean result = storePlatformRoleService.saveRole(role);
        if (result) {
            return R.success("新增成功");
        }
        return R.fail("新增失败");
    }

    @ApiOperation("创建角色（包含权限分配）")
    @ApiOperationSupport(order = 3)
    @PlatformOperationLog(
            module = "角色操作记录",
            type = "新增角色",
            content = "新增角色 #{#p0.roleName}（店铺ID=#{#p0.storeId}，权限数=#{#p0.menuIds != null ? #p0.menuIds.size() : 0}）"
    )
    @PostMapping("/createRole")
    public R<String> createRole(@RequestBody CreateRoleDto createRoleDto) {
        log.info("StorePlatformRoleController.createRole?storeId={}, roleName={}, menuIds={}", 
                createRoleDto.getStoreId(), createRoleDto.getRoleName(), createRoleDto.getMenuIds());
        
        // 检查角色名称是否已存在（同一店铺内不能重复）
        if (storePlatformRoleService.checkRoleNameExists(createRoleDto.getStoreId(), createRoleDto.getRoleName(), null)) {
            return R.fail("已有名称不允许重复添加");
        }
        
        // 构建角色对象
        StorePlatformRole role = new StorePlatformRole();
        role.setStoreId(createRoleDto.getStoreId());
        role.setRoleName(createRoleDto.getRoleName());
        role.setRoleSort(createRoleDto.getRoleSort());
        role.setStatus(createRoleDto.getStatus());
        role.setDescription(createRoleDto.getDescription());
        role.setRoleNameEn(createRoleDto.getRoleNameEn());
        role.setRemark(createRoleDto.getRemark());
        
        // 创建角色并分配权限
        boolean result = storePlatformRoleService.createRoleWithMenus(role, createRoleDto.getMenuIds());
        if (result) {
            return R.success("创建成功");
        }
        return R.fail("创建失败");
    }

    @ApiOperation("修改角色")
    @ApiOperationSupport(order = 4)
    @PlatformOperationLog(
            module = "角色操作记录",
            type = "修改角色",
            content = "修改角色ID=#{#p0.roleId}，名称=#{#p0.roleName}（店铺ID=#{#p0.storeId}）"
    )
    @PostMapping("/updateRole")
    public R<String> updateRole(@RequestBody UpdateRoleDto updateRoleDto) {
        log.info("StorePlatformRoleController.updateRole?roleId={}, roleName={}, menuIds={}", 
                updateRoleDto.getRoleId(), updateRoleDto.getRoleName(), updateRoleDto.getMenuIds());
        
        // 校验必填参数
        if (updateRoleDto.getRoleId() == null) {
            return R.fail("角色ID不能为空");
        }
        if (updateRoleDto.getStoreId() == null) {
            return R.fail("店铺ID不能为空");
        }
        
        // 构建角色对象
        StorePlatformRole role = new StorePlatformRole();
        role.setRoleId(updateRoleDto.getRoleId());
        role.setStoreId(updateRoleDto.getStoreId());
        role.setRoleName(updateRoleDto.getRoleName());
        role.setRoleSort(updateRoleDto.getRoleSort());
        role.setStatus(updateRoleDto.getStatus());
        role.setDescription(updateRoleDto.getDescription());
        role.setRoleNameEn(updateRoleDto.getRoleNameEn());
        role.setRemark(updateRoleDto.getRemark());
        
        // 更新角色和权限
        boolean result = storePlatformRoleService.updateRoleWithMenus(role, updateRoleDto.getMenuIds());
        if (result) {
            return R.success("修改成功");
        }
        return R.fail("修改失败");
    }

    @ApiOperation("删除角色")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", dataType = "Long", paramType = "query", required = true)
    })
    @PlatformOperationLog(
            module = "角色操作记录",
            type = "删除角色",
            content = "删除角色ID=#{#roleId}"
    )
    @DeleteMapping("/deleteRole")
    public R<String> deleteRole(@RequestParam("roleId") Long roleId) {
        log.info("StorePlatformRoleController.deleteRole?roleId={}", roleId);
        boolean result = storePlatformRoleService.deleteRole(roleId);
        if (result) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @ApiOperation("逻辑删除角色")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", dataType = "Long", paramType = "query", required = true)
    })
    @PlatformOperationLog(
            module = "角色操作记录",
            type = "删除角色",
            content = "删除角色ID=#{#roleId}"
    )
    @DeleteMapping("/deleteRoleWithCheck")
    public R<String> deleteRoleWithCheck(@RequestParam("roleId") Long roleId) {
        log.info("StorePlatformRoleController.deleteRoleWithCheck?roleId={}", roleId);
        String errorMsg = storePlatformRoleService.deleteRoleWithCheck(roleId);
        if (errorMsg == null) {
            return R.success("删除成功");
        }
        return R.fail(errorMsg);
    }

    @ApiOperation("查询所有正常状态的角色列表")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = false)
    })
    @GetMapping("/getAllNormalRoles")
    public R<List<StorePlatformRole>> getAllNormalRoles(
            @RequestParam(value = "storeId", required = false) Integer storeId) {
        log.info("StorePlatformRoleController.getAllNormalRoles?storeId={}", storeId);
        List<StorePlatformRole> roles = storePlatformRoleService.getAllNormalRoles(storeId);
        return R.data(roles);
    }

    @ApiOperation("检查角色名称是否已存在")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "roleName", value = "角色名称", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "excludeRoleId", value = "排除的角色ID（用于更新时排除自己）", dataType = "Long", paramType = "query", required = false)
    })
    @GetMapping("/checkRoleNameExists")
    public R<Boolean> checkRoleNameExists(
            @RequestParam(value = "storeId", required = false) Integer storeId,
            @RequestParam("roleName") String roleName,
            @RequestParam(value = "excludeRoleId", required = false) Long excludeRoleId) {
        log.info("StorePlatformRoleController.checkRoleNameExists?storeId={}, roleName={}, excludeRoleId={}", storeId, roleName, excludeRoleId);
        boolean exists = storePlatformRoleService.checkRoleNameExists(storeId, roleName, excludeRoleId);
        return R.data(exists);
    }

    @ApiOperation("查看角色权限（表格形式）")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", dataType = "Long", paramType = "query", required = true)
    })
    @GetMapping("/getRolePermissionTable")
    public R<List<RolePermissionTableVo>> getRolePermissionTable(@RequestParam("roleId") Long roleId) {
        log.info("StorePlatformRoleController.getRolePermissionTable?roleId={}", roleId);
        List<RolePermissionTableVo> tableData = storePlatformRoleMenuService.getRolePermissionTable(roleId);
        return R.data(tableData);
    }
}

