package cn.qg.qaplatform.controller.common;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.utils.JsonResult;
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;

@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) {
        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")) {
                jdbcTemplate.execute(sql);
                return JsonResult.success();
            } else {
                return JsonResult.success("暂不支持该类型SQL");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.serverFailed();
        }
    }
}
