package com.prolog.eis.service.sys.impl;

import com.prolog.eis.dao.out.shelves.sys.SysParamMapper;
import com.prolog.eis.model.sys.SysParam;
import com.prolog.eis.service.sys.SysParamService;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.utils.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SysParamServiceImpl implements SysParamService {
    private final SysParamMapper sysParamMapper;

    @Override
    public List<SysParam> findAll() {
        return sysParamMapper.findByMap(null, SysParam.class);
    }

    @Override
    public List<SysParam> findNeedRefresh() {
        return sysParamMapper.findByMap(MapUtils.put("isRefresh", 1).getMap(), SysParam.class);
    }

    @Override
    public void refresh(List<SysParam> sysParams) {
        for (SysParam sysParam : sysParams) {
            sysParam.setIsRefresh(0);
            sysParam.setUpdateTime(LocalDateTime.now());
            sysParamMapper.update(sysParam);
        }
    }

    @Override
    public void updateSysParam(String paramNo, String paramValue) {
        Criteria criteria = Criteria.forClass(SysParam.class);
        criteria.restrictionBuilder().eq(SysParam::getParamNo, paramNo).build();
        sysParamMapper.updateMapByCriteria(MapUtils.put("paramValue", paramValue).put("isRefresh", 1).getMap(), criteria);
    }

    @Override
    public String findVal(String paramNo, String defaultParamValue) {
        Criteria criteria = Criteria.forClass(SysParam.class);
        criteria.restrictionBuilder().eq(SysParam::getParamNo, paramNo).build();
        SysParam sysParam = sysParamMapper.findByCriteria(criteria).stream().findFirst().orElse(null);
        if (sysParam == null) {
            return defaultParamValue;
        } else {
            return sysParam.getParamValue();
        }
    }

    @Override
    public String findValFromList(List<SysParam> paramList, String paramNo, String defaultParamValue) {
        SysParam sysParam = paramList.stream().filter(r -> r.getParamNo().equals(paramNo)).findFirst().orElse(null);
        if (sysParam == null) {
            return defaultParamValue;
        } else {
            return sysParam.getParamValue();
        }
    }
}
