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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.teachcloud.common.bean.dto.DataPermissionRule;
import com.qmth.teachcloud.common.bean.dto.MqDto;
import com.qmth.teachcloud.common.bean.params.ArraysParams;
import com.qmth.teachcloud.common.bean.result.TaskListResult;
import com.qmth.teachcloud.common.bean.result.TbTaskDetailResult;
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.*;
import com.qmth.teachcloud.common.mapper.TBTaskMapper;
import com.qmth.teachcloud.common.service.BasicRoleDataPermissionService;
import com.qmth.teachcloud.common.service.TBTaskService;
import com.qmth.teachcloud.common.util.*;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <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 BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Resource
    TBTaskMapper tbTaskMapper;

    @Resource
    RedisUtil redisUtil;

    /**
     * 保存任务
     *
     * @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, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return map;
    }

    /**
     * 保存任务
     *
     * @param taskTypeEnum
     * @param printPlanId
     * @param sysUser
     * @param entityId
     * @return
     */
    @Override
    public Map<String, Object> saveTask(TbTaskDetailResult tbTaskDetailResult, 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);
            if (tbTaskDetailResult != null) {
                tbTask.setSemesterId(tbTaskDetailResult.getSemesterId());
                tbTask.setExamId(tbTaskDetailResult.getExamId());
                tbTask.setCourseCode(tbTaskDetailResult.getCourseCode());
                tbTask.setCourseName(tbTaskDetailResult.getCourseName());
                tbTask.setPaperNumber(tbTaskDetailResult.getPaperNumber());
            }
            tbTask.setPrintPlanId(printPlanId);
            this.save(tbTask);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), 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, ((ApiException) e).getCode(), 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, ((ApiException) e).getCode(), 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 semesterId, Long examId, String courseCode, String paperNumber, Long schoolId, Long printPlanId, TaskStatusEnum status, TaskTypeEnum type, TaskResultEnum result) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, sysUser.getId(), ServletUtil.getRequest().getServletPath());
        return tbTaskMapper.query(iPage, schoolId, semesterId, examId, courseCode, paperNumber, printPlanId, Objects.nonNull(status) ? status.name() : null, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(result) ? result.name() : null, dpr);
    }


    /**
     * 保存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;
    }

    @Override
    public IPage<TaskListResult> queryResult(Page<Map> iPage, Long semesterId, Long examId, String courseCode, String paperNumber, TaskStatusEnum status, TaskTypeEnum type, TaskResultEnum result) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, sysUser.getId(), ServletUtil.getRequest().getServletPath());
        return tbTaskMapper.query(iPage, schoolId, semesterId, examId, courseCode, paperNumber, null, Objects.nonNull(status) ? status.name() : null, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(result) ? result.name() : null, dpr);
    }
}
