import com.sdtool.common.api.BusinessExecutor
import com.sdtool.common.api.ConfigService
import com.sdtool.common.api.NoSqlKeysService
import com.sdtool.common.datas.ERPModule
import com.sdtool.common.datas.RedisKeys
import com.sdtool.common.entity.base.InvokeCallParams
import com.sdtool.common.entity.base.InvokeCallResult
import com.sdtool.common.entity.site.SiteContent
import com.dySweetFishPlugin.redis.RedisService
import com.dySweetFishPlugin.sql.dao.OperatorWait
import com.google.common.collect.Lists
import com.sweetfish.convert.json.JsonConvert
import com.sweetfish.service.RetResult
import org.apache.commons.lang3.StringUtils

import javax.annotation.Resource

class BE_SiteContent_Select implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    @Resource
    private JsonConvert jsonConvert

    @Resource
    private RedisService redisService

    @Resource
    private NoSqlKeysService keysService

    @Resource
    private ConfigService configService

    @Override
    String scriptName() {
        return "网站内容选取"
    }

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

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

    private <T> List<T> getRedisDocInfos(String redisKey, Class<T> resultClazz) {
        Map<String, String> docMap = redisService.hgetAll(redisKey)
        List<T> result = Lists.newLinkedList()
        docMap.forEach((key, value) -> result.add(jsonConvert.convertFrom(resultClazz, value)))

        return result
    }

    RetResult<InvokeCallResult> execute(InvokeCallParams source) {
        List<SiteContent> redisInfoList = getRedisDocInfos(keysService.getRedisKey(RedisKeys.KEY_SITE_CONTENT, source.supplierCode), SiteContent.class)


        SiteContent searchContent = jsonConvert.convertFrom(SiteContent.class, source.params)

        SiteContent siteContent = redisInfoList.find { StringUtils.equalsIgnoreCase(it.groupName, searchContent.groupName) && StringUtils.equalsIgnoreCase(it.caption, searchContent.caption) }

        if (siteContent == null) {
            return RetResult.<InvokeCallResult> errorT().retinfo("无效的网站内容信息")
        }

        SiteContent cacheContent = configService.getCacheSiteContentInfo(siteContent.id, source.supplierCode)
        if (cacheContent != null) {
            siteContent.content = cacheContent.content
        }

        return RetResult.<InvokeCallResult> successT().result(
                InvokeCallResult.success().data(jsonConvert.convertTo(siteContent))
        )
    }
}

