import Ignore_ReadUTF8File as ReadUTF8File
import com.sdtool.common.api.BusinessExecutor
import com.sdtool.common.api.NoSqlKeysService
import com.sdtool.common.api.SupplierInitService
import com.sdtool.common.datas.RedisKeys
import com.sdtool.common.entity.doc.BusinessScript
import com.sdtool.common.tool.ERPUtils
import com.dySweetFishPlugin.redis.RedisService
import groovy.io.FileType
import org.apache.commons.io.FilenameUtils
import org.apache.logging.log4j.Logger
import org.codehaus.groovy.control.CompilationFailedException

import java.lang.reflect.InvocationTargetException

static def fillBusinessScript(String directoryName, int commonFlag, String appHome, SupplierInitService supplierService, RedisService redisService, NoSqlKeysService keysService, Logger logger, String dataSourceId, long supplierCode) {
    File directoryScript = new File(directoryName)
    if (!directoryScript.exists()) {
        directoryScript.mkdirs()
    }

    directoryScript.eachFileRecurse(FileType.FILES, { x ->
        String code = FilenameUtils.getBaseName(x.getName())
        if (code.startsWith("BE_")) {
            code = code.substring(3)
            if (!redisService.hexists(keysService.getRedisKey(RedisKeys.KEY_BUSINESSSCRIPT, supplierCode), code)) {
                //读取脚本信息
                try (GroovyClassLoader groovyCl = new GroovyClassLoader(supplierService.getClass().getClassLoader(), ERPUtils.buildERPGroovyConfig())) {
                    //添加公共commons目录
                    groovyCl.addClasspath(appHome + File.separator + "conf" + File.separator + "script" + File.separator + 0 + File.separator + "commons")
                    //添加当前目录
                    groovyCl.addClasspath(x.getParent().toString())

                    String fileStr = ReadUTF8File.execute(x.toPath(), false, logger)

                    Class groovyClass = groovyCl.parseClass(fileStr, "BE_" + code + "_" + supplierCode + ".groovy")
                    BusinessExecutor p = (BusinessExecutor) groovyClass.getDeclaredConstructor().newInstance()
                    BusinessScript businessScript = BusinessScript.newBuilder()
                            .businessName(p.scriptName())
                            .businessCode(code)
                            .businessModule(p.module().getValue())
                            .systemFlag(1)
                            .commonFlag(commonFlag)
                            .build()
                    supplierService.addBusinessScriptLocal(businessScript, dataSourceId, supplierCode)

                    groovyCl.clearCache()
                } catch (IOException | CompilationFailedException | ClassCastException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    logger.error(e.getMessage(), e)
                }
            }
        }
    })
}

static def createRunnable(String appHome, SupplierInitService supplierService, RedisService redisService, NoSqlKeysService keysService, Logger logger, String dataSourceId, long supplierCode) {
    //2024-10-05 tt 脚本分为公共脚本和私有脚本，放在0目录下的为公共脚本，supplierCode下的为私有脚本，均需要写入数据库

    logger.info("初始化脚本开始=====" + supplierCode)
    String directoryName = appHome + File.separator +
            "conf" + File.separator +
            "script" + File.separator +
            0 + File.separator

    fillBusinessScript(directoryName, 1, appHome, supplierService, redisService, keysService, logger, dataSourceId, supplierCode)

    directoryName = appHome + File.separator +
            "conf" + File.separator +
            "script" + File.separator +
            supplierCode + File.separator

    fillBusinessScript(directoryName, 0, appHome, supplierService, redisService, keysService, logger, dataSourceId, supplierCode)

    logger.info("初始化脚本结束=====" + supplierCode)
}

//groovy最后一个表达式的值为返回
createRunnable(appHome, supplierService, redisService, keysService, logger, dataSourceId, supplierCode)
