package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.helper.LoginHelper;
import com.dsk.system.domain.SysUserFileRecord;
import com.dsk.system.mapper.SysUserFileRecordMapper;
import com.dsk.system.service.ISysUserFileRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 用户文件记录
 *
 * @author lcl
 * @create 2023/9/15
 */
@Slf4j
@Service
public class SysUserFileRecordServiceImpl implements ISysUserFileRecordService
{

    @Resource
    private SysUserFileRecordMapper baseMapper;

    @Override
    public TableDataInfo<SysUserFileRecord> userList(PageQuery page)
    {
        return TableDataInfo.build(
                baseMapper.selectPage(page.build(), Wrappers.<SysUserFileRecord>lambdaQuery()
                        .eq(SysUserFileRecord::getUserId, LoginHelper.getUserId())
                        .eq(SysUserFileRecord::getType, 1)
                        .ge(SysUserFileRecord::getCreateTime, DateUtil.offsetDay(new Date(), -30))
                        .orderByDesc(SysUserFileRecord::getCreateTime))
        );
    }

    @Override
    public boolean add(SysUserFileRecord bean)
    {
        dataVerify(bean);
        return baseMapper.insert(bean) != 0;
    }

    private void dataVerify(SysUserFileRecord bean)
    {
        if(ObjectUtils.isEmpty(bean.getUrl())) throw new BeanException("文件存储链接不能为空！");
        if(ObjectUtils.isEmpty(bean.getFileName())) throw new BeanException("文件名称不能为空！");
        if(ObjectUtils.isEmpty(bean.getType())) throw new BeanException("文件类型不能为空！");
        bean.setUserId(LoginHelper.getUserId());
    }
}
