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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.params.professional.TPCourseParam;
import com.qmth.distributed.print.business.bean.result.ProfessionalCourseSelectResult;
import com.qmth.distributed.print.business.entity.TPCourse;
import com.qmth.distributed.print.business.entity.TPRequirement;
import com.qmth.distributed.print.business.mapper.TPCourseMapper;
import com.qmth.distributed.print.business.service.TPCourseService;
import com.qmth.distributed.print.business.service.TPMatrixService;
import com.qmth.distributed.print.business.service.TPRequirementService;
import com.qmth.teachcloud.common.bean.result.TeachCourseSelectResult;
import com.qmth.teachcloud.common.entity.BasicCourse;
import com.qmth.teachcloud.common.entity.SysOrg;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.SysOrgService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 专业认证课程 服务实现类
 * </p>
 *
 * @author xf
 * @since 2024-04-22
 */
@Service
public class TPCourseServiceImpl extends ServiceImpl<TPCourseMapper, TPCourse> implements TPCourseService {

    @Resource
    private TPRequirementService tpRequirementService;
    @Resource
    private TPMatrixService tpMatrixService;
    @Resource
    private SysOrgService sysOrgService;

    @Override
    public List<TPCourse> listCourse(Long professionalId) {
        QueryWrapper<TPCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TPCourse::getProfessionalId, professionalId)
                .orderByAsc(TPCourse::getSortNum);
        return this.list(queryWrapper);
    }

    @Transactional
    @Override
    public boolean saveCourse(TPCourseParam tpCourseParam) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        List<TPCourse> tpCourseList = new ArrayList<>();
        AtomicInteger i = new AtomicInteger(1);
        int maxSortNum = this.getMaxSortNum(tpCourseParam.getProfessionalId());
        tpCourseParam.getCourses().forEach(t -> {
            TPCourse tpCourse = new TPCourse();
            tpCourse.setProfessionalId(tpCourseParam.getProfessionalId());
            tpCourse.setCourseCode(t.getCourseCode());
            tpCourse.setCourseName(t.getCourseName());
            tpCourse.setSortNum(maxSortNum + i.getAndIncrement());
            tpCourse.insertInfo(sysUser.getId());
            tpCourseList.add(tpCourse);
        });

        List<TPRequirement> tpRequirementList = tpRequirementService.listRequirement(tpCourseParam.getProfessionalId());
        if (CollectionUtils.isNotEmpty(tpRequirementList)) {
            // 增加矩阵数据
            for (TPCourse tpCourse : tpCourseList) {
                for (TPRequirement tpRequirement : tpRequirementList) {
                    tpMatrixService.updateMatrixForNodeCount(tpCourse, tpRequirement);
                }
            }
        }

        this.saveBatch(tpCourseList);
        return true;
    }

    @Transactional
    @Override
    public boolean saveSort(List<TPCourse> courseList) {
        courseList.forEach(t -> {
            if (t.getId() != null && t.getSortNum() != null) {
                UpdateWrapper<TPCourse> updateWrapper = new UpdateWrapper();
                updateWrapper.lambda().set(TPCourse::getSortNum, t.getSortNum())
                        .eq(TPCourse::getId, t.getId());
                this.update(updateWrapper);
            }
        });
        return true;
    }

    @Transactional
    @Override
    public boolean removeCourse(Long id) {
        tpMatrixService.removeMatrixByCondition(null, id, null);
        return this.removeById(id);
    }

    @Override
    public List<ProfessionalCourseSelectResult> queryList(Long orgId, Long professionalId) {
        if (orgId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择学院");
        }
        Set<Long> orgIdSet = sysOrgService.findDeepOrgIdListByOrgIdList(Arrays.asList(orgId));

        return this.baseMapper.queryList(professionalId, orgIdSet);
    }

    @Override
    public int getMaxSortNum(Long professionalId) {
        QueryWrapper<TPCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TPCourse::getProfessionalId, professionalId)
                .orderByDesc(TPCourse::getSortNum)
                .last("limit 1");
        TPCourse tpCourse = this.getOne(queryWrapper);
        if (tpCourse == null) {
            return 0;
        } else {
            return tpCourse.getSortNum();
        }
    }
}
