package com.infoepoch.pms.agent.platform.chat.adapter.out.persistence;

import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.common.utils.OracleUtils;
import com.infoepoch.pms.agent.platform.chat.domain.ChatMessageBlock;
import com.infoepoch.pms.agent.platform.chat.domain.Conversation;
import com.infoepoch.pms.agent.platform.chat.domain.irepository.ConversationCriteria;
import com.infoepoch.pms.agent.platform.chat.domain.irepository.IConversationRepository;
import com.infoepoch.pms.agent.platform.shared.exception.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 对话记录表仓储实现
 */
@Repository
public class ConversationRepository implements IConversationRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     */
    @Override
    public boolean insert(Conversation entity) {
        String sql = "INSERT INTO AI_CONVERSATIONS(ID, SESSION_ID, ROLE, CONTENT, AGENT_ID, METADATA, CREATED_AT, BLOCKS, THREAD_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getId(), entity.getSessionId(), entity.getRole(), entity.getContent(), entity.getAgentId(), entity.getMetadataJson(), entity.getCreatedAt() != null ? Timestamp.valueOf(entity.getCreatedAt()) : null, entity.getBlocksJson(), entity.getThreadId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("新增 对话记录表 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(Conversation entity) {
        String sql = "UPDATE AI_CONVERSATIONS SET SESSION_ID = ?, ROLE = ?, CONTENT = ?, AGENT_ID = ?, METADATA = ?, CREATED_AT = ?, BLOCKS = ?, THREAD_ID = ? WHERE ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getSessionId(), entity.getRole(), entity.getContent(), entity.getAgentId(), entity.getMetadataJson(), entity.getCreatedAt() != null ? Timestamp.valueOf(entity.getCreatedAt()) : null, entity.getBlocksJson(), entity.getThreadId(), entity.getId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("更新 对话记录表 数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<Conversation> list) {
        String sql = "INSERT INTO AI_CONVERSATIONS(ID, SESSION_ID, ROLE, CONTENT, AGENT_ID, METADATA, CREATED_AT, BLOCKS, THREAD_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Conversation item = list.get(i);
                ps.setString(++j, item.getId());
                ps.setString(++j, item.getSessionId());
                ps.setString(++j, item.getRole());
                ps.setString(++j, item.getContent());
                ps.setString(++j, item.getAgentId());
                ps.setString(++j, item.getMetadataJson());
                ps.setTimestamp(++j, item.getCreatedAt() != null ? Timestamp.valueOf(item.getCreatedAt()) : null);
                ps.setString(++j, item.getBlocksJson());
                ps.setString(++j, item.getThreadId());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        return result;
    }

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<Conversation> list) {
        String sql = "UPDATE AI_CONVERSATIONS SET SESSION_ID = ?, ROLE = ?, CONTENT = ?, AGENT_ID = ?, METADATA = ?, CREATED_AT = ?, BLOCKS = ?, THREAD_ID = ? WHERE ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Conversation item = list.get(i);
                ps.setString(++j, item.getSessionId());
                ps.setString(++j, item.getRole());
                ps.setString(++j, item.getContent());
                ps.setString(++j, item.getAgentId());
                ps.setString(++j, item.getMetadataJson());
                ps.setTimestamp(++j, item.getCreatedAt() != null ? Timestamp.valueOf(item.getCreatedAt()) : null);
                ps.setString(++j, item.getBlocksJson());
                ps.setString(++j, item.getThreadId());
                ps.setString(++j, item.getId());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        return result;
    }

    /**
     * 删除
     */
    @Override
    public boolean delete(String id) {
        String sql = "DELETE FROM AI_CONVERSATIONS WHERE ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("删除 对话记录表 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 根据Id查询
     */
    @Override
    public Conversation selectById(String id) {
        String sql = "SELECT * FROM AI_CONVERSATIONS WHERE ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new ConversationRowMapper(), id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件查询单个对象
     */
    @Override
    public Conversation selectOneByCriteria(ConversationCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM AI_CONVERSATIONS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), 1, 1);
        try {
            return jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), new ConversationRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件查询对象集合
     */
    @Override
    public List<Conversation> selectByCriteria(ConversationCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM AI_CONVERSATIONS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria));
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new ConversationRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件分页查询对象结合
     */
    @Override
    public List<Conversation> selectCriteriaByPage(ConversationCriteria criteria, int pageNum, int pageSize) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM AI_CONVERSATIONS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), pageNum, pageSize);
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new ConversationRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据条件查询对象总记录数
     */
    @Override
    public Integer selectCountByCriteria(ConversationCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT COUNT(*) FROM AI_CONVERSATIONS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria));
        int count = jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), int.class);
        return count;
    }

    /**
     * RowMapper
     */
    private class ConversationRowMapper implements RowMapper<Conversation> {
        @Override
        public Conversation mapRow(ResultSet rs, int i) throws SQLException {
            return new Conversation(
                    rs.getString("ID"),
                    rs.getString("SESSION_ID"),
                    rs.getString("ROLE"),
                    rs.getString("CONTENT"),
                    rs.getString("AGENT_ID"),
                    rs.getString("METADATA"),
                    rs.getString("BLOCKS"),
                    rs.getTimestamp("CREATED_AT").toLocalDateTime(),
                    rs.getString("THREAD_ID")
            );
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(ConversationCriteria criteria) {
        Map<String, Object> andMap = new LinkedHashMap<>();
        if (criteria == null)
            return andMap;
        //if (criteria.byId())
        //    andMap.put(criteria.getId() == null ? " T_Id IS NULL " : " T_Id = ? ", criteria.getId());

        //会话id
        if (criteria.bySessionId())
            andMap.put(criteria.getSessionId() == null ? " SESSION_ID IS NULL " : " SESSION_ID = ? ", criteria.getSessionId());
        //user / assistant / tool
        if (criteria.byRole())
            andMap.put(criteria.getRole() == null ? " ROLE IS NULL " : " ROLE = ? ", criteria.getRole());
        //触发了哪个智能体，普通对话为 NULL
        if (criteria.byAgentId())
            andMap.put(criteria.getAgentId() == null ? " AGENT_ID IS NULL " : " AGENT_ID = ? ", criteria.getAgentId());
        //消息所属上下文线程 ID
        if (criteria.byThreadId())
            andMap.put(criteria.getThreadId() == null ? " THREAD_ID IS NULL " : " THREAD_ID = ? ", criteria.getThreadId());
        return andMap;
    }

}
