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.GraphThread;
import com.infoepoch.pms.agent.platform.chat.domain.irepository.GraphThreadCriteria;
import com.infoepoch.pms.agent.platform.chat.domain.irepository.IGraphThreadRepository;
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;

/**
 * @author jiangyz
 * @date 2026/4/18 11:23
 */
@Repository
public class GraphThreadRepository implements IGraphThreadRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     */
    @Override
    public boolean insert(GraphThread entity) {
        String sql = "INSERT INTO AI_GRAPHTHREAD(THREAD_ID, THREAD_NAME, IS_RELEASED) VALUES (?, ?, ?)";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getThreadId(), entity.getThreadName(), entity.getReleased());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("新增  数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(GraphThread entity) {
        String sql = "UPDATE AI_GRAPHTHREAD SET THREAD_NAME = ?, IS_RELEASED = ? WHERE THREAD_ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getThreadName(), entity.getReleased(), entity.getThreadId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("更新  数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<GraphThread> list) {
        String sql = "INSERT INTO AI_GRAPHTHREAD(THREAD_ID, THREAD_NAME, IS_RELEASED) VALUES (?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                GraphThread item = list.get(i);
                ps.setString(++j, item.getThreadId());
                ps.setString(++j, item.getThreadName());
                ps.setBoolean(++j, item.getReleased());
            }

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

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<GraphThread> list) {
        String sql = "UPDATE AI_GRAPHTHREAD SET THREAD_NAME = ?, IS_RELEASED = ? WHERE THREAD_ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                GraphThread item = list.get(i);
                ps.setString(++j, item.getThreadName());
                ps.setBoolean(++j, item.getReleased());
                ps.setString(++j, item.getThreadId());
            }

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

    /**
     * 删除
     */
    @Override
    public boolean delete(String id) {
        String sql = "DELETE FROM AI_GRAPHTHREAD WHERE THREAD_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 GraphThread selectById(String id) {
        String sql = "SELECT * FROM AI_GRAPHTHREAD WHERE THREAD_ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new GraphThreadRowMapper(), id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

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

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

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

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

    /**
     * RowMapper
     */
    private class GraphThreadRowMapper implements RowMapper<GraphThread> {
        @Override
        public GraphThread mapRow(ResultSet rs, int i) throws SQLException {
            return new GraphThread(
                    rs.getString("THREAD_ID"),
                    rs.getString("THREAD_NAME"),
                    rs.getObject("IS_RELEASED") != null ? rs.getBoolean("IS_RELEASED") : null
            );
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(GraphThreadCriteria 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.byThreadId())
            andMap.put(criteria.getThreadId() == null ? " THREAD_ID IS NULL " : " THREAD_ID = ? ", criteria.getThreadId());
        //
        if (criteria.byThreadName())
            andMap.put(criteria.getThreadName() == null ? " THREAD_NAME IS NULL " : " THREAD_NAME = ? ", criteria.getThreadName());
        //
        if (criteria.byReleased())
            andMap.put(criteria.getReleased() == null ? " IS_RELEASED IS NULL " : " IS_RELEASED = ? ", criteria.getReleased());
        return andMap;
    }

}
