import com.sdtool.common.api.BusinessExecutor
import com.sdtool.common.datas.ERPModule
import com.sdtool.common.entity.base.InvokeCallParams
import com.sdtool.common.entity.base.InvokeCallResult
import com.alibaba.fastjson2.JSON
import com.dySweetFishPlugin.sql.dao.OperatorWait
import com.dySweetFishPlugin.sql.dao.TunaDaoService
import com.sweetfish.service.RetResult
import groovy.json.JsonSlurper
import org.apache.commons.lang3.StringUtils
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger

import javax.annotation.Resource

@SuppressWarnings("unused")
class BE_System_SqlErrorGet implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    protected final Logger logger = LogManager.getLogger(this.getClass().getSimpleName())

    @Resource
    private TunaDaoService daoService

    @Override
    String scriptName() {
        return "获取错误的SQL数据"
    }

    @Override
    ERPModule module() {
        return ERPModule.SYSTEM
    }

    @Override
    OperatorWait getAWait(InvokeCallParams s) {
        return OperatorWait.SYNC
    }

    @Override
    boolean needLogin(InvokeCallParams source) {
        return true
    }

    RetResult<InvokeCallResult> execute(InvokeCallParams source) {
        def jsonSlurper = new JsonSlurper()
        def invokeData = jsonSlurper.parseText(source.params)

        String sqlKey = invokeData["errorKey"]
        if (StringUtils.isNotBlank(sqlKey)) {
            try {
                //尝试处理下参数化的sql
                String sqlJsonStr = daoService.getErrorSql(sqlKey)
                def sqlJson = jsonSlurper.parseText(sqlJsonStr)
                sqlJson.successList.each { item ->
                    item.sql = item.sql.replaceAll('\n', ' ')
                    item.beans.each { bean ->
                        bean.each { key, value ->
                            def replacement = value instanceof String ? "'${value}'" : value.toString()
                            item.sql = item.sql.replaceAll("(?i)#\\{${key}\\}", replacement)
                        }
                    }
                }
                return RetResult.<InvokeCallResult> successT().result(InvokeCallResult.success().data(JSON.toJSONString(sqlJson)))
            } catch (Exception e) {
                return RetResult.<InvokeCallResult> successT().result(InvokeCallResult.success().data(daoService.getErrorSql(sqlKey)))
            }
        } else {
            return RetResult.<InvokeCallResult> errorT().retinfo("无效的数据")
        }

    }
}
