package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.teachcloud.common.bean.params.ArraysParams;
import com.qmth.teachcloud.common.bean.result.TaskListResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.mapper.TBTaskMapper;
import com.qmth.teachcloud.common.service.TBTaskService;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.JacksonUtil;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * <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 TeachcloudCommonService teachcloudCommonService;

    @Resource
    TBTaskMapper tbTaskMapper;

    /**
     * 保存任务
     *
     * @param file
     * @param taskTypeEnum
     * @param objId
     * @return
     */
    @Override
    public Map<String, Object> saveTask(MultipartFile file, TaskTypeEnum taskTypeEnum, Object objId) {
        return null;
    }

    /**
     * 保存任务
     *
     * @param file
     * @param taskTypeEnum
     * @param projectId
     * @return
     */
    @Override
    public Map<String, Object> saveTask(MultipartFile file, TaskTypeEnum taskTypeEnum, Long projectId) {
        return null;
    }

    /**
     * 保存任务
     *
     * @param file
     * @param taskTypeEnum
     * @param objId
     * @param projectId
     * @return
     */
    @Override
    public Map<String, Object> saveTask(MultipartFile file, TaskTypeEnum taskTypeEnum, Object objId, Long projectId) {
        return null;
    }

    /**
     * 保存任务
     *
     * @param taskTypeEnum
     * @param printPlanId
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> saveTask(TaskTypeEnum taskTypeEnum, Long printPlanId) {
        Map<String, Object> map = new HashMap<>();
        try {
            TBTask tbTask = saveTaskCommon(null, taskTypeEnum, map, null);
            tbTask.setPrintPlanId(printPlanId);
            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 taskTypeEnum
     * @param printPlanId
     * @param sysUser
     * @param entityId
     * @return
     */
    @Override
    public Map<String, Object> saveTask(TaskTypeEnum taskTypeEnum, Long printPlanId, SysUser sysUser, Long entityId) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (Objects.nonNull(entityId)) {
                map.computeIfAbsent("entityId", v -> entityId);
            }
            TBTask tbTask = saveTaskCommon(null, taskTypeEnum, map, sysUser);
            tbTask.setPrintPlanId(printPlanId);
            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 taskTypeEnum
     * @param arraysParams
     * @param sysUser
     * @return
     */
    @Override
    public Map<String, Object> saveTask(TaskTypeEnum taskTypeEnum, ArraysParams arraysParams, SysUser sysUser) {
        Map<String, Object> map = new HashMap<>();
        try {
            TBTask tbTask = saveTaskCommon(null, taskTypeEnum, map, sysUser);
            if (Objects.nonNull(arraysParams)) {
                tbTask.setRemark(JacksonUtil.parseJson(arraysParams.getIds()));
            }
            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;
    }

    @Override
    public Map<String, Object> saveTask(TaskTypeEnum taskTypeEnum) {
        Map<String, Object> map = new HashMap<>();
        try {
            TBTask tbTask = saveTaskCommon(null, taskTypeEnum, map, null);
            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 schoolId
     * @param printPlanId
     * @param status
     * @param type
     * @param result
     * @return
     */
    @Override
    public IPage<TaskListResult> query(IPage<Map> iPage, Long schoolId, Long printPlanId, TaskStatusEnum status, TaskTypeEnum type, TaskResultEnum result) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Set<Long> orgIds = null;
        if (TaskTypeEnum.CREATE_PDF.equals(type)) {
            orgIds = teachcloudCommonService.listSubOrgIds(null);
        }
        return tbTaskMapper.query(iPage, schoolId, printPlanId, Objects.nonNull(status) ? status.name() : null, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(result) ? result.name() : null, sysUser.getId(), orgIds);
    }

    /**
     * 获取任务是否完成
     *
     * @param schoolId
     * @param printPlanId
     * @param entityIds
     * @return
     */
    @Override
    public boolean countByPrintPlanIdAndEntityId(Long schoolId, Long printPlanId, List<Long> entityIds) {
        QueryWrapper<TBTask> tbTaskQueryWrapper = new QueryWrapper<>();
        tbTaskQueryWrapper.lambda().ne(TBTask::getStatus, TaskStatusEnum.FINISH).isNotNull(TBTask::getStatus)
                .eq(TBTask::getType, TaskTypeEnum.CREATE_PDF);
        if (Objects.nonNull(schoolId)) {
            tbTaskQueryWrapper.lambda().eq(TBTask::getSchoolId, schoolId);
        }
        if (Objects.nonNull(printPlanId)) {
            tbTaskQueryWrapper.lambda().eq(TBTask::getPrintPlanId, printPlanId);
        }
        if (Objects.nonNull(entityIds)) {
            tbTaskQueryWrapper.lambda().in(TBTask::getEntityId, entityIds);
        }
        return this.count(tbTaskQueryWrapper) == 0 ? true : false;
    }

    /**
     * 保存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());
        if (Objects.nonNull(map.get("entityId"))) {
            tbTask.setEntityId((Long) map.get("entityId"));
        }
        map.computeIfAbsent(SystemConstant.TASK, v -> tbTask);
        map.computeIfAbsent(SystemConstant.USER, v -> requestUser);
        map.computeIfAbsent(SystemConstant.TB_TASK_ID, v -> tbTask.getId());
        return tbTask;
    }
}
