package com.infoepoch.pms.agent.platform.model.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.model.domain.SystemSettings;
import com.infoepoch.pms.agent.platform.model.domain.irepository.ISystemSettingsRepository;
import com.infoepoch.pms.agent.platform.model.domain.irepository.SystemSettingsCriteria;
import com.infoepoch.pms.agent.platform.shared.exception.ValidationException;
import lombok.RequiredArgsConstructor;
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;
import java.util.Optional;

/**
 * 系统全局配置键值对仓储实现
 */
@RequiredArgsConstructor
@Repository
public class SystemSettingsRepository implements ISystemSettingsRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     */
    @Override
    public boolean insert(SystemSettings entity) {
        String sql = "INSERT INTO AI_SYSTEM_SETTINGS(KEY, VALUE, UPDATED_AT) VALUES (?, ?, ?)";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getKey(), entity.getValue(), entity.getUpdatedAt() != null ? Timestamp.valueOf(entity.getUpdatedAt()) : null);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("新增 系统全局配置键值对 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(SystemSettings entity) {
        String sql = "UPDATE AI_SYSTEM_SETTINGS SET VALUE = ?, UPDATED_AT = ? WHERE KEY = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getValue(), entity.getUpdatedAt() != null ? Timestamp.valueOf(entity.getUpdatedAt()) : null, entity.getKey());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("更新 系统全局配置键值对 数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<SystemSettings> list) {
        String sql = "INSERT INTO AI_SYSTEM_SETTINGS(KEY, VALUE, UPDATED_AT) VALUES (?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                SystemSettings item = list.get(i);
                ps.setString(++j, item.getKey());
                ps.setString(++j, item.getValue());
                ps.setTimestamp(++j, item.getUpdatedAt() != null ? Timestamp.valueOf(item.getUpdatedAt()) : null);
            }

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

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<SystemSettings> list) {
        String sql = "UPDATE AI_SYSTEM_SETTINGS SET VALUE = ?, UPDATED_AT = ? WHERE KEY = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                SystemSettings item = list.get(i);
                ps.setString(++j, item.getValue());
                ps.setTimestamp(++j, item.getUpdatedAt() != null ? Timestamp.valueOf(item.getUpdatedAt()) : null);
                ps.setString(++j, item.getKey());
            }

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

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

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

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

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

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

    @Override
    public Optional<SystemSettings> findById(String id) {
        return Optional.ofNullable(id).map(this::selectById);
    }

    @Override
    public SystemSettings save(SystemSettings entity) {
        if (entity == null) {
            return null;
        }
        if (findById(entity.getKey()).isPresent()) {
            update(entity);
        } else {
            insert(entity);
        }
        return entity;
    }

    /**
     * RowMapper
     */
    private class SystemSettingsRowMapper implements RowMapper<SystemSettings> {
        @Override
        public SystemSettings mapRow(ResultSet rs, int i) throws SQLException {
            return new SystemSettings(
                    rs.getString("KEY"),
                    rs.getString("VALUE"),
                    rs.getTimestamp("UPDATED_AT").toLocalDateTime()
            );
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(SystemSettingsCriteria 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.byKey())
            andMap.put(criteria.getKey() == null ? " KEY IS NULL " : " KEY = ? ", criteria.getKey());
        //键（LIKE）
        if (criteria.byKeyContain())
            andMap.put(" KEY LIKE ? ", "%" + criteria.getKeyContain() + "%");
        return andMap;
    }

}
