package com.qmth.exam.reserve.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.core.collection.PageResult;
import com.qmth.exam.reserve.bean.Constants;
import com.qmth.exam.reserve.bean.asynctask.AsyncTaskReq;
import com.qmth.exam.reserve.bean.asynctask.AsyncTaskVO;
import com.qmth.exam.reserve.config.SysProperty;
import com.qmth.exam.reserve.dao.AsyncTaskDao;
import com.qmth.exam.reserve.entity.AsyncTaskEntity;
import com.qmth.exam.reserve.enums.AsyncTaskStatus;
import com.qmth.exam.reserve.enums.AsyncTaskType;
import com.qmth.exam.reserve.service.AsyncTaskService;
import com.qmth.exam.reserve.util.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 异步任务
 */
@Service
public class AsyncTaskServiceImpl extends ServiceImpl<AsyncTaskDao, AsyncTaskEntity> implements AsyncTaskService {

    @Autowired
    private SysProperty sysProperty;

    @Override
    public Map<String, Object> saveAsyncTask(AsyncTaskType type, Long operateId) {
        Map<String, Object> map = new HashMap<>();
        AsyncTaskEntity taskEntity = new AsyncTaskEntity();
        taskEntity.setType(type);
        taskEntity.setStatus(AsyncTaskStatus.INIT);
        taskEntity.setOperateId(operateId);
        this.save(taskEntity);
        map.computeIfAbsent(Constants.ASYNC_TASK, v -> taskEntity);
        return map;
    }

    @Override
    public PageResult<AsyncTaskVO> pageAsyncTask(AsyncTaskReq req) {
        IPage<AsyncTaskVO> iPage = baseMapper.pageAsyncTask(new Page<>(req.getPageNumber(), req.getPageSize()), req);

        List<AsyncTaskVO> records = iPage.getRecords();
        String server = sysProperty.getServer();
        for (AsyncTaskVO record : records) {
            if (StringUtils.isNotEmpty(record.getImportFilePath())) {
                record.setImportFilePath(server + File.separator + record.getImportFilePath());
            }
            if (StringUtils.isNotEmpty(record.getExportFilePath())) {
                record.setExportFilePath(server + File.separator + record.getExportFilePath());
            }
        }

        return PageUtil.of(iPage);
    }


}
