package top.continew.admin.business.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import top.continew.admin.business.mapper.TaskInfoMapper;
import top.continew.admin.business.model.entity.InviteRewardsRule;
import top.continew.admin.business.model.entity.TaskInfo;
import top.continew.admin.business.model.query.TaskInfoQuery;
import top.continew.admin.business.model.req.TaskInfoReq;
import top.continew.admin.business.service.ITaskInfoService;
import top.continew.starter.core.validation.CheckUtils;
import top.continew.starter.extension.crud.model.resp.BasePageResp;
import top.continew.starter.extension.crud.model.resp.PageResp;

import java.time.LocalDateTime;

/**
 * <p>
 * 任务信息表 服务实现类
 * </p>
 *
 * @author xudm
 * @since 2024-12-15
 */
@Service
public class TaskInfoServiceImpl extends ServiceImpl<TaskInfoMapper, TaskInfo> implements ITaskInfoService {
    @Override
    public BasePageResp<TaskInfo> getTaskInfoPage(TaskInfoQuery query) {
        Page<TaskInfo> page = new Page<>();
        page.setCurrent(query.getPage() != 0 ? query.getPage() : 1);
        page.setSize(query.getSize() != 0 ? query.getSize() : 10);

        LambdaQueryWrapper<TaskInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(query.getCategoryCode())) {
            queryWrapper.eq(TaskInfo::getCategoryCode, query.getCategoryCode());
        }
        if (StrUtil.isNotBlank(query.getName())) {
            queryWrapper.like(TaskInfo::getName, query.getName());
        }
        queryWrapper.orderByDesc(TaskInfo::getSortNum);
        page = page(page, queryWrapper);
        return PageResp.build(page, TaskInfo.class);
    }

    @Override
    public void updatetaskInfo(Long id, TaskInfoReq req) {
        Object loginId = StpUtil.getLoginId();
        TaskInfo byId = getById(id);
        CheckUtils.throwIfNull(byId, "任务信息为空，更新失败");
        BeanUtils.copyProperties(req, byId);
        byId.setUpdateBy(String.valueOf(loginId));
        byId.setUpdatedTime(LocalDateTime.now());
        updateById(byId);
    }

    @Override
    public Long addTaskInfo(TaskInfoReq req) {
        Object loginId = StpUtil.getLoginId();
        TaskInfo taskInfo = new TaskInfo();
        BeanUtils.copyProperties(req, taskInfo);
        taskInfo.setCreateBy((String) loginId);
        taskInfo.setCreateTime(LocalDateTime.now());
        taskInfo.setUpdatedTime(LocalDateTime.now());
        taskInfo.setUpdateBy((String) loginId);
        save(taskInfo);
        return taskInfo.getId();
    }
}
