package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.distributed.print.business.bean.result.BasicTeachClazzResult;
import com.qmth.distributed.print.business.bean.result.DictionaryResult;
import com.qmth.distributed.print.business.bean.result.PrintPlanBrief;
import com.qmth.distributed.print.business.entity.BasicProfessional;
import com.qmth.distributed.print.business.entity.ObeCultureProgram;
import com.qmth.distributed.print.business.enums.ExamDetailStatusEnum;
import com.qmth.distributed.print.business.enums.PrintPlanStatusEnum;
import com.qmth.distributed.print.business.mapper.ConditionMapper;
import com.qmth.distributed.print.business.service.BasicExamService;
import com.qmth.distributed.print.business.service.BasicTeachClazzService;
import com.qmth.distributed.print.business.service.ConditionService;
import com.qmth.distributed.print.business.service.TeachCourseService;
import com.qmth.teachcloud.common.bean.dto.DataPermissionRule;
import com.qmth.teachcloud.common.entity.*;
import com.qmth.teachcloud.common.enums.ExamCategoryEnum;
import com.qmth.teachcloud.common.enums.mark.MarkPaperStatus;
import com.qmth.teachcloud.common.service.BasicRoleDataPermissionService;
import com.qmth.teachcloud.common.service.BasicSemesterService;
import com.qmth.teachcloud.common.service.SysOrgService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 查询条件 服务实现类
 * </p>
 */
@Service
public class ConditionServiceImpl implements ConditionService {

    @Resource
    BasicSemesterService basicSemesterService;

    @Resource
    BasicExamService basicExamService;

    @Resource
    BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Resource
    SysOrgService sysOrgService;

    @Resource
    ConditionMapper conditionMapper;

    @Resource
    BasicTeachClazzService basicTeachClazzService;

    @Override
    public List<BasicSemester> listSemester(Boolean enable) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<BasicSemester> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicSemester::getSchoolId, schoolId);
        if (enable != null) {
            queryWrapper.lambda().eq(BasicSemester::getEnable, enable);
        }
        queryWrapper.lambda().orderByDesc(BasicSemester::getCreateTime);
        return basicSemesterService.list(queryWrapper);
    }

    @Override
    public List<BasicExam> listExam(Long semesterId, ExamCategoryEnum category, Boolean enable) {
        QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicExam::getSemesterId, semesterId);
        if (category != null) {
            queryWrapper.lambda().eq(BasicExam::getCategory, category);
        }
        if (enable != null) {
            queryWrapper.lambda().eq(BasicExam::getEnable, enable);
        }
        queryWrapper.lambda().orderByDesc(BasicExam::getCreateTime);
        return basicExamService.list(queryWrapper);
    }

    @Override
    public List<BasicCourse> listCourse(Long semesterId, Long examId, Boolean enable, List<String> printPlanIds) {
        // 考试ID为空，默认返回空
        if (examId == null) {
            return new ArrayList<>();
        }
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        String privilegeIdString = privilegeId == null ? null : String.valueOf(privilegeId);

        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        // 未找到权限菜单，默认为本人权限
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();

        // 命题任务管理（39）
        if ("39".equals(privilegeIdString)) {
            return conditionMapper.listCourseFromExamTaskByCreateId(examId, dpr);
        }
        // 入库申请（40）
        else if ("40".equals(privilegeIdString)) {
            return conditionMapper.listCourseForApply(examId, sysUser.getId());
        }
        // 入库审核（41）
        else if ("41".equals(privilegeIdString)) {
            return conditionMapper.listCourseForAudit(semesterId, examId, enable);
        }
        // 卷库查询（42）
        else if ("42".equals(privilegeIdString)) {
            return conditionMapper.listCourseForQuery(examId, dpr);
        }
        // 印刷任务管理（47）
        else if ("47".equals(privilegeIdString)) {
            return conditionMapper.listCourseForPlanTask(semesterId, examId, printPlanIds, dpr);
        }
        // 流程审批记录管理（403）
        else if ("403".equals(privilegeIdString)) {
            return conditionMapper.listCourseForApproveHistory(semesterId, examId, dpr);
        }
        // 成绩查询
        else if ("487".equals(privilegeIdString) || "2001".equals(privilegeIdString)) {
            return conditionMapper.listCourseForScore(semesterId, examId, MarkPaperStatus.FINISH.name(), dpr);
        }
        // 评卷入口（491）
        else if ("491".equals(privilegeIdString)) {
            return conditionMapper.listCourseForEntrance(examId, sysUser.getId(), MarkPaperStatus.FORMAL.name());
        }
        // 评卷设置（897）、评卷管理（917）、成绩检查（946）
        else if ("897".equals(privilegeIdString) || "917".equals(privilegeIdString) || "946".equals(privilegeIdString)) {
            return conditionMapper.listCourseFromMarkPaper(examId, dpr);
        }
        // 下载管理（653)
        else if ("653".equals(privilegeIdString)) {
            return conditionMapper.listCourseFromExamTaskByUserId(examId, dpr);
        } else {
            return conditionMapper.listCourse(semesterId, examId, enable, printPlanIds, dpr);
        }
    }

    @Override
    public List<String> listPaperNumber(Long semesterId, Long examId, String courseCode, List<String> printPlanIds) {
        // 考试ID为空，默认返回空
        if (examId == null) {
            return new ArrayList<>();
        }
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        String privilegeIdString = privilegeId == null ? null : String.valueOf(privilegeId);
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        // 未找到权限菜单，默认为本人权限
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();

        // 命题任务管理（39）
        if ("39".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberFromExamTaskByCreateId(examId, courseCode, dpr);
        }
        // 入库申请（40）
        else if ("40".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberForApply(examId, courseCode, sysUser.getId());
        }
        // 入库审核（41）
        else if ("41".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberAudit(semesterId, examId, courseCode);
        }
        // 卷库查询（42）
        else if ("42".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberForQuery(examId, courseCode, dpr);
        }
        // 印刷任务管理（47）
        else if ("47".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberPlanTask(semesterId, examId, printPlanIds, courseCode, dpr);
        }
        // 流程审批记录管理（403）
        else if ("403".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberForApproveHistory(semesterId, examId, courseCode, dpr);
        }
        // 成绩查询
        else if ("487".equals(privilegeIdString) || "2001".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberForScore(semesterId, examId, MarkPaperStatus.FINISH.name(), dpr);
        }
        // 评卷入口（491）
        else if ("491".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberForEntrance(examId, sysUser.getId(), courseCode, MarkPaperStatus.FORMAL.name());
        }
        // 评卷设置（897）、评卷管理（917）、成绩检查（946）
        else if ("897".equals(privilegeIdString) || "917".equals(privilegeIdString) || "946".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberFromMarkPaper(examId, courseCode, dpr);
        }
        // 下载管理（653)
        else if ("653".equals(privilegeIdString)) {
            return conditionMapper.listPaperNumberFromExamTaskByUserIdAndPass(examId, courseCode, dpr);
        } else {
            return conditionMapper.listPaperNumber(semesterId, examId, courseCode, printPlanIds, dpr);
        }
    }

    @Override
    public List<PrintPlanBrief> listPrintPlan(Long semesterId, Long examId, String source) {
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        DataPermissionRule dpr = new DataPermissionRule();
        // 未找到权限菜单，默认为本人权限
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();

        if ("client".equals(source)) {
            String[] examDetailStatus = new String[] { ExamDetailStatusEnum.NEW.name(),
                    PrintPlanStatusEnum.READY.name() };
            return conditionMapper.listPrintPlanForClient(semesterId, examId, examDetailStatus);
        } else {
            // 如果byAssignUser为true时，不能通过层级关系查询
            if (privilegeId == null) {
                dpr.setRequestUserId(sysUser.getId());
                dpr.setOrgIdSet(null);
            } else {
                dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
            }
            return conditionMapper.listPrintPlan(semesterId, examId, dpr);
        }
    }

    @Override
    public List<BasicClazz> listClazz(Long semesterId, Long examId, String courseCode, String clazzName) {
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        String privilegeIdString = privilegeId == null ? null : String.valueOf(privilegeId);
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        if ("487".equals(privilegeIdString)) {
            return conditionMapper.listClazz(semesterId, examId, courseCode, clazzName, dpr);
        }
        return new ArrayList<>();
    }

    @Override
    public List<SysOrg> listCollege() {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        SysOrg rootOrg = sysOrgService.findRootOrg(schoolId);
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysOrg::getParentId, rootOrg.getId()).isNull(SysOrg::getType)
                .orderByAsc(SysOrg::getCreateTime);
        return sysOrgService.list(queryWrapper);
    }

    @Override
    public List<BasicTeachClazzResult> listBasicTeachClazz(Long examId, String courseCode, String clazzName) {
        return basicTeachClazzService.findAllTeachClazz(examId, courseCode, clazzName);
    }

    @Override
    public List<BasicProfessional> listProfessional() {
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        // 未找到权限菜单，默认为本人权限
        return conditionMapper.listProfessional(schoolId, dpr);
    }

    @Override
    public List<ObeCultureProgram> listCultureProgram(Long professionalId) {
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());

        return conditionMapper.listCultureProgram(schoolId, professionalId, dpr);
    }

    @Override
    public List<DictionaryResult> listOutlineSemester(Long professionalId, Long cultureProgramId) {
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());

        return conditionMapper.listOutlineSemester(schoolId, professionalId, cultureProgramId, dpr);
    }

    @Override
    public List<BasicCourse> listCultureProgramCourse(Long professionalId, Long cultureProgramId, Long semesterId) {
        Long privilegeId = ServletUtil.getCurrentPrivilegeId();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(privilegeId);
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        return conditionMapper.listCultureProgramCourse(schoolId, professionalId, cultureProgramId, semesterId, dpr);
    }
}
