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.obe.cultureProgram.ObeCultureProgramCourseParam;
import com.qmth.distributed.print.business.bean.result.obe.cultureProgram.CultureProgramCourseSelectResult;
import com.qmth.distributed.print.business.entity.ObeCourseRequirementMatrix;
import com.qmth.distributed.print.business.entity.ObeCultureProgramCourse;
import com.qmth.distributed.print.business.mapper.ObeCultureProgramCourseMapper;
import com.qmth.distributed.print.business.service.ObeCourseRequirementMatrixService;
import com.qmth.distributed.print.business.service.ObeCultureProgramCourseService;
import com.qmth.distributed.print.business.service.ObeCultureProgramService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicCourse;
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;

/**
 * <p>
 * 培养方案课程体系 服务实现类
 * </p>
 *
 * @author xf
 * @since 2024-06-05
 */
@Service
public class ObeCultureProgramCourseServiceImpl extends ServiceImpl<ObeCultureProgramCourseMapper, ObeCultureProgramCourse> implements ObeCultureProgramCourseService {

    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ObeCultureProgramService obeCultureProgramService;
    @Resource
    private ObeCourseRequirementMatrixService obeCourseRequirementMatrixService;

    @Override
    public List<CultureProgramCourseSelectResult> queryList(Long cultureProgramId, Long orgId) {
        if (orgId == null) {
            return null;
        }
        Set<Long> orgIdSet = sysOrgService.findDeepOrgIdListByOrgIdList(Arrays.asList(orgId));

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

    @Override
    public List<ObeCultureProgramCourse> listCourse(Long cultureProgramId) {
        return this.baseMapper.listCourse(cultureProgramId);
    }

    @Override
    public boolean saveCourse(ObeCultureProgramCourseParam obeCultureProgramCourseParam) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        List<ObeCultureProgramCourse> courseList = new ArrayList<>();
        AtomicInteger i = new AtomicInteger(1);
        int maxSortNum = this.getMaxSortNum(obeCultureProgramCourseParam.getCultureProgramId());
        obeCultureProgramCourseParam.getCourses().forEach(t -> {
            ObeCultureProgramCourse obeCultureProgramCourse = new ObeCultureProgramCourse();
            obeCultureProgramCourse.setCultureProgramId(obeCultureProgramCourseParam.getCultureProgramId());
            obeCultureProgramCourse.setCourseId(t.getCourseId());
            obeCultureProgramCourse.setSortNum(maxSortNum + i.getAndIncrement());
            obeCultureProgramCourse.insertInfo(sysUser.getId());
            courseList.add(obeCultureProgramCourse);
        });

        if (this.saveBatch(courseList)) {
            // 增加矩阵数据
            obeCourseRequirementMatrixService.updateMatrix(obeCultureProgramCourseParam.getCultureProgramId(), null, courseList);
            obeCultureProgramService.updateCourseCount(obeCultureProgramCourseParam.getCultureProgramId());
        }
        return true;
    }

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

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

    @Transactional
    @Override
    public boolean removeCourse(Long id) {
        ObeCultureProgramCourse obeCultureProgramCourse = this.getById(id);
        obeCourseRequirementMatrixService.removeMatrixByCondition(new ObeCourseRequirementMatrix(null, id, null, null));
        if (this.removeById(id)) {
            List<ObeCultureProgramCourse> obeCultureProgramCourseList = this.listCourse(obeCultureProgramCourse.getCultureProgramId());
            if (CollectionUtils.isNotEmpty(obeCultureProgramCourseList)) {
                for (int i = 0; i < obeCultureProgramCourseList.size(); i++) {
                    obeCultureProgramCourseList.get(i).setSortNum(i + 1);
                }
                this.updateBatchById(obeCultureProgramCourseList);
            }

            obeCultureProgramService.updateCourseCount(obeCultureProgramCourse.getCultureProgramId());
        }
        return true;
    }

    @Override
    public void removeByCultureProgramId(Long id) {
        this.remove(new QueryWrapper<ObeCultureProgramCourse>().lambda().eq(ObeCultureProgramCourse::getCultureProgramId, id));
    }

    @Override
    public Map<Long, Long> copyByCultureProgramId(Long id, Long obeCultureProgramNewId) {
        List<ObeCultureProgramCourse> obeCultureProgramCourseList = this.listCourse(id);
        Map<Long, Long> idMap = new HashMap<>();
        for (ObeCultureProgramCourse obeCultureProgramCourse : obeCultureProgramCourseList) {
            Long newId = SystemConstant.getDbUuid();
            idMap.put(obeCultureProgramCourse.getId(), newId);
            obeCultureProgramCourse.setId(newId);
            obeCultureProgramCourse.setCultureProgramId(obeCultureProgramNewId);
        }
        if (CollectionUtils.isNotEmpty(obeCultureProgramCourseList)) {
            this.saveBatch(obeCultureProgramCourseList);
        }
        return idMap;
    }
}
