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 testcommission implements DataWindowFormatSQLEventInterface {
    private static final Logger LOGGER = SDK.getLogAPI().getLogger(testcommission.class);

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

            if (sqlParam.containsKey("ITEM_DATE") && sql.contains("a.ITEM_DATE")) {
                sql1 += " AND UPPER(d.ITEM_DATE) like :ITEM_DATE ";
                sql = sql.replace("AND UPPER(a.ITEM_DATE) like :ITEM_DATE", "");
            }

            if (sqlParam.containsKey("POSTED_DATE")) {
                sql1 += " AND d.POSTED_DATE = :POSTED_DATE ";
                sql = sql.replace("AND d.POSTED_DATE like :POSTED_DATE", "");

            }

            if (sqlParam.containsKey("ACCOUNT_ID")) {
                sql1 += " AND d.ACCOUNT_ID = :ACCOUNT_ID ";
                sql = sql.replace("AND d.ACCOUNT_ID like :ACCOUNT_ID", "");
            }

            if (sqlParam.containsKey("BILL_ACCOUNT_ID")) {
                sql1 += " AND d.BILL_ACCOUNT_ID = :BILL_ACCOUNT_ID ";
                sql = sql.replace("AND d.BILL_ACCOUNT_ID like :BILL_ACCOUNT_ID", "");
            }

            if (sqlParam.containsKey("ACCOUNT_MANAGER_ID")) {
                sql1 += " AND d.ACCOUNT_MANAGER_ID = :ACCOUNT_MANAGER_ID ";
                sql = sql.replace("AND d.ACCOUNT_MANAGER_ID like :ACCOUNT_MANAGER_ID", "");
            }

            if (sqlParam.containsKey("ITEM_TYPE")) {
                sql1 += " AND d.ITEM_TYPE = :ITEM_TYPE ";
                sql = sql.replace("AND d.ITEM_TYPE like :ITEM_TYPE", "");
            }


            sql = sql.replace("2 = 2", sql1);
            LOGGER.info("【拼接后SQL】" + sql);

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

        return sql;
    }
}