package com.hys.app.service.base.service.impl;

import com.hys.app.model.base.CachePrefix;
import com.hys.app.model.base.vo.ConfigItem;
import com.hys.app.service.base.plugin.validator.ValidatorPlugin;
import com.hys.app.service.base.service.ValidatorManager;
import com.hys.app.model.system.vo.ValidatorPlatformVO;
import com.hys.app.service.system.factory.ValidatorFactory;
import com.hys.app.framework.cache.Cache;
import com.hys.app.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 验证相关接口实现
 * @author duanmingyu
 * @version v1.0
 * @since v7.1.6
 * 2019-12-18
 */
@Service
public class ValidatorManagerImpl implements ValidatorManager {

    @Autowired
    private ValidatorFactory validatorFactory;

    @Autowired
    private Cache cache;

    @Override
    @Transactional(value = "systemTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void validate() {
        ValidatorPlugin platform = validatorFactory.getValidatorPlugin();
        platform.onValidate(this.getConfig());
    }

    /**
     * 将json参数转换为map格式
     *
     * @return 验证平台参数
     */
    private Map getConfig() {
        ValidatorPlatformVO validatorPlatformVO = ((ValidatorPlatformVO) this.cache.get(getValidatorPlatformKey()));
        List<ConfigItem> list = validatorPlatformVO.getConfigItems();

        Map<String, String> result = new HashMap<>(16);

        if (list != null && list.size() != 0) {
            for (ConfigItem item : list) {
                result.put(item.getName(), StringUtil.toString(item.getValue()));
            }
        }
        return result;

    }

    protected String getValidatorPlatformKey() {
        return CachePrefix.VALIDATOR_PLATFORM.getPrefix();
    }

}
