package com.roma.romaapi.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


// 执行具体sql语句
@Repository
public class DbApiDao {

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    // 通过code,获取要执行的sql
    public Map<String, Object> dbQueryForMap(String sqlCode) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("sql_code", sqlCode);
            Map<String, Object> resMap2 = namedParameterJdbcTemplate.queryForMap(
                        "SELECT * FROM `sql_details` where sql_code = :sql_code AND is_enable=1", paramMap);
            return  resMap2;
        } catch (EmptyResultDataAccessException e) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("sysErrorCode", "500");

            return resultMap;
        }
    }

    // 获取sql总数,需要完整的sql和要绑定的参数
    public Integer dbCountQueryForObject(String sql, Map bindValue) {
        Integer count = namedParameterJdbcTemplate.queryForObject(sql, bindValue, Integer.class);

        return  count;
    }

    // 获取查询数据--单条数据使用
    public Map dbCustomQueryForMap(String sql, Map bindValue) {
        try {
            Map<String, Object> resMap2 = namedParameterJdbcTemplate.queryForMap(sql, bindValue);
            return  resMap2;
        } catch (EmptyResultDataAccessException e) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("sysErrorCode", "500");

            return resultMap;
        }
    }

    // 查询数据--多条数据使用
    public List<Map<String, Object>> dbCustomQueryForList(String sql, Map<String, Object> bindValue){
        System.out.println("sql-----"+sql);
        System.out.println("bindvalue------------"+bindValue);
        List<Map<String, Object>> resMap2 = namedParameterJdbcTemplate.queryForList(sql, bindValue);
        return  resMap2;
    }

    // 执行增删改语句
    public Integer dbUpdate(String sql, Map<String, Object> bindValue){
        System.out.println("sql-----"+sql);
        System.out.println("bindvalue------------"+bindValue);
        Integer row = namedParameterJdbcTemplate.update(sql, bindValue);
        return  row;
    }
}
