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

import com.prolog.eis.controller.sys.SystemPageReqDTO;
import com.prolog.eis.dao.SysParamMapper;
import com.prolog.eis.enums.base.BaseVisitEnum;
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;
import java.util.Objects;

@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 Long updateSysParam(String paramNo, String paramValue) {
        Criteria criteria = Criteria.forClass(SysParam.class);
        criteria.restrictionBuilder().eq(SysParam::getParamNo, paramNo).build();
        return sysParamMapper.updateMapByCriteria(MapUtils.put("paramValue", paramValue).put("isRefresh", 1).getMap(), criteria);
    }

    @Override
    public List<SysParam> findPageList(SystemPageReqDTO pageParam) {
        Criteria criteria = Criteria.forClass(SysParam.class);
        criteria.restrictionBuilder().like(SysParam::getParamNo, "%" + pageParam.getParamNo() + "%", Objects::nonNull).eq(SysParam::getIsVisit, BaseVisitEnum.VISIBLE.getCode()).build();
        List<SysParam> list = sysParamMapper.findByCriteria(criteria);
        return list;
    }

    @Override
    public void updateSysParamById(SysParam sysParam) {
        sysParamMapper.updateMapById(sysParam.getId(), MapUtils.put("paramValue", sysParam.getParamValue())
                .put("paramDesc", sysParam.getParamDesc()).put("updateTime", LocalDateTime.now()).put("isRefresh", 1).getMap(), SysParam.class);
    }

    @Override
    public void add(SysParam sysParam) {
        sysParam.setCreateTime(LocalDateTime.now());
        long save = sysParamMapper.save(sysParam);
    }

    @Override
    public void delete(Integer id) {
        sysParamMapper.deleteById(id, SysParam.class);
    }
}
