package com.sundot.airport.system.service.impl;

import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.system.domain.SysDynamicSql;
import com.sundot.airport.system.mapper.SysDynamicSqlMapper;
import com.sundot.airport.system.service.ISysDynamicSqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 动态sql执行configService业务层处理
 *
 * @author ruoyi
 * @date 2025-06-20
 */
@Service
public class SysDynamicSqlServiceImpl implements ISysDynamicSqlService
{
    @Autowired
    private SysDynamicSqlMapper sysDynamicSqlMapper;

    /**
     * 查询动态sql执行config
     *
     * @param id 动态sql执行config主键
     * @return 动态sql执行config
     */
    @Override
    public SysDynamicSql selectSysDynamicSqlById(Long id)
    {
        return sysDynamicSqlMapper.selectSysDynamicSqlById(id);
    }

    /**
     * 查询动态sql执行config列表
     *
     * @param sysDynamicSql 动态sql执行config
     * @return 动态sql执行config
     */
    @Override
    public List<SysDynamicSql> selectSysDynamicSqlList(SysDynamicSql sysDynamicSql)
    {
        return sysDynamicSqlMapper.selectSysDynamicSqlList(sysDynamicSql);
    }

    /**
     * 新增动态sql执行config
     *
     * @param sysDynamicSql 动态sql执行config
     * @return 结果
     */
    @Override
    public int insertSysDynamicSql(SysDynamicSql sysDynamicSql)
    {
        sysDynamicSql.setCreateTime(DateUtils.getNowDate());
        return sysDynamicSqlMapper.insertSysDynamicSql(sysDynamicSql);
    }

    /**
     * 修改动态sql执行config
     *
     * @param sysDynamicSql 动态sql执行config
     * @return 结果
     */
    @Override
    public int updateSysDynamicSql(SysDynamicSql sysDynamicSql)
    {
        sysDynamicSql.setUpdateTime(DateUtils.getNowDate());
        return sysDynamicSqlMapper.updateSysDynamicSql(sysDynamicSql);
    }

    /**
     * 批量删除动态sql执行config
     *
     * @param ids 需要删除的动态sql执行config主键
     * @return 结果
     */
    @Override
    public int deleteSysDynamicSqlByIds(Long[] ids)
    {
        return sysDynamicSqlMapper.deleteSysDynamicSqlByIds(ids);
    }

    /**
     * 删除动态sql执行config信息
     *
     * @param id 动态sql执行config主键
     * @return 结果
     */
    @Override
    public int deleteSysDynamicSqlById(Long id)
    {
        return sysDynamicSqlMapper.deleteSysDynamicSqlById(id);
    }


    @Override
    public List<Map<String, Object>> executeSqlByKeyAndParam(String sqlkey, Map<String, Object> params) {
        // 预处理SQL，将参数替换为MyBatis的参数格式
        SysDynamicSql sysDynamicSql = sysDynamicSqlMapper.selectBySqlKey(sqlkey);
        if (sysDynamicSql == null) {
            return null;
        }
        String processedSql = processSqlWithParams(sysDynamicSql.getSqlContent(), params);
        return sysDynamicSqlMapper.executeDynamicSelect(processedSql, params);
    }

    private String processSqlWithParams(String sql, Map<String, Object> params) {
        if (sql == null || params == null || params.isEmpty()) {
            return sql;
        }

        // 处理命名参数格式（如 :paramName 或 ${paramName}）
        Pattern pattern = Pattern.compile("(:\\w+|\\$\\{\\w+\\})");
        Matcher matcher = pattern.matcher(sql);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String placeholder = matcher.group(1);
            String paramName;

            if (placeholder.startsWith(":")) {
                paramName = placeholder.substring(1); // 去掉冒号
            } else {
                paramName = placeholder.substring(2, placeholder.length() - 1); // 去掉 ${ 和 }
            }

            if (params.containsKey(paramName)) {
                // 替换为 MyBatis 参数格式 #{params.paramName}
                matcher.appendReplacement(sb, "#{params." + paramName + "}");
            } else {
                // 参数不存在，保留原样（或可以抛出异常）
                matcher.appendReplacement(sb, placeholder);
            }
        }
        matcher.appendTail(sb);

        return sb.toString();
    }
}
