import com.sdtool.common.api.BusinessExecutor
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 javax.annotation.Resource

class BE_SiteContent_List implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    @Resource
    private JsonConvert jsonConvert

    @Resource
    private RedisService redisService

    @Resource
    private NoSqlKeysService keysService

    @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)

        redisInfoList.sort { v1, v2 ->
            v1.sortIndex <=> v2.sortIndex ?: v1.id <=> v2.id
        }

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