package com.changhu.module.superManagement.controller;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Dict;
import com.changhu.common.annotation.CheckUserType;
import com.changhu.common.annotation.JsonBody;
import com.changhu.common.db.enums.UserType;
import com.changhu.common.pojo.vo.SelectNodeVo;
import com.changhu.controller.OpenController;
import com.changhu.module.superManagement.pojo.params.GeneratedAccessKeyParams;
import com.changhu.pojo.entity.AccessKeys;
import com.changhu.service.AccessKeysService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author 20252
 * @createTime 2024/11/19 上午10:38
 * @desc AccessKeysController...
 */
@Tag(name = "超级后台-开放平台")
@RequestMapping("/m1/accessKeys")
@JsonBody
@CheckUserType(userTypes = UserType.MANAGEMENT_SUPER)
@RestController
public class AccessKeysController {

    @Autowired
    private AccessKeysService accessKeysService;

    @GetMapping("/listOpenApi")
    public List<SelectNodeVo<String>> listOpenApi() {
        Class<OpenController> openControllerClass = OpenController.class;
        RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(openControllerClass, RequestMapping.class);
        String controllerPath = requestMapping.value()[0];
        return Arrays.stream(openControllerClass.getMethods())
                .filter(m -> AnnotationUtil.hasAnnotation(m, RequestMapping.class))
                .map(m -> {
                    Operation operation = m.getAnnotation(Operation.class);
                    RequestMapping mReq = AnnotatedElementUtils.findMergedAnnotation(m, RequestMapping.class);
                    return SelectNodeVo.<String>builder()
                            .value(controllerPath + mReq.value()[0])
                            .label(operation.summary())
                            .extData(Dict.of("methods", mReq.method()))
                            .build();
                })
                .toList();
    }

    @Operation(summary = "生成访问凭证")
    @PostMapping("/generatedAccessKey")
    public void generatedAccessKey(@RequestBody GeneratedAccessKeyParams params) {
        accessKeysService.generatedAccessKey(params);
    }

    @Operation(summary = "访问凭证列表")
    @GetMapping("/tableList")
    public List<AccessKeys> tableList() {
        return accessKeysService.list();
    }

}
