package com.docus.server.common;

import com.docus.infrastructure.core.db.enums.EnumItemView;
import com.docus.infrastructure.core.db.enums.IIntegerEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/common/")
@Api(value = "通用控制层", tags = "通用控制层")
public class CommonController {

    @Value("${mybatis-plus.type-enums-package:#{nu11}}")
    private String enumsPackage;
    @Value("${spring.application.name: #{null}}")
    private String appName;

    //返回数据库枚举定义的value和display，枚举需实现IIntegerEnum接口
    @IgnoreValidate
    @GetMapping("enum/{enumName}")
    @ApiOperation("按枚举名称获取枚举列表值")
    public List<EnumItemView> getEnum(@PathVariable String enumName) throws ClassNotFoundException {
        if (!StringUtils.isEmpty(enumsPackage)) {
            String className = enumsPackage + "." + enumName;
            if (!className.endsWith("Enum")) {
                className += "Enum";
            }
            Class<IIntegerEnum> enumClass = (Class<IIntegerEnum>) Class.forName(className);
            IIntegerEnum[] enums = enumClass.getEnumConstants();
            List<EnumItemView> enumItemViews = new ArrayList<>();
            for (IIntegerEnum anEnum : enums) {
                EnumItemView enumItemView = new EnumItemView();
                enumItemView.setValue(anEnum.getValue());
                enumItemView.setDisplay(anEnum.getDisplay());
                enumItemViews.add(enumItemView);
            }
            return enumItemViews;
        }
        return null;
    }
}
