package com.usky.sas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.sas.domain.SasSystemWlanConfig;
import com.usky.sas.mapper.SasSystemWlanConfigMapper;
import com.usky.sas.service.SasSystemWlanConfigService;
import com.usky.sas.service.vo.NetworkConfigPageRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 网络配置 服务实现
 */
@Service
public class SasSystemWlanConfigServiceImpl extends AbstractCrudService<SasSystemWlanConfigMapper, SasSystemWlanConfig>
        implements SasSystemWlanConfigService {

    @Override
    public CommonPage<SasSystemWlanConfig> page(NetworkConfigPageRequest request) {
        IPage<SasSystemWlanConfig> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<SasSystemWlanConfig> wrapper = new LambdaQueryWrapper<>();
        if (request.getName() != null && !request.getName().isEmpty()) {
            wrapper.like(SasSystemWlanConfig::getName, request.getName());
        }
        if (request.getIpAddr() != null && !request.getIpAddr().isEmpty()) {
            wrapper.like(SasSystemWlanConfig::getIpAddr, request.getIpAddr());
        }
        if (request.getStatus() != null) {
            wrapper.eq(SasSystemWlanConfig::getStatus, request.getStatus());
        }
        wrapper.orderByDesc(SasSystemWlanConfig::getUpdateTime);
        page = this.page(page, wrapper);
        return new CommonPage<>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public SasSystemWlanConfig getConfig() {
        LambdaQueryWrapper<SasSystemWlanConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.last("limit 1");
        return this.getOne(wrapper, false);
    }

    @Override
    public void updateConfig(SasSystemWlanConfig config) {
        LocalDateTime now = LocalDateTime.now();
        SasSystemWlanConfig exist = null;
        if (config.getId() != null) {
            exist = this.getById(config.getId());
        } else {
            exist = getConfig();
        }
        if (exist == null) {
            config.setCreateTime(now);
            config.setUpdateTime(now);
            this.save(config);
        } else {
            config.setId(exist.getId());
            config.setCreateTime(exist.getCreateTime());
            config.setUpdateTime(now);
            this.updateById(config);
        }
    }
}
