package com.artfess.report.bigScreen.controller;

import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.controller.BaseController;
import com.artfess.base.datasource.DatabaseContext;
import com.artfess.base.datasource.DatabaseSwitchResult;
import com.artfess.base.feign.SystemConfigFeignService;
import com.artfess.report.bigScreen.manager.BladeVisualConfigManager;
import com.artfess.report.bigScreen.model.BladeVisualConfig;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 可视化配置表 前端控制器
 *
 * @author 向贞好
 * @company 阿特菲斯
 * @since 2021-07-12
 */
@RestController
@RequestMapping("/bigScreen/bladeVisualConfig/v1/")
@Api(tags = "可视化配置接口")
@ApiGroup(group = {ApiGroupConsts.GROUP_APPLICATION})
public class BladeVisualConfigController extends BaseController<BladeVisualConfigManager, BladeVisualConfig> {
    @Resource
    SystemConfigFeignService systemConfigFeignService;
    @Resource
    DatabaseContext databaseContext;

    @RequestMapping(value = "dosql", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "", httpMethod = "POST", notes = "")
    public List<Map<String,Object>> doQuery(@ApiParam(name = "alias", value = "别名") @RequestParam Optional<String> alias,
                                            @ApiParam(name = "sql", value = "sql") @RequestBody String sql) throws Exception {
        JsonNode sysDataSource = systemConfigFeignService.getBeanByAlias(alias.orElse(null));//根据数据源别名，获取数据源的设置信息
        if (sysDataSource == null) {
            return null;
        }
        String aliasName =sysDataSource.get("alias").asText();
        DatabaseSwitchResult dResult = databaseContext.setDataSource(aliasName);//根据别名切换数据源
        MySqlStatementParser parser = new MySqlStatementParser(sql);//校验sql是否合法
        List<com.alibaba.druid.sql.ast.SQLStatement> smtList = parser.parseStatementList();
        return  baseService.query(sql);//执行sql
    }

}
