package com.yem.wm.utils;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RequestCmmp {
    private static String URL = "jdbc:oracle:thin:@";
    private static String driver = "oracle.jdbc.driver.OracleDriver";

    /**
     * 根据组织ID获取链接
     *
     * @param org  组织ID
     * @param conn
     * @return
     */
    private static Connection getConnectionByOrgId(Long org, Connection conn, Long id) {
        DynamicObject cplxObj = BusinessDataServiceHelper.loadSingle(id, "yem_bd_productsgroup");
        id = getTopCplx(cplxObj);
        DynamicObject yem_cmmpconfig = QueryServiceHelper.queryOne("yem_cmmpconfig", "number,name,yem_pwd",
                new QFilter[]{new QFilter("yem_cmmpconfigentry.yem_bd_productsgroupn.id", QCP.equals, id)});
        if (yem_cmmpconfig == null) {
            return null;
        }
        String url = yem_cmmpconfig.getString("number");
        String username = yem_cmmpconfig.getString("name");
        String pwd = yem_cmmpconfig.getString("yem_pwd");
        conn = getConnection(driver, URL + url, username, pwd);
        return conn;
    }

    /**
     * 根据id获取链接
     *
     * @param id
     * @param conn
     * @return
     */
    private static Connection getConnectionById(Long id, Connection conn) {
        DynamicObject yem_cmmpconfig = QueryServiceHelper.queryOne("yem_cmmpconfig", "number,name,yem_pwd", new QFilter[]{new QFilter("id", QCP.equals, id)});
        if (yem_cmmpconfig == null) {
            throw new KDBizException("当前id未查询到CMMP连接配置，请联系管理员！");
        }

        String url = yem_cmmpconfig.getString("number");
        String username = yem_cmmpconfig.getString("name");
        String pwd = yem_cmmpconfig.getString("yem_pwd");
        conn = getConnection(driver, URL + url, username, pwd);
        return conn;
    }

    public static Long getTopCplx(DynamicObject cplxObj) {
        cplxObj = BusinessDataServiceHelper.loadSingle(cplxObj.getLong("id"), "yem_bd_productsgroup");
        if (cplxObj.get("parent") != null) {
            return getTopCplx(cplxObj.getDynamicObject("parent"));
        }
        return cplxObj.getLong("id");
    }

    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;
    }

    /**
     * @param org 组织id(废弃)
     * @param sql sql语句——不能用*
     * @param id  产品类型id
     * @return
     */
    public static List<Map> getFromCmmp(Long org, String sql, Long id) {
        if (sql.contains("select *")) {
            throw new KDBizException("请勿执行select * 语句！");
        }
        Connection conn = null;
        conn = getConnectionByOrgId(org, conn, id);
        PreparedStatement ps = null;
        ResultSet rs = null;
        String property = null;
        ArrayList<Map> list = new ArrayList<>();
        if (conn == null) {
            return list;
        }
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                HashMap<String, Object> map = new HashMap<>();
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String col_name = rsmd.getColumnName(i + 1);// 获取列名
                    Object value = rs.getObject(col_name);
                    map.put(col_name.toLowerCase(), value);
                }
                list.add(map);
            }
        } catch (SQLException ex) {
            throw new KDBizException("SQL执行失败！查询SQL:[" + sql + "]" + ex.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                throw new KDBizException("关闭资源失败！");
            }
        }
        return list;
    }

    /**
     * @param id  链接id
     * @param sql sql语句——不能用*
     * @return
     */
    public static List<Map> getFromCmmpWithConnId(Long id, String sql) {
        if (sql.contains("*")) {
            throw new KDBizException("请勿执行select * 语句！");
        }
        Connection conn = null;
        conn = getConnectionById(id, conn);
        PreparedStatement ps = null;
        ResultSet rs = null;
        String property = null;
        ArrayList<Map> list = new ArrayList<>();
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                HashMap<String, Object> map = new HashMap<>();
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String col_name = rsmd.getColumnName(i + 1);// 获取列名
                    Object value = rs.getObject(col_name);
                    map.put(col_name.toLowerCase(), value);
                }
                list.add(map);
            }
        } catch (SQLException ex) {
            throw new KDBizException("SQL执行失败！查询SQL:[" + sql + "]" + ex.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                throw new KDBizException("关闭资源失败！");
            }
        }
        return list;
    }

    /**
     * @param sql sql语句——不能用*
     * @param yem_num  账套编码
     * @return
     */
    public static List<Map> getViewConfig(String sql, String yem_num) {
        if (sql.contains("select *")) {
            throw new KDBizException("请勿执行select * 语句！");
        }
        Connection conn = null;
        conn = getConnectionnum(conn, yem_num);
        PreparedStatement ps = null;
        ResultSet rs = null;
        String property = null;
        ArrayList<Map> list = new ArrayList<>();
        if (conn == null) {
            return list;
        }
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                HashMap<String, Object> map = new HashMap<>();
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String col_name = rsmd.getColumnName(i + 1);// 获取列名
                    Object value = rs.getObject(col_name);
                    map.put(col_name.toLowerCase(), value);
                }
                list.add(map);
            }
        } catch (SQLException ex) {
            throw new KDBizException("SQL执行失败！查询SQL:[" + sql + "]" + ex.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                throw new KDBizException("关闭资源失败！");
            }
        }
        return list;
    }

    /**
     * 根据章台编码获取配置信息
     *
     * @param conn
     * @param yem_num
     * @return
     */
    private static Connection getConnectionnum(Connection conn, String yem_num) {
        DynamicObject yem_cmmpconfig = QueryServiceHelper.queryOne("yem_cmmpconfig", "number,name,yem_pwd",
                new QFilter[]{new QFilter("yem_num", QCP.equals, yem_num)});
        if (yem_cmmpconfig == null) {
            return null;
        }
        String url = yem_cmmpconfig.getString("number");
        String username = yem_cmmpconfig.getString("name");
        String pwd = yem_cmmpconfig.getString("yem_pwd");
        conn = getConnection(driver, URL + url, username, pwd);
        return conn;
    }
}
