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;

public class testForm implements DataWindowFormatSQLEventInterface {
    private static final Logger LOGGER = SDK.getLogAPI().getLogger(testForm.class);
    // 统一表名（全大写，和FROM中的表名一致）
    private static final String TABLE_NAME = "VIEW_EU_DNV_PENDING_RECURRING_CONTRACT";

    @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));

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

                // 2. 处理ITEM_MONTH
            if (sqlParam.containsKey("ITEM_MONTH")) {
                String itemMonth = sqlParam.get("ITEM_MONTH").toString().trim();
                if (!itemMonth.isEmpty()) {
                    sql1 += " AND " + TABLE_NAME + ".ITEM_MONTH LIKE :ITEM_MONTH ";
                    sql = sql.replace("AND UPPER(" + TABLE_NAME + ".ITEM_MONTH) like :ITEM_MONTH", "");
                }
            }

            // 3. 处理SEARCH_FIELD（多字段OR）
            if (sqlParam.containsKey("SEARCH_FIELD")) {
                String searchValue = sqlParam.get("SEARCH_FIELD").toString().trim();
                if (!searchValue.isEmpty()) {
                    if (!searchValue.contains("%")) {
                        searchValue = "%" + searchValue + "%";
                    }
                    searchValue = searchValue.replace("'", "''");
                    sqlParam.put("SEARCH_FIELD", searchValue);

                    sql1 += " AND (" +
                            TABLE_NAME + ".ACCOUNT_NAME LIKE :SEARCH_FIELD OR " +
                            TABLE_NAME + ".CONTRACT_NAME LIKE :SEARCH_FIELD OR " +
                            TABLE_NAME + ".NO LIKE :SEARCH_FIELD OR " +
                            TABLE_NAME + ".ITEM_SUBCATE_ID LIKE :SEARCH_FIELD OR " +
                            TABLE_NAME + ".BILL_ACCOUNT_ID LIKE :SEARCH_FIELD) ";
                    sql = sql.replace("AND " + TABLE_NAME + ".SEARCH_FIELD = :SEARCH_FIELD", "");
                }
            }

            // 4. 替换占位符，并修复ORDER BY表名大小写
            sql = sql.replace("1=1", sql1)
                    // 统一ORDER BY中的表名（全大写）
                    .replace("VIEW_EU_dnv_PENDING_RECURRING_CONTRACT", TABLE_NAME);

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

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

        return sql;
    }
}