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.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.JsonUtils;
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());
    }

    @Override
    public Long exportAdd(SysUserFileRecord fileRecord){
        fileRecord.setUserId(LoginHelper.getUserId());
        baseMapper.insert(fileRecord);
        return fileRecord.getId();
    }

    @Override
    public AjaxResult exportBack(JSONObject object) {
        if (object==null||object.get("url")==null||object.get("uniqueCode")==null){
            return AjaxResult.error("回调参数异常："+object.toString());
        }
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setId( Long.valueOf(object.get("uniqueCode").toString()));
        fileRecord.setUrl(object.get("url").toString());
        fileRecord.setStatus(0);
        baseMapper.updateById(fileRecord);
        log.info("导出回调成功："+object.toString());
        return AjaxResult.success();
    }
}
