package com.ai.da.service.impl;

import com.ai.da.mapper.primary.AccountMapper;
import com.ai.da.mapper.primary.CloudTaskMapper;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.CloudTask;
import com.ai.da.service.ClassificationService;
import com.ai.da.service.CloudTaskService;
import com.ai.da.service.CreditsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Service
public class CloudTaskServiceImpl extends ServiceImpl<CloudTaskMapper, CloudTask> implements CloudTaskService {

    @Resource
    private CreditsService creditsService;

    @Override
    public CloudTask getByTaskId(String taskId) {
        QueryWrapper<CloudTask> qw = new QueryWrapper<>();
        qw.lambda().eq(CloudTask::getTaskId, taskId);
        return baseMapper.selectOne(qw);
    }

    @Override
    public void startTask(String batchTaskId) {
        QueryWrapper<CloudTask> qw = new QueryWrapper<>();
        qw.lambda().eq(CloudTask::getTaskId, batchTaskId);
        CloudTask cloudTask = baseMapper.selectOne(qw);
        cloudTask.setStartTime(LocalDateTime.now());
        baseMapper.updateById(cloudTask);
    }

    @Override
    public void completeTask(String batchTaskId) {
        QueryWrapper<CloudTask> qw = new QueryWrapper<>();
        qw.lambda().eq(CloudTask::getTaskId, batchTaskId);
        CloudTask cloudTask = baseMapper.selectOne(qw);
        cloudTask.setStatus(1);
//        cloudTask.setCompletedNum(cloudTask.getNums());
        cloudTask.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(cloudTask);

        // 扣除积分
        Boolean b = creditsService.taskCreditsDeduction(cloudTask.getAccountId(), cloudTask.getTaskId());
        // 记录积分变更
        if (b) creditsService.updateChangedCredits(String.valueOf(cloudTask.getAccountId()), cloudTask.getTaskId());
    }
}
