package cn.ey.biz.module.system.service.job;

import cn.ey.biz.common.pojo.R;
import cn.ey.biz.module.system.api.job.ReportApi;
import cn.ey.biz.module.system.api.job.dto.ReportInfoDTO;
import cn.ey.biz.module.system.convert.job.JobConvert;
import cn.ey.biz.module.system.dal.dataobject.job.SystemJobDO;
import cn.ey.biz.module.system.dal.mapper.job.SystemJobMapper;
import cn.ey.biz.module.system.enums.ErrorCodeConstants;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;

@Service
public class JobServiceImpl implements JobService {

    @Resource
    private SystemJobMapper systemJobMapper;
    @Autowired
    private ReportApi reportApi;

    @Override
    public void updateJobStatus(String reqId, String result) {
        SystemJobDO jobDO = systemJobMapper.selectOne(new LambdaQueryWrapper<SystemJobDO>().eq(SystemJobDO::getReqId, reqId));
        if (null == jobDO) {
            throw exception(ErrorCodeConstants.JOB_REC_NOT_EXISTS);
        }
        jobDO.setResult(result);
        systemJobMapper.updateById(jobDO);
        // 获取对应数据，组装DTO 调用远程接口更新状态
        ReportInfoDTO reportInfoDTO = JobConvert.INSTANCE.convert(jobDO);
        if (result.equals("0")) {
            reportInfoDTO.setSucceedTaskNum(1);
            reportInfoDTO.setInstanceStatus(5);
        } else {
            reportInfoDTO.setFailedTaskNum(1);
            reportInfoDTO.setInstanceStatus(4);
        }
        reportInfoDTO.setSourceAddress(jobDO.getSourceAddress());
        reportInfoDTO.setEndTime(System.currentTimeMillis());
        reportInfoDTO.setReportTime(System.currentTimeMillis() + 1);
        R<Void> r = reportApi.reportInstanceStatus(reportInfoDTO);
        if(r.isError()){
            throw exception(ErrorCodeConstants.JOB_UPDATE_STATUS_ERROR);
        }
    }

}
