package com.infoepoch.pms.dispatchassistant.infractructure.langchain;

import com.infoepoch.pms.dispatchassistant.common.utils.OracleUtils;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.IMessagesRepository;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.Messages;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.MessagesCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * generated by code-generator
 * 仓储实现
 */
@Repository
public class MessagesRepository implements IMessagesRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final Logger LogHelper = LoggerFactory.getLogger(ConversationsRepository.class);

    /**
     * 查询表序列id
     */
    @Override
    public Long sequenceId() {
        StringBuffer buffer = new StringBuffer("SELECT SEQ_T_MESSAGES.NEXTVAL FROM DUAL ");
        return jdbcTemplate.queryForObject(buffer.toString(), Long.class);
    }

    /**
     * 新增
     */
    @Override
    public boolean insert(Messages entity) {
        String sql = "INSERT INTO T_MESSAGES(M_ID, M_CID, M_SESSION_ID, M_REQUEST_ID, M_ROLE, M_CONTENT, M_PARENT_MSG_ID, M_KEY_WORDS, M_MODEL_NAME, M_RECORD_TIME,M_SORT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
        int result=0;
        try {
            result = jdbcTemplate.update(sql, entity.getId(), entity.getCid(), entity.getSessionId(), entity.getRequestId(), entity.getRole(), entity.getContent(), entity.getParentMsgId(), entity.getKeyWords(), entity.getModelName(), entity.getRecordTime(),entity.getSort());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
           // throw new ServiceException("新增  数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(Messages entity) {
        String sql = "UPDATE T_MESSAGES SET M_CID = ?, M_SESSION_ID = ?, M_REQUEST_ID = ?, M_ROLE = ?, M_CONTENT = ?, M_PARENT_MSG_ID = ?, M_KEY_WORDS = ?, M_MODEL_NAME = ?, M_RECORD_TIME = ?,M_SORT=? WHERE M_ID = ?";
        int result=0;
        try {
            result = jdbcTemplate.update(sql, entity.getCid(), entity.getSessionId(), entity.getRequestId(), entity.getRole(), entity.getContent(), entity.getParentMsgId(), entity.getKeyWords(), entity.getModelName(), entity.getRecordTime(),entity.getSort(), entity.getId());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
          //  throw new ServiceException("更新  数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<Messages> list) {
        String sql = "INSERT INTO T_MESSAGES(M_ID, M_CID, M_SESSION_ID, M_REQUEST_ID, M_ROLE, M_CONTENT, M_PARENT_MSG_ID, M_KEY_WORDS, M_MODEL_NAME, M_RECORD_TIME,M_SORT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Messages item = list.get(i);
                ps.setString(++j, item.getId());
                ps.setString(++j, item.getCid());
                ps.setString(++j, item.getSessionId());
                ps.setString(++j, item.getRequestId());
                ps.setString(++j, item.getRole());
                ps.setString(++j, item.getContent());
                ps.setString(++j, item.getParentMsgId());
                ps.setString(++j, item.getKeyWords());
                ps.setString(++j, item.getModelName());
                ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
                ps.setInt(++j, item.getSort());
            }

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

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<Messages> list) {
        String sql = "UPDATE T_MESSAGES SET M_CID = ?, M_SESSION_ID = ?, M_REQUEST_ID = ?, M_ROLE = ?, M_CONTENT = ?, M_PARENT_MSG_ID = ?, M_KEY_WORDS = ?, M_MODEL_NAME = ?, M_RECORD_TIME = ? ,M_SORT=? WHERE M_ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Messages item = list.get(i);
                ps.setString(++j, item.getCid());
                ps.setString(++j, item.getSessionId());
                ps.setString(++j, item.getRequestId());
                ps.setString(++j, item.getRole());
                ps.setString(++j, item.getContent());
                ps.setString(++j, item.getParentMsgId());
                ps.setString(++j, item.getKeyWords());
                ps.setString(++j, item.getModelName());
                ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
                ps.setInt(++j, item.getSort());
                ps.setString(++j, item.getId());
            }

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

    /**
     * 删除
     */
    @Override
    public boolean delete(String id) {
        String sql = "DELETE FROM T_MESSAGES WHERE M_ID = ?";
        int result=0;
        try {
            result = jdbcTemplate.update(sql, id);
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            //throw new ServiceException("删除  数据 失败。");
        }
        return result > 0;
    }

    /**
     * 删除
     */
    @Override
    public boolean deleteBySessionId(String sessionId) {
        String sql = "DELETE FROM T_MESSAGES WHERE M_SESSION_ID = ?";
        int result=0;
        try {
            result = jdbcTemplate.update(sql, sessionId);
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            //throw new ServiceException("删除  数据 失败。");
        }
        return result > 0;
    }

    /**
     * 根据Id查询
     */
    @Override
    public Messages selectById(String id) {
        String sql = "SELECT * FROM T_MESSAGES WHERE M_ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new MessagesRowMapper(), id);
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            return null;
        }
    }

    /**
     * 根据查询条件查询单个对象
     */
    @Override
    public Messages selectOneByCriteria(MessagesCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), 1, 1,"M_SORT",true);
        try {
            return jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), new MessagesRowMapper());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            return null;
        }
    }

    /**
     * 根据查询条件查询对象集合
     */
    @Override
    public List<Messages> selectByCriteria(MessagesCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria),"M_SORT",false);
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new MessagesRowMapper());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            return null;
        }
    }

    /**
     * 根据查询条件分页查询对象结合
     */
    @Override
    public List<Messages> selectCriteriaByPage(MessagesCriteria criteria, int pageNum, int pageSize) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), pageNum, pageSize);
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new MessagesRowMapper());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            return null;
        }
    }

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

    /**
     * RowMapper
     */
    private class MessagesRowMapper implements RowMapper<Messages> {
        @Override
        public Messages mapRow(ResultSet rs, int i) throws SQLException {
            Messages messages=new Messages();
            messages.setId(rs.getString("M_ID"));
            messages.setCid(rs.getString("M_CID"));
            messages.setSessionId( rs.getString("M_SESSION_ID"));
            messages.setRequestId(rs.getString("M_REQUEST_ID"));
            messages.setRole(rs.getString("M_ROLE"));
            messages.setContent(rs.getString("M_CONTENT"));
            messages.setParentMsgId(rs.getString("M_PARENT_MSG_ID"));
            messages.setKeyWords(rs.getString("M_KEY_WORDS"));
            messages.setModelName( rs.getString("M_MODEL_NAME"));
            messages.setRecordTime(rs.getTimestamp("M_RECORD_TIME"));
            messages.setSort(rs.getInt("M_SORT"));
            return messages;
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(MessagesCriteria 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.byId())
            andMap.put(criteria.getId() == null ? " M_ID IS NULL " : " M_ID = ? ", criteria.getId());
        //会话表主键
        if (criteria.byCid())
            andMap.put(criteria.getCid() == null ? " M_CID IS NULL " : " M_CID = ? ", criteria.getCid());
        //会话id
        if (criteria.bySessionId())
            andMap.put(criteria.getSessionId() == null ? " M_SESSION_ID IS NULL " : " M_SESSION_ID = ? ", criteria.getSessionId());
        //请求id
        if (criteria.byRequestId())
            andMap.put(criteria.getRequestId() == null ? " M_REQUEST_ID IS NULL " : " M_REQUEST_ID = ? ", criteria.getRequestId());
        //角色'user','assistant'
        if (criteria.byRole())
            andMap.put(criteria.getRole() == null ? " M_ROLE IS NULL " : " M_ROLE = ? ", criteria.getRole());
        //父消息id
        if (criteria.byParentMsgId())
            andMap.put(criteria.getParentMsgId() == null ? " M_PARENT_MSG_ID IS NULL " : " M_PARENT_MSG_ID = ? ", criteria.getParentMsgId());
        return andMap;
    }

}
