package com.ruoyi.business.controller;

import com.ruoyi.business.domain.Database;
import com.ruoyi.business.domain.vo.DatabaseVo;
import com.ruoyi.business.service.IDatabaseService;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据源Controller
 * 
 * @author ruoyi
 * @date 2024-01-10
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/database")
@RequiredArgsConstructor
public class DatabaseController extends BaseController {

    private final IDatabaseService databaseService;

    /**
     * 查询数据源列表
     */
    @RequiresPermissions("business_database_list")
    @GetMapping
    public AjaxResult list(Database database) {
        List<Database> list = databaseService.selectDatabaseList(database);
        return success(list);
    }

    /**
     * 查询数据源列表(分页)
     */
    @RequiresPermissions("business_database_list")
    @GetMapping("/list")
    public TableDataInfo pageList(Database database) {
        startPage();
        List<Database> list = databaseService.selectDatabaseList(database);
        return getDataTable(list);
    }

    @RequiresPermissions("business_database_list")
    @GetMapping("/dict")
    public AjaxResult selectDatabaseDict(Database database) {
        List<Database> list = databaseService.selectDatabaseDict(database);
        return success(list);
    }

    /**
     * 获取数据源详细信息
     */
    @RequiresPermissions("business_database_query")
    @GetMapping(value = "/{id}")
    public AjaxResult getDatabaseById(@PathVariable("id") Long id) {
        return success(databaseService.selectDatabaseById(id));
    }

    /**
     * 新增数据源
     */
    @RequiresPermissions("business_database_add")
    @Log(title = "数据源", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addDatabase(@RequestBody Database database) {
        database.setDeptIdPath(SecurityUtils.getDeptIdPath());
        database.setDeptName(SecurityUtils.getDeptName());
        database.setCreateUserId(SecurityUtils.getUserId());
        database.setCreateBy(SecurityUtils.getUsername());
        return toAjax(databaseService.insertDatabase(database));
    }

    /**
     * 修改数据源
     */
    @RequiresPermissions("business_database_edit")
    @Log(title = "数据源", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateDatabase(@RequestBody Database database) {
        database.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(databaseService.updateDatabase(database));
    }

    /**
     * 批量删除数据源
     */
    @RequiresPermissions("business_database_delete")
    @Log(title = "数据源", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteByIds/{ids}")
    public AjaxResult delete(@PathVariable Long[] ids) {
        return toAjax(databaseService.deleteDatabaseByIds(ids));
    }

    /**
     * 删除数据源
     */
    @RequiresPermissions("business_database_delete")
    @Log(title = "数据源", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteById/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        return toAjax(databaseService.deleteDatabaseById(id));
    }

    /**
     * 导出数据源列表
     */
    @RequiresPermissions("business_database_export")
    @Log(title = "数据源", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Database database) {
        List<Database> list = databaseService.selectDatabaseList(database);
        ExcelUtil<Database> util = new ExcelUtil<Database>(Database.class);
        util.exportExcel(response, list, "数据源数据");
    }

    @PostMapping("/testConnection")
    @Log(title = "测试数据库连接", businessType = BusinessType.INSERT)
    public AjaxResult testConnection(@RequestBody DatabaseVo databaseVo) {
        try {
            if (databaseService.testConnection(databaseVo)){
                return success("数据库连接成功！");
            }else {
                return error("数据库关闭连接失败！");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return error("找不到驱动程序类 ，加载驱动失败！");
        } catch (SQLException e){
            e.printStackTrace();
            return error("数据库连接失败！");
        }
    }

    @PostMapping("/testConn_update")
    @Log(title = "编辑时测试数据库连接", businessType = BusinessType.UPDATE)
    public AjaxResult testConnection_update(@RequestBody DatabaseVo databaseVo) {
        try {
            if (databaseService.testConnection_update(databaseVo)){
                return success("数据库连接成功！");
            }else {
                return error("数据库关闭连接失败！");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return error("找不到驱动程序类 ，加载驱动失败！");
        } catch (SQLException e){
            e.printStackTrace();
            return error("数据库连接失败！");
        }
    }

    /**
     * 查询数据源的表
     * @param dataSourceId 数据源id
     * @return 表
     */
    @RequiresPermissions("business_database_list")
    @GetMapping("/tables")
    public AjaxResult selectDatabaseTables(String dataSourceId) {
        return databaseService.getTables(dataSourceId);
    }

    /**
     * 获取表字段
     *
     * @param dbId 数据源配置id
     * @param tableName 表名
     * @return 字段集合
     */
    @RequiresPermissions("business_database_list")
    @GetMapping("/tableFields")
    public AjaxResult getTableFields(Long dbId, String tableName) throws SQLException, ClassNotFoundException {
        return AjaxResult.success(databaseService.getTableFields(dbId, tableName));
    }
}
