import com.sdtool.common.api.BusinessExecutor
import com.sdtool.common.api.ConfigService
import com.sdtool.common.datas.ERPModule
import com.sdtool.common.datas.TokenUserFrom
import com.sdtool.common.entity.base.InvokeCallParams
import com.sdtool.common.entity.base.InvokeCallResult
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONWriter
import com.dySweetFishPlugin.sql.dao.OperatorWait
import com.sweetfish.service.RetResult
import groovy.json.JsonSlurper

import javax.annotation.Resource

class BE_SiteConfig_Save implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    @Resource(name = "APP_HOME")
    private String appHome

    @Resource
    private ConfigService configService

    @Override
    String scriptName() {
        return "保存网站配置"
    }

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

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

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

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

        //直接存source.params有些编码上的问题，改用fastjson中转一下
        String configJson = JSON.toJSONString(invokeData, JSONWriter.Feature.PrettyFormat)

        String fileName = "default_SiteConfig.json"

        if (source.currentUser.userFrom == TokenUserFrom.PC_MALL_FRONT.value) {
            fileName = source.currentUser.id + "_SiteConfig.json"
        } else if (invokeData.containsKey('_siteHost_') && invokeData._siteHost_ != null && invokeData._siteHost_.trim()) {
            fileName = invokeData._siteHost_ + "_SiteConfig.json"
        }

        def siteConfigFile = new File(appHome + File.separator +
                "conf" + File.separator +
                "script" + File.separator +
                source.supplierCode + File.separator +
                "config" + File.separator +
                fileName)

        siteConfigFile.setText(configJson, "UTF-8")

        //清一下read的缓存
        configService.reloadScriptCache("SiteConfig_Read", ERPModule.CONFIG, source.dataSourceId, source.supplierCode)

        return RetResult.<InvokeCallResult> successT().result(
                InvokeCallResult.success().data("")
        )
    }
}


