package cn.qg.qaplatform.controller.common;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/sql")
public class SqlController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 执行SQL
     * @param namespace 环境
     * @param database 数据库名
     * @param sql sql语句
     * @param type 当sql语句为select时，返回的数据类型，map/list
     * @return
     */
    @GetMapping("/execute")
    public JsonResult executeSQL(String namespace, String database, String sql, String type) {
        log.info("收到sql请求，环境：{}, 数据库: {}, sql: {}, type: {}", namespace, database, sql, type);
        try {
            SwitchDataSource.dataSourceSwitch(namespace, database);
            if (sql.startsWith("select") || sql.startsWith("SELECT")) {
                if (type.equals("map")) {
                    return JsonResult.success(jdbcTemplate.queryForMap(sql));
                } else if (type.equals("list")) {
                    return JsonResult.success(jdbcTemplate.queryForList(sql));
                } else {
                    return JsonResult.serverFailed("暂不支持该类型！");
                }
            } else if (sql.startsWith("update") || sql.startsWith("UPDATE")
                    || sql.startsWith("delete") || sql.startsWith("DELETE")
                    || sql.startsWith("insert") || sql.startsWith("INSERT")
                    || sql.startsWith("create") || sql.startsWith("CREATE")) {
                jdbcTemplate.execute(sql);
                return JsonResult.success();
            } else {
                return JsonResult.success("暂不支持该类型SQL");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.serverFailed();
        }
    }
}
