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;

/**
 * 采购已付款 - 服务周期重合查询（强制生效版）
 * 核心：只要参数存在就强制替换，放弃所有格式校验
 */
public class PeriodForm implements DataWindowFormatSQLEventInterface {
    private static final Logger LOGGER = SDK.getLogAPI().getLogger(PeriodForm.class);
    private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");

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

            String standardSql = WHITESPACE_PATTERN.matcher(sql).replaceAll(" ").trim();
            LOGGER.info("【周期查询】标准化SQL：" + standardSql);

            if (sqlParams.containsKey("PERIOD_BEGIN_DATE") && sqlParams.containsKey("PERIOD_BEGIN_DATE0")) {
                String oldCondition = "AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE >= :PERIOD_BEGIN_DATE AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE <= :PERIOD_BEGIN_DATE0";
                standardSql = standardSql.replace(oldCondition, "");

                standardSql = standardSql.replace(" AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE >= :PERIOD_BEGIN_DATE", "");
                standardSql = standardSql.replace(" AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE <= :PERIOD_BEGIN_DATE0", "");

                String newCondition = "AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE <= :PERIOD_BEGIN_DATE0 AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_END_DATE >= :PERIOD_BEGIN_DATE";

                if (standardSql.contains("AND 1=1")) {
                    standardSql = standardSql.replace("AND 1=1", "AND 1=1 " + newCondition);
                } else {
                    standardSql += " " + newCondition;
                }


                LOGGER.info("周期查询替换完成，中间SQL：" + standardSql);
            }

            String finalSql = standardSql
                    .replace(" FROM ", "\nFROM ")
                    .replace(" WHERE ", "\nWHERE ")
                    .replace(" AND orgid = ", "\nAND orgid = ")
                    .replace(" AND 1=1", "\nAND 1=1")
                    .replace(" AND VIEW_EU_DNV_PAYMENT_PLAN.PLAN_DATE", "\nAND VIEW_EU_DNV_PAYMENT_PLAN.PLAN_DATE")
                    .replace(" AND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE", "\nAND VIEW_EU_DNV_PAYMENT_PLAN.PERIOD_BEGIN_DATE");

            LOGGER.info("周期查询最终SQL：" + finalSql);
            return finalSql;

        } catch (Exception e) {
            LOGGER.error("周期查询SQL格式化失败", e);
            return sql;
        }
    }
}