package com.chuanxia.mcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuanxia.mcp.bean.dto.UaQueryDto;
import com.chuanxia.mcp.bean.model.CdnUa;
import com.chuanxia.mcp.bean.vo.Result;
import com.chuanxia.mcp.mapper.CdnUaMapper;
import com.chuanxia.mcp.service.CdnUaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
@Slf4j
public class CdnUaServiceImpl extends ServiceImpl<CdnUaMapper, CdnUa> implements CdnUaService {
    private final CdnUaMapper cdnUaMapper;

    @Override
    public Result<IPage<CdnUa>> listPage(UaQueryDto queryDto) {
        IPage<CdnUa> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        LambdaQueryWrapper<CdnUa> query = Wrappers.lambdaQuery();
        String browser = queryDto.getBrowser();
        String browserVersion = queryDto.getBrowserVersion();
        String device = queryDto.getDevice();
        Integer level = queryDto.getLevel();
        String os = queryDto.getOs();

        if (StringUtils.isNotBlank(browser)) {
            query.eq(CdnUa::getBrowser, browser);
        }
        if (StringUtils.isNotBlank(browserVersion)) {
            query.eq(CdnUa::getBrowserVersion, browserVersion);
        }
        if (StringUtils.isNotBlank(os)) {
            query.eq(CdnUa::getOs, os);
        }
        if (level != null) {
            query.eq(CdnUa::getLevel, level);
        }
        page = cdnUaMapper.selectPage(page, query);
        return Result.success(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<String> saveUa(CdnUa ua) {
        cdnUaMapper.insert(ua);
        return Result.success("操作成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateUa(CdnUa ua) {
        cdnUaMapper.updateById(ua);
        return Result.success("操作成功");
    }
}
