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 commissionAgentPayDWFormatSQLEvent implements DataWindowFormatSQLEventInterface {
    private static final Logger LOGGER = SDK.getLogAPI().getLogger(commissionAgentPayDWFormatSQLEvent.class);//记录日志

    /**
     *sql格式化
     * @param userContext
     * @param dataView
     * @param sql
     * @return
     */
    @Override
    public String formatSQL(UserContext userContext, DataView dataView, String sql) {
        try {
            Map<String, Object> sqlParam = dataView.getDatagrid().getSqlParams();

            if (sqlParam.containsKey("COMMISSION_PAY_ID") && sqlParam.get("COMMISSION_PAY_ID") != null) {
                String COMMISSION_PAY_ID = sqlParam.get("COMMISSION_PAY_ID").toString();

                LOGGER.info("COMMISSION_PAY_ID:" + COMMISSION_PAY_ID);
                LOGGER.info("改之前sql:" + sql);
                LOGGER.info(JSON.toJSONString(sqlParam));

                if (sqlParam.containsKey("ZB_FEE_DATE") && sqlParam.get("ZB_FEE_DATE") != null) {
                    sqlParam.put("ZB_FEE_DATE", "%%");
                }

                //COMMISSION_PAY_ID 只能是字母 数字 横线 下划线 逗号 组成，其他都要报错
                if (!COMMISSION_PAY_ID.matches("[a-zA-Z0-9\\-_,]+")) {
                    throw new Exception("COMMISSION_PAY_ID只能是字母 数字 横线 下划线 逗号 组成的");
                }

                sql = sql.replace(" COMMISSION_PAY_ID = :COMMISSION_PAY_ID", "(COMMISSION_PAY_ID = :COMMISSION_PAY_ID OR FIND_IN_SET(ID,'" + COMMISSION_PAY_ID + "')>0)");


                LOGGER.info("改之后sql:" + sql);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sql;
    }
}
