package com.beagle.informix.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.beagle.informix.service.InformixService;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
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.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    private ResourceLoader resourceLoader;

    public InformixJdbcServiceImpl(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{
        Driver driver = getDriver();
        Connection conn = getConnection(driver);
//        insert(conn);
//        update(conn);
        // todo 使用jdbc连接proxy，对应的query（clob、blob字段）存在jdbc 类型转换mysql异常的问题
        // Unknown exception: Can not find JDBC type `2005` in column type
//        insert(conn);
//        update(conn);
        ResultSet rs = this.getImportedKeys(conn, conn.getMetaData(), "AO_2AD648_INSIGHT_ANNOTATION");
       this.newForeignKey(rs, "AO_2AD648_INSIGHT_ANNOTATION");

//        query(conn);
//        delete(conn);
//        deregisterDriver(driver);
        closeConnection(conn);
    }
    private ResultSet getImportedKeys(Connection connection, DatabaseMetaData metaData, String tableName) throws SQLException {
        return connection.getMetaData().getImportedKeys((String)null, connection.getSchema(), tableName);
    }



    private Object newForeignKey(ResultSet rs, String localTableName) throws SQLException {
        String localFieldName = this.parseStringValue(rs, "FKCOLUMN_NAME");
        String foreignFieldName = this.parseStringValue(rs, "PKCOLUMN_NAME");
        String foreignTableName = this.parseStringValue(rs, "PKTABLE_NAME");
        return null;
//        return new DatabaseMetaDataReaderImpl.ForeignKeyImpl(localTableName, localFieldName, foreignTableName, foreignFieldName);
    }

    private String parseStringValue(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (StringUtils.isBlank(value)) {
            return value;
        } else {
            Matcher m = STRING_VALUE.matcher(value);
            return m.find() ? m.group(1) : value;
        }
    }

    private static final Pattern STRING_VALUE = Pattern.compile("\"(.*)\"");


    public static void main(String[] args) {
        try {
            new InformixJdbcServiceImpl(null).doConnectJob();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private void insert(Connection conn) throws Exception{
        // 创建testdb数据库、my_test_create_table表
        // 现在模拟插入、更新、删除、查询等sql
        // 插入
        String insertSql = "insert  into  cti_vccinfo_new (vccid ,vccname, effective, agentmax,ivrmax,updatekey,tclob,tblob) values (?, ? , ?, ?, ? , ?,?,? )";
        PreparedStatement stat = conn.prepareStatement(insertSql);
        stat.setObject(1, "123456");
        stat.setObject(2, "vname");
        stat.setObject(3, 1);
        stat.setObject(4, 2);
        stat.setObject(5, 3);
        stat.setObject(6, "updatekey");
        String clobContent = "This is a very very long string";
        // 处理clob字段
        StringReader reader = new StringReader(clobContent);
        stat.setClob(7, reader, clobContent.length());
        // 处理blob字段
        Resource resource = resourceLoader.getResource("classpath:translator.bak2.yaml");
        File inputStream = resource.getFile();
        FileInputStream fis = new FileInputStream(inputStream);
        stat.setBlob(8, 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 tabs ";
        PreparedStatement stat = conn.prepareStatement(querySQL);
        ResultSet resultSet = stat.executeQuery();
        if (resultSet != null) {
            while (resultSet.next()) {
                java.util.Date dateExecuted = null;
                Object tmpDateExecuted = resultSet.getObject("cols");
                if (tmpDateExecuted instanceof Date) {
                    dateExecuted = (Date)tmpDateExecuted;
                } else {
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        dateExecuted = df.parse((String)tmpDateExecuted);
                    } catch (ParseException e) {}
                }
            }
         }
    }
    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://")
        StringBuilder jdbcBuilder = new StringBuilder("jdbc:kingbase8://")
                .append("localhost:54321")
                .append("/")
                .append("test");
        DriverManager.setLoginTimeout(10);
        properties.put("user", "root");
        properties.put("password", "123456");
        return DriverManager.getConnection(jdbcBuilder.toString(), properties);
    }
    private Driver getDriver() throws Exception{
        // 定义informix的驱动信息
//        String driverUrl = "com.mysql.jdbc.Driver";
        String driverUrl = "com.kingbase8.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 closeConnection(Connection connection) throws Exception {
        connection.close();
    }
}
