package com.yem.wm.bd.cmmpconfig.from;

import com.yem.wm.utils.RequestCmmp;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.exception.KDBizException;
import kd.bos.form.IFormView;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;

import java.sql.*;

/**
 * @author zhouc
 * @date 2024/4/17 17:33
 * @className CMMPConfigFromEdit
 * @description CMMP配置表单插件
 */
public class CMMPConfigFromEdit extends AbstractBillPlugIn {
    private static String URL = "jdbc:oracle:thin:@";
    private static String driver = "oracle.jdbc.driver.OracleDriver";

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String operateKey = operate.getOperateKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("connection".equals(operateKey)) {
            String url = dataEntity.getString("number");
            String username = dataEntity.getString("name");
            String pwd = dataEntity.getString("yem_pwd");
            Connection connection = getConnection(driver, URL + url, username, pwd);
            if (connection != null) {
                String sql = " SELECT * FROM v$version";
                try {
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    if (preparedStatement != null) {
                        ResultSetMetaData metaData = preparedStatement.getMetaData();
                        this.getView().showSuccessNotification("连接成功！");
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    this.getView().showErrorNotification("连接失败！");
                }
            }
        }
    }

    private static Connection getConnection(String driver, String url, String username, String pwd) {
        Connection conn = null;
        try {
            Class.forName(driver); // 加载数据库驱动
            conn = DriverManager.getConnection(url, username, pwd); // 获取数据库连接
        } catch (Exception e) {
            throw new KDBizException("链接CMMP数据库失败，请查看链接配置！" + e.getMessage());
        }
        return conn;
    }

    private static boolean isConnectionValid(Connection connection) throws SQLException {
        if (connection == null || connection.isClosed()) {
            return false;
        }
        // 尝试执行一个简单的查询
        try (Statement statement = connection.createStatement()) {
            return statement.execute("SELECT 1");
        } catch (SQLException e) {
            // 如果发生SQLException，则认为连接无效
            return false;
        }
    }
}

