package com.cm.common.plugin.controller.apis.database;

import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.ParamsException;
import com.cm.common.exception.RemoveException;
import com.cm.common.exception.SaveException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.pojo.vos.database.DatabaseVO;
import com.cm.common.plugin.service.database.IDatabaseService;
import com.cm.common.result.SuccessResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @ClassName: DatabaseController
 * @Description: 数据库
 * @Author: WangGeng
 * @Date: 2019-07-14 18:19
 * @Version: 1.0
 **/
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/database")
public class DatabaseController extends AbstractController {

    @Autowired
    private IDatabaseService databaseService;

    /**
     * 保存数据库连接
     *
     * @param databaseVO
     * @return
     * @throws ParamsException
     */
    @PostMapping("saveconnection")
    public SuccessResult saveConnection(@RequestBody DatabaseVO databaseVO) throws ParamsException, SaveException, RemoveException, SearchException {
        Map<String, Object> params = requestParams();
        if (StringUtils.isEmpty(databaseVO.getDialect())) {
            throw new ParamsException("数据库类型不能为空");
        }
        params.put("dialect", databaseVO.getDialect().toLowerCase());

        if (StringUtils.isEmpty(databaseVO.getIp())) {
            throw new ParamsException("数据库IP不能为空");
        }
        params.put("ip", databaseVO.getIp());

        if (StringUtils.isEmpty(databaseVO.getPort())) {
            throw new ParamsException("数据库端口不能为空");
        }
        params.put("port", databaseVO.getPort());

        if (StringUtils.isEmpty(databaseVO.getDbName())) {
            throw new ParamsException("数据库名不能为空");
        }
        params.put("dbName", databaseVO.getDbName());

        if (StringUtils.isEmpty(databaseVO.getUsername())) {
            throw new ParamsException("数据库用户名不能为空");
        }
        params.put("username", databaseVO.getUsername());

        if (StringUtils.isEmpty(databaseVO.getPassword())) {
            throw new ParamsException("数据库密码不能为空");
        }
        params.put("password", databaseVO.getPassword());

        return databaseService.saveConnection(params);
    }

    /**
     * 删除数据库链接
     *
     * @return
     */
    @DeleteMapping("removeconnection")
    public SuccessResult removeConnection() throws RemoveException, SearchException {
        Map<String, Object> params = requestParams();
        return databaseService.removeConnection(params);
    }

}
