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

import com.infoepoch.pms.dispatchassistant.common.utils.OracleUtils;
import com.infoepoch.pms.dispatchassistant.controller.langchain.LangChainController;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.Conversations;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.ConversationsCriteria;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.IConversationsRepository;
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 ConversationsRepository implements IConversationsRepository {

    @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_CONVERSATIONS.NEXTVAL FROM DUAL ");
        return jdbcTemplate.queryForObject(buffer.toString(), Long.class);
    }

    /**
     * 新增
     */
    @Override
    public boolean insert(Conversations entity) {
        String sql = "INSERT INTO T_CONVERSATIONS(C_ID, C_USER_ID, C_USER_NAME, C_NAME, C_SESSION_ID, C_FIRST_QUESTION, C_STATUS, C_RECORD_TIME, C_UPDATE_TIME, C_AI_TYPE, C_CONDITION1) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int result=0;
        try {
            result = jdbcTemplate.update(sql, entity.getId(), entity.getUserId(), entity.getUserName(), entity.getName(), entity.getSessionId(), entity.getFirstQuestion(), entity.getStatus(), entity.getRecordTime(), entity.getUpdateTime(), entity.getAiType(), entity.getCondition1());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            //throw new ServiceException("新增  数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(Conversations entity) {
        String sql = "UPDATE T_CONVERSATIONS SET C_USER_ID = ?, C_USER_NAME = ?, C_NAME = ?, C_SESSION_ID = ?, C_FIRST_QUESTION = ?, C_STATUS = ?, C_RECORD_TIME = ?, C_UPDATE_TIME = ?, C_AI_TYPE = ?, C_CONDITION1 = ? WHERE C_ID = ?";
        int result=0;
        try {
            result = jdbcTemplate.update(sql, entity.getUserId(), entity.getUserName(), entity.getName(), entity.getSessionId(), entity.getFirstQuestion(), entity.getStatus(), entity.getRecordTime(), entity.getUpdateTime(), entity.getAiType(), entity.getCondition1(), entity.getId());
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
           // throw new ServiceException("更新  数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<Conversations> list) {
        String sql = "INSERT INTO T_CONVERSATIONS(C_ID, C_USER_ID, C_USER_NAME, C_NAME, C_SESSION_ID, C_FIRST_QUESTION, C_STATUS, C_RECORD_TIME, C_UPDATE_TIME, C_AI_TYPE, C_CONDITION1) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Conversations item = list.get(i);
                ps.setString(++j, item.getId());
                ps.setString(++j, item.getUserId());
                ps.setString(++j, item.getUserName());
                ps.setString(++j, item.getName());
                ps.setString(++j, item.getSessionId());
                ps.setString(++j, item.getFirstQuestion());
                ps.setString(++j, item.getStatus());
                ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
                ps.setTimestamp(++j, item.getUpdateTime() != null ? new Timestamp(item.getUpdateTime().getTime()) : null);
                ps.setString(++j, item.getAiType());
                ps.setString(++j, item.getCondition1());
            }

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

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<Conversations> list) {
        String sql = "UPDATE T_CONVERSATIONS SET C_USER_ID = ?, C_USER_NAME = ?, C_NAME = ?, C_SESSION_ID = ?, C_FIRST_QUESTION = ?, C_STATUS = ?, C_RECORD_TIME = ?, C_UPDATE_TIME = ?, C_AI_TYPE = ?, C_CONDITION1 = ? WHERE C_ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Conversations item = list.get(i);
                ps.setString(++j, item.getUserId());
                ps.setString(++j, item.getUserName());
                ps.setString(++j, item.getName());
                ps.setString(++j, item.getSessionId());
                ps.setString(++j, item.getFirstQuestion());
                ps.setString(++j, item.getStatus());
                ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
                ps.setTimestamp(++j, item.getUpdateTime() != null ? new Timestamp(item.getUpdateTime().getTime()) : null);
                ps.setString(++j, item.getAiType());
                ps.setString(++j, item.getCondition1());
                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_CONVERSATIONS WHERE C_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_CONVERSATIONS WHERE C_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 Conversations selectById(String id) {
        String sql = "SELECT * FROM T_CONVERSATIONS WHERE C_ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new ConversationsRowMapper(), id);
        } catch (Exception e) {
            LogHelper.info(e.getMessage());
            return null;
        }
    }

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

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

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

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

    /**
     * RowMapper
     */
    private class ConversationsRowMapper implements RowMapper<Conversations> {
        @Override
        public Conversations mapRow(ResultSet rs, int i) throws SQLException {
            Conversations conversations=new Conversations();
            conversations.setId( rs.getString("C_ID"));
            conversations.setUserId(rs.getString("C_USER_ID"));
            conversations.setUserName(rs.getString("C_USER_NAME"));
            conversations.setName(rs.getString("C_NAME"));
            conversations.setSessionId(rs.getString("C_SESSION_ID"));
            conversations.setFirstQuestion( rs.getString("C_FIRST_QUESTION"));
            conversations.setStatus( rs.getString("C_STATUS"));
            conversations.setRecordTime(rs.getTimestamp("C_RECORD_TIME"));
            conversations.setUpdateTime( rs.getTimestamp("C_UPDATE_TIME"));
            conversations.setAiType( rs.getString("C_AI_TYPE"));
            conversations.setCondition1( rs.getString("C_CONDITION1"));
            return conversations;
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(ConversationsCriteria 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.byUserId())
            andMap.put(criteria.getUserId() == null ? " C_USER_ID IS NULL " : " C_USER_ID = ? ", criteria.getUserId());
        //用户名
        if (criteria.byUserName())
            andMap.put(criteria.getUserName() == null ? " C_USER_NAME IS NULL " : " C_USER_NAME = ? ", criteria.getUserName());
        //用户姓名
        if (criteria.byName())
            andMap.put(criteria.getName() == null ? " C_NAME IS NULL " : " C_NAME = ? ", criteria.getName());
        //会话id
        if (criteria.bySessionId())
            andMap.put(criteria.getSessionId() == null ? " C_SESSION_ID IS NULL " : " C_SESSION_ID = ? ", criteria.getSessionId());
        //智能体专业类型
        if (criteria.byAiType())
            andMap.put(criteria.getAiType() == null ? " C_AI_TYPE IS NULL " : " C_AI_TYPE = ? ", criteria.getAiType());
        //条件1
        if (criteria.byCondition1())
            andMap.put(criteria.getCondition1() == null ? " C_CONDITION1 IS NULL " : " C_CONDITION1 = ? ", criteria.getCondition1());
        //查询近几天会话
        if (criteria.byConversationsDays())
            andMap.put(criteria.getConversationsDays() == null ? " C_RECORD_TIME IS NULL " : "C_RECORD_TIME>=sysdate-? ", criteria.getConversationsDays());
        return andMap;
    }

}
