package com.simuwang.manage.service.impl.system;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.simuwang.base.common.support.MybatisPage;
import com.simuwang.base.common.support.query.PageQuery;
import com.simuwang.base.common.support.service.IService;
import com.simuwang.base.mapper.system.SysLogMapper;
import com.simuwang.base.pojo.dos.sys.SysLogDO;
import com.simuwang.base.pojo.dto.sys.LogQuery;
import com.simuwang.base.pojo.vo.sys.SysLogVO;
import com.simuwang.logging.Logging;
import com.simuwang.manage.service.system.SysLogService;
import org.springframework.stereotype.Service;

@Service
public class SysLogServiceImpl implements SysLogService {
    private final SysLogMapper mapper;

    public SysLogServiceImpl(SysLogMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public String[] selectColumns() {
        return IService.extColumns(DEFAULT_COLUMNS, "title", "id", "type", "remote_addr",
                "request_uri", "method", "params", "result", "has_exception", "execute_time", "exception");
    }

    @Override
    public <Q extends PageQuery> void wrapQuery(QueryWrapper<SysLogDO> wrapper, Q query) {
        LogQuery params = (LogQuery) query;
        wrapper.like(StrUtil.isNotBlank(params.getKeyword()), "title", params.getKeyword())
                .gt(params.getMaxId() != null, "id", params.getMaxId())
                .eq(params.getHasException() != null, "has_exception", params.getHasException())
                .between(StrUtil.isAllNotBlank(params.getBeginTime(), params.getEndTime()),
                        "updatetime", params.getBeginTime(), params.getEndTime());
    }

    @Override
    public MybatisPage<SysLogVO> convertPage(Page<SysLogDO> page, QueryWrapper<SysLogDO> wrapper) {
        IPage<SysLogDO> entityPage = this.mapper.selectPage(page, wrapper);
        return MybatisPage.ofList(entityPage, SysLogDO::toVo);
    }

    @Override
    public void asyncSave(Logging logging) {
        SysLogDO entity = new SysLogDO();
        entity.setTitle(logging.getTitle());
        entity.setType(logging.getType());
        entity.setRemoteAddr(logging.getRemoteAddr());
        entity.setRequestUri(logging.getRequestUri());
        entity.setMethod(logging.getMethod());
        entity.setParams(logging.getParams());
        entity.setResult(logging.getResult());
        entity.setHasException(logging.getHasException());
        entity.setException(logging.getException());
        entity.setExecuteTime(logging.getExecuteTime());
        this.mapper.insert(entity);
    }

    @Override
    public boolean truncate() {
        this.mapper.truncateAll();
        return true;
    }
}
