package com.ruoyi.ucp.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ucp.entity.UcpDataSource;
import com.ruoyi.ucp.service.IUcpDataSourceService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gfhd
 * @since 2024-02-20
 */
@RestController
@RequestMapping("/ucpDataSource")
public class UcpDataSourceController extends BaseController {

    @Resource
    private IUcpDataSourceService ucpDataSourceService;

    @PostMapping("/test")
    public AjaxResult test(@RequestBody UcpDataSource dataSource) {
        try (Connection conn = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUserName(), dataSource.getPassWord());) {
            return toAjax(true);
        } catch (Exception e) {
            return toAjax(false);
        }
    }

    /**
     * 查询数据库列表
     */
    @PreAuthorize("@ss.hasPermi('monitor:job:list')")
    @GetMapping("/list")
    public TableDataInfo list() {
        List<UcpDataSource> list = ucpDataSourceService.list();
        return getDataTable(list);
    }

    /**
     * 获取数据库详细信息
     */
    @PreAuthorize("@ss.hasPermi('monitor:job:query')")
    @GetMapping(value = "/{jobId}")
    public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
        return success(ucpDataSourceService.getById(jobId));
    }

    /**
     * 新增数据库
     */
    @PreAuthorize("@ss.hasPermi('monitor:job:add')")
    @Log(title = "数据库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UcpDataSource job) {
        return toAjax(ucpDataSourceService.save(job));
    }

    /**
     * 修改数据库
     */
    @PreAuthorize("@ss.hasPermi('monitor:job:edit')")
    @Log(title = "数据库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UcpDataSource job) {
        return toAjax(ucpDataSourceService.updateById(job));
    }

    /**
     * 删除数据库
     */
    @PreAuthorize("@ss.hasPermi('monitor:job:remove')")
    @Log(title = "数据库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{jobIds}")
    public AjaxResult remove(@PathVariable List<Long> jobIds) {
        return toAjax(ucpDataSourceService.removeByIds(jobIds));
    }
}
