package com.qmth.exam.reserve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.core.exception.StatusException;
import com.qmth.exam.reserve.dao.SystemPropertyDao;
import com.qmth.exam.reserve.entity.SystemPropertyEntity;
import com.qmth.exam.reserve.service.SystemPropertyService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class SystemPropertyServiceImpl extends ServiceImpl<SystemPropertyDao, SystemPropertyEntity> implements SystemPropertyService {

    private static final Logger log = LoggerFactory.getLogger(SystemPropertyServiceImpl.class);

    @Override
    public SystemPropertyEntity findByPropKey(Long orgId, String propKey) {
        LambdaQueryWrapper<SystemPropertyEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemPropertyEntity::getPropKey, propKey);
        if (orgId != null) {
            wrapper.eq(SystemPropertyEntity::getOrgId, orgId);
        }
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public boolean existPropValue(Long orgId, String propKey, String propValue) {
        LambdaQueryWrapper<SystemPropertyEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemPropertyEntity::getOrgId, orgId);
        wrapper.eq(SystemPropertyEntity::getPropKey, propKey);
        wrapper.eq(SystemPropertyEntity::getPropValue, propValue);
        return baseMapper.selectCount(wrapper) > 0;
    }

    @Override
    public void updatePropValue(Long orgId, String propKey, String propValue) {
        if (orgId == null) {
            throw new StatusException("orgId值不能为空");
        }
        if (StringUtils.isBlank(propKey)) {
            throw new StatusException("propKey值不能为空");
        }

        LambdaQueryWrapper<SystemPropertyEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemPropertyEntity::getOrgId, orgId);
        wrapper.eq(SystemPropertyEntity::getPropKey, propKey);

        SystemPropertyEntity systemProperty = baseMapper.selectOne(wrapper);
        if (systemProperty == null) {
            systemProperty = new SystemPropertyEntity();
            systemProperty.setOrgId(orgId);
            systemProperty.setPropKey(propKey);
            systemProperty.setPropValue(propValue);
            systemProperty.setCreateTime(System.currentTimeMillis());
            systemProperty.setUpdateTime(System.currentTimeMillis());
            baseMapper.insert(systemProperty);
        } else {
            systemProperty.setPropValue(propValue);
            systemProperty.setUpdateTime(System.currentTimeMillis());
            baseMapper.updateById(systemProperty);
        }
    }

}
