package com.qmth.paper.library.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.paper.library.common.bean.result.TaskListResult;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.BasicAttachment;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.entity.TBTask;
import com.qmth.paper.library.common.enums.TaskResultEnum;
import com.qmth.paper.library.common.enums.TaskStatusEnum;
import com.qmth.paper.library.common.enums.TaskTypeEnum;
import com.qmth.paper.library.common.mapper.TBTaskMapper;
import com.qmth.paper.library.common.service.LibraryCommonService;
import com.qmth.paper.library.common.service.TBTaskService;
import com.qmth.paper.library.common.util.ResultUtil;
import com.qmth.paper.library.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 导入导出任务表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2021-03-19
 */
@Service
public class TBTaskServiceImpl extends ServiceImpl<TBTaskMapper, TBTask> implements TBTaskService {
    private final static Logger log = LoggerFactory.getLogger(TBTaskServiceImpl.class);

    @Resource
    private LibraryCommonService libraryCommonService;

    @Resource
    TBTaskMapper tbTaskMapper;

    /**
     * 保存任务
     */
    @Override
    public Map<String, Object> saveTask(TaskTypeEnum taskTypeEnum, String remark, SysUser sysUser) {
        Map<String, Object> map = new HashMap<>();
        try {
            TBTask tbTask = saveTaskCommon(null, taskTypeEnum, map, sysUser);
            if (StringUtils.isNotBlank(remark)) {
                tbTask.setRemark(remark);
            }
            this.save(tbTask);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return map;
    }

    /**
     * 查询任务列表
     *
     * @param iPage
     * @param status
     * @param type
     * @param result
     * @return
     */
    @Override
    public IPage<TaskListResult> query(IPage<TaskListResult> iPage, TaskStatusEnum status, TaskTypeEnum type, TaskResultEnum result) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        Set<Long> orgIds = libraryCommonService.listSubOrgIds(null);
        IPage<TaskListResult> taskListResultIPage = tbTaskMapper.query(iPage, schoolId, Objects.nonNull(status) ? status.name() : null, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(result) ? result.name() : null, sysUser.getId(), orgIds);
        for (TaskListResult record : taskListResultIPage.getRecords()) {
            String importFilePath = record.getImportFilePath();
            if (StringUtils.isNotBlank(importFilePath)) {
                JSONObject jsonObject = JSON.parseObject(importFilePath, JSONObject.class);
                record.setImportFilePath(libraryCommonService.preViewPath(jsonObject.getString(SystemConstant.PATH), jsonObject.getString(SystemConstant.UPLOAD_TYPE), jsonObject.getString(SystemConstant.TYPE), false));
            }
            String errorFilePath = record.getErrorFilePath();
            if (StringUtils.isNotBlank(errorFilePath)) {
                JSONObject jsonObject = JSON.parseObject(errorFilePath, JSONObject.class);
                record.setErrorFilePath(libraryCommonService.preViewPath(jsonObject.getString(SystemConstant.PATH), jsonObject.getString(SystemConstant.UPLOAD_TYPE), jsonObject.getString(SystemConstant.TYPE), false));
            }
            String exportFilePath = record.getExportFilePath();
            if (StringUtils.isNotBlank(exportFilePath)) {
                JSONObject jsonObject = JSON.parseObject(exportFilePath, JSONObject.class);
                record.setExportFilePath(libraryCommonService.preViewPath(jsonObject.getString(SystemConstant.PATH), jsonObject.getString(SystemConstant.UPLOAD_TYPE), jsonObject.getString(SystemConstant.TYPE), false));
            }
        }
        return taskListResultIPage;
    }

    /**
     * 保存task
     *
     * @param basicAttachment
     * @param taskTypeEnum
     * @param map
     * @param sysUser
     * @return
     */
    @Override
    public TBTask saveTaskCommon(BasicAttachment basicAttachment, TaskTypeEnum taskTypeEnum, Map map, SysUser sysUser) {
        SysUser requestUser = Objects.nonNull(sysUser) ? sysUser : (SysUser) ServletUtil.getRequestUser();
        TBTask tbTask = new TBTask(taskTypeEnum,
                TaskStatusEnum.INIT,
                Objects.nonNull(basicAttachment) ? basicAttachment.getName() : null,
                Objects.nonNull(basicAttachment) ? basicAttachment.getPath() : null,
                requestUser.getId(),
                requestUser.getSchoolId());
        map.computeIfAbsent(SystemConstant.TASK, v -> tbTask);
        map.computeIfAbsent(SystemConstant.USER, v -> requestUser);
        map.computeIfAbsent(SystemConstant.TB_TASK_ID, v -> tbTask.getId());
        return tbTask;
    }
}
