

package com.zcloud.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcloud.common.utils.PageUtils;
import com.zcloud.common.utils.Query;
import com.zcloud.modules.sys.dao.SysLogDao;
import com.zcloud.modules.sys.entity.SysLogEntity;
import com.zcloud.modules.sys.service.SysLogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;


@Service("sysLogService")
public class SysLogServiceImpl extends ServiceImpl<SysLogDao, SysLogEntity> implements SysLogService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String)params.get("key");

        IPage<SysLogEntity> page = this.page(
            new Query<SysLogEntity>().getPage(params),
            new QueryWrapper<SysLogEntity>().like(StringUtils.isNotBlank(key),"username", key)
        );

        return new PageUtils(page);
    }

    @Override
    public void saveLog(SysLogEntity logEntity) {
        logEntity.setCreateDate(new Date());
        //计算表名
        String tableName = buildTableName(Calendar.getInstance().get(Calendar.YEAR));
        //如果表不存在，则创建
        if (!baseMapper.existsTable(tableName)){
            baseMapper.createTable(tableName);
        }
        //将日志插入到对应的表中
        baseMapper.insertIntoTable(logEntity, tableName);
    }

    private String buildTableName(int year) {
        // 构造表名
        return "sys_log_" + year;
    }
}
