package com.infoepoch.pms.agent.platform.chatbot.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.chatbot.domain.ChatbotAgents;
import com.infoepoch.pms.agent.platform.chatbot.domain.irepository.ChatbotAgentsCriteria;
import com.infoepoch.pms.agent.platform.chatbot.domain.irepository.IChatbotAgentsRepository;
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.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天机器人与智能体关联表仓储实现
 */
@Repository
public class ChatbotAgentsRepository implements IChatbotAgentsRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     */
    @Override
    public boolean insert(ChatbotAgents entity) {
        String sql = "INSERT INTO AI_CHATBOT_AGENTS(ID, CHATBOT_ID, AGENT_ID) VALUES (?, ?, ?)";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getId(), entity.getChatBotId(), entity.getAgentId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("新增 聊天机器人与智能体关联表 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(ChatbotAgents entity) {
        String sql = "UPDATE AI_CHATBOT_AGENTS SET CHATBOT_ID = ?, AGENT_ID = ? WHERE ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getChatBotId(), entity.getAgentId(), entity.getId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("更新 聊天机器人与智能体关联表 数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<ChatbotAgents> list) {
        String sql = "INSERT INTO AI_CHATBOT_AGENTS(ID, CHATBOT_ID, AGENT_ID) VALUES (?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                ChatbotAgents item = list.get(i);
                ps.setString(++j, item.getId());
                ps.setString(++j, item.getChatBotId());
                ps.setString(++j, item.getAgentId());
            }

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

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<ChatbotAgents> list) {
        String sql = "UPDATE AI_CHATBOT_AGENTS SET CHATBOT_ID = ?, AGENT_ID = ? WHERE ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                ChatbotAgents item = list.get(i);
                ps.setString(++j, item.getChatBotId());
                ps.setString(++j, item.getAgentId());
                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_CHATBOT_AGENTS 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 ChatbotAgents selectById(String id) {
        String sql = "SELECT * FROM AI_CHATBOT_AGENTS WHERE ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new ChatbotAgentsRowMapper(), id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

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

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

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

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

    @Override
    public List<ChatbotAgents> findByChatBotId(String chatbotId) {
        ChatbotAgentsCriteria criteria = new ChatbotAgentsCriteria();
        criteria.setChatBotId(chatbotId);
        List<ChatbotAgents> relations = selectByCriteria(criteria);
        return relations == null ? List.of() : relations;
    }

    @Override
    public void deleteByChatBotId(String chatbotId) {
        findByChatBotId(chatbotId).forEach(item -> delete(item.getId()));
    }

    @Override
    public void deleteByAgentId(String agentId) {
        ChatbotAgentsCriteria criteria = new ChatbotAgentsCriteria();
        criteria.setAgentId(agentId);
        List<ChatbotAgents> relations = selectByCriteria(criteria);
        if (relations == null) {
            return;
        }
        relations.forEach(item -> delete(item.getId()));
    }

    /**
     * RowMapper
     */
    private class ChatbotAgentsRowMapper implements RowMapper<ChatbotAgents> {
        @Override
        public ChatbotAgents mapRow(ResultSet rs, int i) throws SQLException {
            return new ChatbotAgents(
                    rs.getString("ID"),
                    rs.getString("CHATBOT_ID"),
                    rs.getString("AGENT_ID")
            );
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(ChatbotAgentsCriteria 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());

        //聊天机器人主键
        if (criteria.byChatBotId())
            andMap.put(criteria.getChatBotId() == null ? " CHATBOT_ID IS NULL " : " CHATBOT_ID = ? ", criteria.getChatBotId());
        //关联的智能体主键
        if (criteria.byAgentId())
            andMap.put(criteria.getAgentId() == null ? " AGENT_ID IS NULL " : " AGENT_ID = ? ", criteria.getAgentId());
        return andMap;
    }
}
