package com.beagle.informix.service.impl;


import com.beagle.informix.service.InformixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.Properties;

/**
 * @author lzz
 * date 2023/5/29
 * @version 1.0
 * description:
 */
@Slf4j
@Service("informixJdbcProxyService")
public class InformixJdbcProxyServiceImpl implements InformixService {

    private ResourceLoader resourceLoader;

    public InformixJdbcProxyServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * informix.url=jdbc:informix-sqli://localhost:9088/sysadmin:INFORMIXSERVER=informix
     * informix.driverClassName=com.informix.jdbc.IfxDriver
     * informix.user=informix
     * informix.password=in4mix
     * 进入容器，使用dbaccess 进入informix
     * 问题： Invalid default sbspace name (sbspace).
     * 解决： onspaces -c -S sbspace -p /opt/ibm/data/spaces/sbspace.000 -o 100 -s 20000 -Df "LOGGING=ON"
     * @throws Exception
     */
    @Override
    public void doConnectJob() throws Exception{
        // todo 使用jdbc连接proxy，对应的query（clob、blob字段）存在jdbc 类型转换mysql异常的问题
        // Unknown exception: Can not find JDBC type `2005` in column type
        Driver driver =  getDriver();
        Connection conn = getConnection(driver);
        insert(conn);
        update(conn);
        query(conn);
        delete(conn);
        closeConnection(conn);
        deregisterDriver(driver);
    }
    private Driver getDriver() throws Exception{
        // 定义informix的驱动信息
        String driverUrl = "com.mysql.cj.jdbc.Driver";
        // 还需要加入informix的jdbc驱动jar包
        Class<?> driverClass = Class.forName(driverUrl);
        return (Driver) driverClass.getConstructor().newInstance();
    }
    private void deregisterDriver(Driver driver) throws Exception{
        // 卸载驱动
        DriverManager.deregisterDriver(driver);
    }
    private void insert(Connection conn) throws Exception{
        // 创建testdb数据库、my_test_create_table表
        // 现在模拟插入、更新、删除、查询等sql
        // 插入
        String insertSql = "insert  into  cti_vccinfo_new ( vccname, effective, agentmax,ivrmax,updatekey,tclob,tblob) values ( ? , ?, ?, ? , ?,?,? )";
        PreparedStatement stat = conn.prepareStatement(insertSql);
//        stat.setObject(1, "123456");
        stat.setObject(1, "vname");
        stat.setObject(2, 1);
        stat.setObject(3, 2);
        stat.setObject(4, 3);
        stat.setObject(5, "updatekey");
        String clobContent = "This is a very very long string df sdferwerqwsdasdsda";
        // 处理clob字段
        StringReader reader = new StringReader(clobContent);
        stat.setClob(6, reader, clobContent.length());
        // 处理blob字段
        Resource resource = resourceLoader.getResource("classpath:EnableLoopback.exe");
        File inputStream = resource.getFile();
        FileInputStream fis = new FileInputStream(inputStream);
        stat.setBlob(7, fis);
        stat.executeUpdate();
    }
    private void update(Connection conn) throws Exception{
        // 创建testdb数据库、my_test_create_table表
        // 现在模拟插入、更新、删除、查询等sql
        // 插入
        String updateSql = "update  cti_vccinfo_new set vccname = 'informix_name' where vccid = '123456'";
        PreparedStatement stat = conn.prepareStatement(updateSql);
        stat.executeUpdate();
    }
    private void query(Connection conn) throws Exception {
        String querySQL = "select * from cti_vccinfo_new where vccid = '123456' ";
        PreparedStatement stat = conn.prepareStatement(querySQL);
        ResultSet resultSet = stat.executeQuery();
        if (resultSet != null) {
            while (resultSet.next()) {
                log.info("vccid =>" + resultSet.getString("vccid"));
                Clob clob = resultSet.getClob("tclob");
                BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                String clobStr = "";
                String finalClobStr = "";
                while ((clobStr = reader.readLine())!= null) {
                    finalClobStr += clobStr;
                }
                log.info("tclob =>" + finalClobStr);
                Blob blob = resultSet.getBlob("tblob");
                BufferedInputStream bins= new BufferedInputStream(blob.getBinaryStream());
                byte [] bytes = bins.readAllBytes();
                String blobStr=  new String(bytes, StandardCharsets.UTF_8);
                log.info("tblob =>" + blobStr);
            }
         }
    }
    private void delete(Connection conn) throws Exception{
        String deleteSql = "delete from cti_vccinfo_new where vccid = '123456' ";
        conn.createStatement().executeUpdate(deleteSql);
    }
    private Connection getConnection(Driver driver) throws Exception{
        DriverManager.registerDriver(driver);
        Properties properties = new Properties();
        // 组装连接数据库信息
//        jdbc:informix-sqli://<server>:<port1526>/<database>:informixserver=<dbservername>
        StringBuilder jdbcBuilder = new StringBuilder("jdbc:mysql://localhost:23307")
                .append("/")
                .append("postgres").append("?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai&useServerPrepStmts=true"); // useServerPrepStmts=true
        DriverManager.setLoginTimeout(10);
        properties.put("user", "root");
        properties.put("password", "Apurelove9014");
        return DriverManager.getConnection(jdbcBuilder.toString(), properties);
    }
    private void closeConnection(Connection connection) throws Exception {
        connection.close();
    }
}
