package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.DataSource;
import com.ruoyi.system.service.IDataSourceService;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/dataSource")
public class DataSourceController extends BaseController {

    @Resource
    private IDataSourceService dataSourceService;

    /**
     * 数据源信息列表
     */
    @GetMapping("/list")
    public AjaxResult dataSourceList(){
        return AjaxResult.success(dataSourceService.list());
    }

    /**
     * 新增数据源
     */
    @PostMapping("/save")
    public AjaxResult addDataSource(@RequestBody Map<String,Object> map){

        DataSource dataSource = JSON.parseObject(JSON.toJSONString(map.get("dataSource")), DataSource.class);
        Integer tenantId = (Integer)map.get("tenantId");
        if(dataSourceService.selectDatabaseExist(dataSource.getDatabaseIp(),dataSource.getDatabaseName(),dataSource.getPortNumber())>0){
            return AjaxResult.error("数据源已存在");
        }
        return toAjax(dataSourceService.insertDataSource(dataSource,tenantId.longValue()));
    }

}
