package com.awspaas.user.apps.donenow_ctt.event;

import com.actionsoft.bpms.dw.design.event.DataWindowFormatSQLEventInterface;
import com.actionsoft.bpms.dw.exec.component.DataView;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.Logger;
import com.alibaba.fastjson.JSON;

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

/**
 * 已过账服务数据窗口SQL格式化类
 * 功能：处理SEARCH_FIELD多字段模糊查询，自动补全通配符，彻底清理原单字段查询条件
 */
public class postedForm implements DataWindowFormatSQLEventInterface {
    // 日志实例（修正类名驼峰命名）
    private static final Logger LOGGER = SDK.getLogAPI().getLogger(postedForm.class);
    // 统一表名常量
    private static final String TABLE_NAME = "VIEW_EU_DNV_POSTED_SERIVE";
    // 查询参数名常量
    private static final String SEARCH_PARAM_NAME = "SEARCH_FIELD";
    // 正则匹配原SEARCH_FIELD相关条件（兼容等值/模糊、大小写、多空格）
    private static final Pattern OLD_CONDITION_PATTERN = Pattern.compile(
            "AND\\s+UPPER?\\(?\\s*" + TABLE_NAME + "\\.SEARCH_FIELD\\s*\\)?\\s+(=|like|LIKE)\\s+:" + SEARCH_PARAM_NAME,
            Pattern.CASE_INSENSITIVE
    );

    @Override
    public String formatSQL(UserContext userContext, DataView dataView, String sql) {
        try {
            Map<String, Object> sqlParam = dataView.getDatagrid().getSqlParams();
            LOGGER.info("【初始SQL】" + sql);
            LOGGER.info("【查询参数】" + JSON.toJSONString(sqlParam));

            // 初始化基础条件
            String sql1 = " 1=1 ";

            // 处理SEARCH_FIELD（多字段OR模糊查询）
            if (sqlParam.containsKey(SEARCH_PARAM_NAME)) {
                Object searchObj = sqlParam.get(SEARCH_PARAM_NAME);
                if (searchObj != null) {
                    String searchValue = searchObj.toString().trim();
                    if (!searchValue.isEmpty()) {
                        // 1. 自动补全%通配符 + 转义单引号
                        if (!searchValue.contains("%")) {
                            searchValue = "%" + searchValue + "%";
                        }
                        searchValue = searchValue.replace("'", "''");
                        sqlParam.put(SEARCH_PARAM_NAME, searchValue);
                        LOGGER.info("【处理后SEARCH_FIELD参数】" + searchValue);

                        // 2. 拼接多字段OR模糊查询条件
                        sql1 += " AND (" +
                                TABLE_NAME + ".POSTED_DATE LIKE :" + SEARCH_PARAM_NAME + " OR " +
                                TABLE_NAME + ".CONTRACT_NAME LIKE :" + SEARCH_PARAM_NAME + " OR " +
                                TABLE_NAME + ".CONTRACT_NO LIKE :" + SEARCH_PARAM_NAME + " OR " +
                                TABLE_NAME + ".ITEM_TYPE LIKE :" + SEARCH_PARAM_NAME + " OR " +
                                TABLE_NAME + ".BILL_ACCOUNT_ID LIKE :" + SEARCH_PARAM_NAME + ") ";

                        // 3. 彻底删除原SQL中所有SEARCH_FIELD相关条件（解决残留问题）
                        sql = OLD_CONDITION_PATTERN.matcher(sql).replaceAll("");
                        LOGGER.info("【删除所有旧条件后SQL】" + sql);
                    }
                }
            }

            // 替换占位符（清理多余空格）+ 修正表名
            sql = sql.replace("1=1", sql1)
                    // 清理拼接后可能出现的多余空格（如AND  AND）
                    .replaceAll("AND\\s+AND", "AND")
                    // 兼容旧表名替换（若有）
                    .replace("VIEW_EU_dnv_PENDING_RECURRING_CONTRACT", TABLE_NAME);

            // 最终SQL日志
            LOGGER.info("【拼接后最终SQL】" + sql);

        } catch (Exception e) {
            LOGGER.error("SQL拼接失败", e);
            e.printStackTrace();
        }

        return sql;
    }
}