package com.ycwl.basic.controller.pc;

import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.model.pc.permission.entity.PermissionEntity;
import com.ycwl.basic.model.pc.permission.req.PermissionSaveReq;
import com.ycwl.basic.model.pc.permission.resp.PermissionResp;
import com.ycwl.basic.service.pc.PermissionService;
import com.ycwl.basic.utils.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;

import java.util.ArrayList;
import java.util.Arrays;

@RestController
@RequestMapping("/api/permission/v1")
@Api(tags = "权限管理接口")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/get/")
    public ApiResponse<PermissionResp> getPermissionByUser() {
        String userId = BaseContextHandler.getUserId();
        PermissionEntity permission = permissionService.getPermissionByUserId(Long.parseLong(userId));
        if (permission == null || StringUtils.isEmpty(permission.getPermString())) {
            return ApiResponse.success(new PermissionResp(new ArrayList<>()));
        }
        return ApiResponse.success(new PermissionResp(Arrays.asList(StringUtils.split(permission.getPermString(), ","))));
    }

    @ApiOperation("根据用户ID查询权限信息")
    @GetMapping("/get/{userId}")
    public ApiResponse<PermissionResp> getPermissionByUser(@PathVariable Long userId) {
        PermissionEntity permission = permissionService.getPermissionByUserId(userId);
        if (permission == null || StringUtils.isEmpty(permission.getPermString())) {
            return ApiResponse.success(new PermissionResp(new ArrayList<>()));
        }
        return ApiResponse.success(new PermissionResp(Arrays.asList(StringUtils.split(permission.getPermString(), ","))));
    }

    @ApiOperation("保存或更新权限信息")
    @PostMapping("/save/{userId}")
    public ApiResponse saveOrUpdate(@PathVariable Long userId, @RequestBody PermissionSaveReq req) {
        permissionService.saveOrUpdate(userId, StringUtils.join(req.getPermissions(), ","));
        return ApiResponse.success(true);
    }
}