package com.xjrsoft.module.magicapi.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.module.magicapi.dto.InterfaceAuthDto;
import com.xjrsoft.module.magicapi.entity.InterfaceAuth;
import com.xjrsoft.module.magicapi.service.IInterfaceAuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * 接口权限表 前端控制器
 * </p>
 *
 * @author zlf
 * @since 2022-11-03
 */
@RestController
@RequestMapping(GlobalConstant.MAGICAPI_MODULE_PREFIX + "/auth")
@Api(value = GlobalConstant.MAGICAPI_MODULE_PREFIX + "/auth", tags = "接口权限模块接口")
@AllArgsConstructor
public class InterfaceAuthController {

    private final IInterfaceAuthService authService;

    @GetMapping(value = "/role")
    @ApiOperation("查询角色所授权的接口id集合")
    public R role(@RequestParam Long roleId) {
        List<InterfaceAuth> authList = authService.list(Wrappers.<InterfaceAuth>query().lambda()
                .eq(InterfaceAuth::getRoleId, roleId));
        List<String> resultIdList = null;
        if (CollectionUtil.isNotEmpty(authList)) {
            resultIdList = authList.stream().map(InterfaceAuth::getInterfaceId).collect(Collectors.toList());
        }
        return R.ok(resultIdList);
    }

    @PostMapping
    @ApiOperation("角色接口授权")
    public R authorize(@RequestBody InterfaceAuthDto dto) {
        // 删除原有的接口权限
        authService.remove(Wrappers.<InterfaceAuth>query().lambda().eq(InterfaceAuth::getRoleId, dto.getRoleId()));
        if (CollectionUtil.isNotEmpty(dto.getInterfaceIds())) {
            List<InterfaceAuth> savedList = new ArrayList<>();
            for (String interfaceId : dto.getInterfaceIds()) {
                InterfaceAuth auth = new InterfaceAuth();
                auth.setRoleId(dto.getRoleId());
                auth.setInterfaceId(interfaceId);
                savedList.add(auth);
            }
            authService.saveBatch(savedList);
        }
        return R.ok();
    }
}
