package com.hzya.frame.execsql.service;

import com.hzya.frame.datasource.DataSourceUtil;
import com.hzya.frame.execsql.entity.ExecSqlEntity;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Description 描述
 * @Author xiang2lin
 * @Date 2021/4/28 14:27
 **/
@Service(value = "ya_ExecSqlService")
@Lazy(value = false)
public class ExecSqlServiceImpl implements IExecSqlService {
    Logger logger = LoggerFactory.getLogger(ExecSqlServiceImpl.class);
    @Resource
    private SqlSession sqlSession;
    /**
     * 执行select语句
     *
     * @param sql              要执行的sql语句
     * @param data_source_code 数据源编号
     * @return
     * @throws Exception
     */
    @Override
    public List<HashMap<String, Object>> execSelectSql(String sql, String data_source_code) throws Exception {
        ExecSqlEntity entity = new ExecSqlEntity();
        entity.setSql(sql);
        entity.setDatasource_code(data_source_code);
        return execSelectSql(entity);
    }

    /**
     * 执行select语句
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public List<HashMap<String, Object>> execSelectSql(ExecSqlEntity entity) throws RuntimeException {
        List<HashMap<String, Object>> list = new ArrayList<>();
        logger.info("=============进入execSelectSql方法============");
        if (null != entity && null!=entity.getSql()) {
            //sqlsession
//            SqlSession sqlSession = getSqlSession(entity.getDatasource_code());
//            SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();
            String select_sql = entity.getSql();
            logger.info("=============execSelectSql方法要执行的sql：============" + select_sql);
            if (!select_sql.contains("update") && !select_sql.contains("delete")
                    && !select_sql.contains("insert") && !select_sql.contains("create")) {
                list = sqlSession.selectList("com.hzya.frame.execsql.entity.ExecSqlEntity.ExecSqlEntity_execsql", entity);
                logger.info("===========execSelectSql方法返回的结果条数=============" + list.size());
            }
            //sqlSession.close();
        }
        return list;
    }

    /**
     * 执行update语句
     *
     * @param sql
     * @param data_source_code
     * @return
     * @throws Exception
     */
    @Override
    public int execUpdateSql(String sql, String data_source_code) throws Exception {
        logger.info("=============进入execUpdateSql方法============");
        if (ObjectUtils.isEmpty(sql)) {
            if (sql.contains("where") || sql.contains("WHERE")) {
//                SqlSession sqlSession = getSqlSession(data_source_code);
//                SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();
                logger.info("=============execUpdateSql方法要执行的sql：============" + sql);
                ExecSqlEntity entity = new ExecSqlEntity();
                entity.setSql(sql);
                int result = sqlSession.update("com.hzya.frame.sysnew.execsql.entity.ExecSqlEntity.ExecSqlEntity_execsql_update", entity);
                logger.info("update受影响行数：" + result);
                //sqlSession.close();
                return result;
            } else {
                logger.info("=============sql语句不包含where条件============" + sql);
            }
        } else {
            logger.info("=============sql为null============");
        }
        return 0;
    }

    /**
     * 执行insert语句
     *
     * @param sql
     * @param data_source_code
     * @return
     * @throws Exception
     */
    @Override
    public int execInsertSql(String sql, String data_source_code) throws Exception {
        logger.info("=============进入execInsertSql方法============");
        if (ObjectUtils.isEmpty(sql)) {
//            SqlSession sqlSession = getSqlSession(data_source_code);
//            SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();
            logger.info("=============execInsertSql方法要执行的sql：============" + sql);
            ExecSqlEntity entity = new ExecSqlEntity();
            entity.setSql(sql);
            int result = sqlSession.insert("com.hzya.frame.sysnew.execsql.entity.ExecSqlEntity.ExecSqlEntity_execsql_insert", entity);
            logger.info("insert受影响行数：" + result);
            //sqlSession.close();
            return result;
        } else {
            logger.info("=============sql为null============");
        }
        return 0;
    }


//    private SqlSession getSqlSession(String data_source_code){
//        //sqlsession默认值
//        SqlSession sqlSession = null;
//        if (StrUtil.isNotEmpty(data_source_code)){
//            try {
//                sqlSession = DataSourceUtil.getSqlSession(data_source_code);
//            }catch (Exception e){
//                e.printStackTrace();
//                logger.info("根据数据源编号："+data_source_code+"，取sqlSession时出现异常");
//                //如果取数据源时出异常，则用默认数据源
//                sqlSession = default_sqlSession;
//            }
//        }
//        //如果取不到，用默认数据源
//        if (null == sqlSession){
//            sqlSession = default_sqlSession;
//        }
//        return sqlSession;
//    }
}
