package com.mortals.xhx.base.system.param.service.impl;

import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.IParam;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.param.dao.ParamDao;
import com.mortals.xhx.base.system.param.model.ParamEntity;
import com.mortals.xhx.base.system.param.service.ParamService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Title: 参数信息</p>
 * <p>Description: ParamServiceImpl service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author
 * @version 1.0.0
 */
@Service("paramService")
public class ParamServiceImpl extends AbstractCRUDCacheServiceImpl<ParamDao, ParamEntity, Long>
        implements ParamService {
    @Override
    protected String getCacheName() {
        return "ParamEntity.paramKey";
    }

    @Override
    public String getValueByKey(String key) {
        List<ParamEntity> list = this.getCacheList();
        Map<String, String> keyValueMap = list.parallelStream().collect(Collectors.toMap(x -> x.getParamKey(), y -> y.getParamValue(), (o, n) -> n));
        return keyValueMap.getOrDefault(key, "");
    }

    @Override
    public Long getIdByKey(String key) {
        List<ParamEntity> list = this.getCacheList();
        Map<String, Long> keyValueMap = list.parallelStream().collect(Collectors.toMap(x -> x.getParamKey(), y -> y.getId(), (o, n) -> n));
        return keyValueMap.get(key);
    }

    @Override
    public Map<String, String> getParamByFirstOrganize(String firstOrganize, String... excludeParamKeys) {
        List<ParamEntity> list = this.getCacheList();
        return list.stream()
                .filter(f -> firstOrganize.equals(f.getFirstOrganize()))
                .filter(s ->
                        !Arrays.asList(excludeParamKeys).contains(s.getParamKey())
                ).collect(Collectors.toMap(ParamEntity::getParamKey, ParamEntity::getParamValue, (o, n) -> n));
    }

    public Map<String, String> getParamBySecondOrganize(String firstOrganize, String secondOrganize, String... excludeParamKeys) {
        List<ParamEntity> list = this.getCacheList();
        return list.stream()
                .filter(f -> firstOrganize.equals(f.getFirstOrganize()))
                .filter(f -> secondOrganize.equals(f.getSecondOrganize()))
                .filter(s ->
                        !Arrays.asList(excludeParamKeys).contains(s.getParamKey())
                ).collect(Collectors.toMap(ParamEntity::getParamKey, ParamEntity::getParamValue, (o, n) -> n));
    }


    @Override
    public boolean needRefresh() {
        if (super.cacheService.isShareCache()) {
            //共享缓存如redis，不需要实时刷新
            return false;
        }
        IParam param = this.findByKey(IParam.KEY_PARAM_REFRESH_COUNT);
        if (param != null) {
            String value = StringUtils.trim(param.getParamValue());
            IParam memParam = getParamByKey(IParam.KEY_PARAM_REFRESH_COUNT);
            if (memParam == null || !value.equals(StringUtils.trim(memParam.getParamValue()))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void refresh() {
        log.info("开始初始化系统参数...");
        try {
            super.removeAllCache();
            super.loadCache();
            log.info("系统参数初始化完成！");
        } catch (Exception e) {
            log.error("查询系统参数异常", e);
        }
    }

    @Override
    public IParam findByKey(String key) throws AppException {
        return this.getCacheList().stream().filter(f -> key.equals(f.getParamKey())).findFirst().orElseGet(() -> null);
    }

    @Override
    public List<? extends IParam> findAll() throws AppException {
        return this.getCacheList();
    }

    @Override
    public boolean containsParamKey(String key) {
        List<ParamEntity> list = this.getCacheList();
        Map<String, String> keyValueMap = list.parallelStream().collect(Collectors.toMap(x -> x.getParamKey(), y -> y.getParamValue(), (o, n) -> n));
        return keyValueMap.containsKey(key);
    }

    @Override
    public IParam getParamByKey(String key) {
        List<ParamEntity> list = this.getCacheList();
        Map<String, IParam> keyValueMap = list.parallelStream().collect(Collectors.toMap(x -> x.getParamKey(), y -> y, (o, n) -> n));
        return keyValueMap.get(key);
    }

    @Override
    public String getParamValue(String key) {
        List<ParamEntity> list = this.getCacheList();
        Map<String, String> keyValueMap = list.parallelStream().collect(Collectors.toMap(x -> x.getParamKey(), y -> y.getParamValue(), (o, n) -> n));
        return keyValueMap.getOrDefault(key, "");
    }


    @Override
    public String getParamValue(String key, String defaultValue) {
        String value = getParamValue(key);
        if (StringUtils.isEmpty(value)) {
            return defaultValue;
        }
        return value;
    }

    @Override
    public int getParamIntValue(String key) {
        return DataUtil.converStr2Int(getParamValue(key), 0);
    }

    @Override
    public int getParamIntValue(String key, int defaultValue) {
        return DataUtil.converStr2Int(getParamValue(key), defaultValue);
    }

    @Override
    public long getParamLongValue(String key) {
        return DataUtil.converStr2Long(getParamValue(key), 0L);
    }

    @Override
    public long getParamLongValue(String key, long defaultValue) {
        return DataUtil.converStr2Long(getParamValue(key), defaultValue);
    }

    @Override
    public boolean getParamBooleanValue(String key) {
        String value = getParamValue(key);
        if (StringUtils.isEmpty(value)) {
            return false;
        }
        try {
            return Boolean.parseBoolean(value);
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    public boolean getParamBooleanValue(String key, boolean defaultValue) {
        String value = getParamValue(key);
        if (StringUtils.isEmpty(value)) {
            return defaultValue;
        }
        try {
            return Boolean.parseBoolean(value);
        } catch (Exception e) {
            log.debug("cannot conver key[" + key + "]'s value[" + value + "] to boolean, use default value[" + defaultValue + "]");
            return defaultValue;
        }
    }


    @Override
    protected void saveBefore(ParamEntity entity, Context context) throws AppException {
        super.saveBefore(entity, context);



    }
}