package com.xjrsoft.module.textbook.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.ExerciseBookeTypeEnum;
import com.xjrsoft.common.enums.SubscriptionTypeEnum;
import com.xjrsoft.common.enums.TextbookTypeEnum;
import com.xjrsoft.common.enums.WarehouseModeEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.utils.excel.CustomCellWriteWidthConfig;
import com.xjrsoft.common.utils.excel.ExcelFillCellMergePrevColUtil;
import com.xjrsoft.common.utils.excel.ExcelMergeUtil;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.entity.BaseCourseSubject;
import com.xjrsoft.module.base.entity.BaseGrade;
import com.xjrsoft.module.base.entity.BaseSemester;
import com.xjrsoft.module.base.mapper.BaseCourseSubjectMapper;
import com.xjrsoft.module.base.mapper.BaseGradeMapper;
import com.xjrsoft.module.base.mapper.BaseSemesterMapper;
import com.xjrsoft.module.base.service.IBaseClassService;
import com.xjrsoft.module.courseTable.entity.CourseTable;
import com.xjrsoft.module.teacher.entity.BaseTeacher;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.textbook.dto.*;
import com.xjrsoft.module.textbook.entity.*;
import com.xjrsoft.module.textbook.mapper.*;
import com.xjrsoft.module.textbook.service.*;
import com.xjrsoft.module.textbook.vo.*;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @title: 教材管理
 * @Author szs
 * @Date: 2023-12-25
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class TextbookServiceImpl extends MPJBaseServiceImpl<TextbookMapper, Textbook> implements ITextbookService {
    private final TextbookMapper textbookTextbookMapper;

    private final TextbookClassRelationMapper textbookTextbookClassRelationMapper;

    private final TextbookSubscriptionRecordMapper textbookTextbookSubscriptionRecordMapper;

    private final IWfTextbookSubscriptionService iWfTextbookSubscriptionService;

    private final IWfExerciseBookService wfExerciseBookService;

    private final IBaseClassService baseClassService;

    private final ITextbookWarehouseRecordService textbookClassWarehouseService;

    private final TextbookIssueRecordMapper textbookIssueRecordMapper;

    private final TextbookStudentClaimMapper textbookStudentClaimMapper;

    private final SubjectGroupMapper subjectGroupMapper;

    private final BaseGradeMapper baseGradeMapper;

    private final BaseCourseSubjectMapper baseCourseSubjectMapper;

    private final BaseSemesterMapper baseSemesterMapper;

    private final ITextbookCoreAttributeService textbookCoreAttributeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(Textbook textbook) {
        textbook.setCreateDate(new Date());
        textbookTextbookMapper.insert(textbook);
        for (TextbookClassRelation textbookClassRelation : textbook.getTextbookClassRelationList()) {
            textbookClassRelation.setTextbookId(textbook.getId());
            textbookClassRelation.setCreateDate(new Date());
            textbookTextbookClassRelationMapper.insert(textbookClassRelation);
        }
        if (textbook.getTextbookSubscriptionRecordList() != null) {
            for (TextbookSubscriptionRecord textbookSubscriptionRecord : textbook.getTextbookSubscriptionRecordList()) {
                textbookSubscriptionRecord.setTextbookId(textbook.getId());
                textbookSubscriptionRecord.setCreateDate(new Date());
                textbookTextbookSubscriptionRecordMapper.insert(textbookSubscriptionRecord);
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(Textbook textbook) {
        textbookTextbookMapper.updateById(textbook);
        //********************************* TextbookClassRelation  增删改  开始 *******************************************/
        {
            // 查出所有子级的id
            List<TextbookClassRelation> textbookClassRelationList = textbookTextbookClassRelationMapper.selectList(Wrappers.lambdaQuery(TextbookClassRelation.class).eq(TextbookClassRelation::getTextbookId, textbook.getId()).select(TextbookClassRelation::getId));
            List<Long> textbookClassRelationIds = textbookClassRelationList.stream().map(TextbookClassRelation::getId).collect(Collectors.toList());
            //原有子表单 没有被删除的主键
            List<Long> textbookClassRelationOldIds = textbook.getTextbookClassRelationList().stream().map(TextbookClassRelation::getId).filter(Objects::nonNull).collect(Collectors.toList());
            //找到需要删除的id
            List<Long> textbookClassRelationRemoveIds = textbookClassRelationIds.stream().filter(item -> !textbookClassRelationOldIds.contains(item)).collect(Collectors.toList());

            for (TextbookClassRelation textbookClassRelation : textbook.getTextbookClassRelationList()) {
                //如果不等于空则修改
                if (textbookClassRelation.getId() != null) {
                    textbookTextbookClassRelationMapper.updateById(textbookClassRelation);
                }
                //如果等于空 则新增
                else {
                    //已经不存在的id 删除
                    textbookClassRelation.setTextbookId(textbook.getId());
                    textbookTextbookClassRelationMapper.insert(textbookClassRelation);
                }
            }
            //已经不存在的id 删除
            if (textbookClassRelationRemoveIds.size() > 0) {
                textbookTextbookClassRelationMapper.deleteBatchIds(textbookClassRelationRemoveIds);
            }
        }
        //********************************* TextbookClassRelation  增删改  结束 *******************************************/

        //********************************* TextbookSubscriptionRecord  增删改  开始 *******************************************/
        {
            // 查出所有子级的id
            List<TextbookSubscriptionRecord> textbookSubscriptionRecordList = textbookTextbookSubscriptionRecordMapper.selectList(Wrappers.lambdaQuery(TextbookSubscriptionRecord.class).eq(TextbookSubscriptionRecord::getWfTextbookSubscriptionId, textbook.getId()).select(TextbookSubscriptionRecord::getId));
            List<Long> textbookSubscriptionRecordIds = textbookSubscriptionRecordList.stream().map(TextbookSubscriptionRecord::getId).collect(Collectors.toList());
            //原有子表单 没有被删除的主键
            if (!textbookSubscriptionRecordIds.isEmpty()) {
                List<Long> textbookSubscriptionRecordOldIds = textbook.getTextbookSubscriptionRecordList().stream().map(TextbookSubscriptionRecord::getId).filter(Objects::nonNull).collect(Collectors.toList());
                //找到需要删除的id
                List<Long> textbookSubscriptionRecordRemoveIds = textbookSubscriptionRecordIds.stream().filter(item -> !textbookSubscriptionRecordOldIds.contains(item)).collect(Collectors.toList());

                for (TextbookSubscriptionRecord textbookSubscriptionRecord : textbook.getTextbookSubscriptionRecordList()) {
                    //如果不等于空则修改
                    if (textbookSubscriptionRecord.getId() != null) {
                        textbookTextbookSubscriptionRecordMapper.updateById(textbookSubscriptionRecord);
                    }
                    //如果等于空 则新增
                    else {
                        //已经不存在的id 删除
                        textbookSubscriptionRecord.setWfTextbookSubscriptionId(textbook.getId());
                        textbookTextbookSubscriptionRecordMapper.insert(textbookSubscriptionRecord);
                    }
                }
                //已经不存在的id 删除
                if (textbookSubscriptionRecordRemoveIds.size() > 0) {
                    textbookTextbookSubscriptionRecordMapper.deleteBatchIds(textbookSubscriptionRecordRemoveIds);
                }
                for (TextbookSubscriptionRecord textbookSubscriptionRecord : textbook.getTextbookSubscriptionRecordList()) {
                    //如果不等于空则修改
                    if (textbookSubscriptionRecord.getId() != null) {
                        textbookTextbookSubscriptionRecordMapper.updateById(textbookSubscriptionRecord);
                    }
                    //如果等于空 则新增
                    else {
                        //已经不存在的id 删除
                        textbookSubscriptionRecord.setWfTextbookSubscriptionId(textbook.getId());
                        textbookTextbookSubscriptionRecordMapper.insert(textbookSubscriptionRecord);
                    }
                }
                //已经不存在的id 删除
                if (textbookSubscriptionRecordRemoveIds.size() > 0) {
                    textbookTextbookSubscriptionRecordMapper.deleteBatchIds(textbookSubscriptionRecordRemoveIds);
                }


            }
            //********************************* TextbookSubscriptionRecord  增删改  结束 *******************************************/

            return true;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        textbookTextbookMapper.deleteBatchIds(ids);
        textbookTextbookClassRelationMapper.delete(Wrappers.lambdaQuery(TextbookClassRelation.class).in(TextbookClassRelation::getTextbookId, ids));
        textbookTextbookSubscriptionRecordMapper.delete(Wrappers.lambdaQuery(TextbookSubscriptionRecord.class).in(TextbookSubscriptionRecord::getWfTextbookSubscriptionId, ids));

        return true;
    }

    @Override
    public Page<TextbookPageVo> getPage(Page<TextbookPageDto> page, TextbookPageDto dto) {
        Page<TextbookPageVo> result = textbookTextbookMapper.getPage(page, dto);
        return result;
    }

    @Override
    @Transactional
    public Boolean dataHandleAddTextbookNode(Long dataId) {
        WfTextbookSubscription wfTextbookSubscription = iWfTextbookSubscriptionService.selectById(dataId);
        if (ObjectUtil.isNotNull(wfTextbookSubscription) && ObjectUtil.isNotNull(wfTextbookSubscription.getWfTextbookSubscriptionItemList()) && wfTextbookSubscription.getWfTextbookSubscriptionItemList().size() > 0) {
            //遍历征订项
            for (WfTextbookSubscriptionItem wfTextbookSubscriptionItem : wfTextbookSubscription.getWfTextbookSubscriptionItemList()) {
                Long semesterId = wfTextbookSubscription.getBaseSemesterId();
                String issn = wfTextbookSubscriptionItem.getIssn();
                LambdaQueryWrapper<Textbook> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper
                        .eq(Textbook::getIssn, issn)
                        .eq(Textbook::getBaseSemesterId, semesterId);
                List<Textbook> textbookList = this.list(queryWrapper);
                //征订的教材没有在教材管理
                if (ObjectUtil.isNull(textbookList) || textbookList.size() == 0) {
                    Textbook textbook = new Textbook() {{
                        setIssn((ObjectUtil.isNull(wfTextbookSubscriptionItem.getIssn()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getIssn())) ? "/" : wfTextbookSubscriptionItem.getIssn());
                        setIsbn((ObjectUtil.isNull(wfTextbookSubscriptionItem.getIsbn()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getIsbn())) ? "/" : wfTextbookSubscriptionItem.getIsbn());
                        setBookName((ObjectUtil.isNull(wfTextbookSubscriptionItem.getBookName()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getBookName())) ? "/" : wfTextbookSubscriptionItem.getBookName());
                        setPublishingHouse((ObjectUtil.isNull(wfTextbookSubscriptionItem.getPublishingHouse()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getPublishingHouse())) ? "/" : wfTextbookSubscriptionItem.getPublishingHouse());
                        setEditorInChief((ObjectUtil.isNull(wfTextbookSubscriptionItem.getEditorInChief()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getEditorInChief())) ? "/" : wfTextbookSubscriptionItem.getEditorInChief());
                        setSubjectGroupId((ObjectUtil.isNull(wfTextbookSubscription.getSubjectGroupId())) ? 0 : wfTextbookSubscription.getSubjectGroupId());
                        setBaseSemesterId(wfTextbookSubscription.getBaseSemesterId());
                        setCourseSubjectId((ObjectUtil.isNull(wfTextbookSubscriptionItem.getCourseSubjectId())) ? 0 : wfTextbookSubscriptionItem.getCourseSubjectId());
                        setVersion((ObjectUtil.isNull(wfTextbookSubscriptionItem.getVersion()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getVersion())) ? "/" : wfTextbookSubscriptionItem.getVersion());
                        setIsTextbookPlan((ObjectUtil.isNull(wfTextbookSubscriptionItem.getIsTextbookPlan()) || StringUtils.isBlank(wfTextbookSubscriptionItem.getIsTextbookPlan())) ? "/" : wfTextbookSubscriptionItem.getIsTextbookPlan());
                        if (ObjectUtil.isNotNull(wfTextbookSubscriptionItem.getSubscriptionType()) && wfTextbookSubscriptionItem.getSubscriptionType().equals(SubscriptionTypeEnum.STextbook.getCode())) {
                            setTextbookType(TextbookTypeEnum.TTextbook.getCode());
                        }
                        if (ObjectUtil.isNotNull(wfTextbookSubscriptionItem.getSubscriptionType()) && wfTextbookSubscriptionItem.getSubscriptionType().equals(SubscriptionTypeEnum.SMaterials.getCode())) {
                            setTextbookType(TextbookTypeEnum.TMaterials.getCode());
                        }
                        setSpecificationsModels("/");
                        setAppraisalPrice((ObjectUtil.isNull(wfTextbookSubscriptionItem.getAppraisalPrice())) ? new BigDecimal(0) : wfTextbookSubscriptionItem.getAppraisalPrice());
                        setPrice(new BigDecimal(0));
                        setDiscount(10D);
                        setSubtotal(new BigDecimal(0));
                        setStock(0);
                    }};

                    //班级不为空
                    List<Long> classIdList = new ArrayList<>();
                    if (ObjectUtil.isNotNull(wfTextbookSubscriptionItem.getClassIds()) && !wfTextbookSubscriptionItem.getClassIds().equals("")) {
                        //将班级ids转换为List
                        String classIds = wfTextbookSubscriptionItem.getClassIds();
                        String[] classIdStrs = classIds.split(",");

                        for (String classIdStr : classIdStrs) {
                            classIdList.add(Long.parseLong(classIdStr));
                        }

                        //查询年级，如果添加的班级只存在一个年级，添加年级字段值
                        LambdaQueryWrapper<BaseClass> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1
                                .select(BaseClass::getGradeId)
                                .in(BaseClass::getId, classIdList)
                                .groupBy(BaseClass::getGradeId);
                        List<BaseClass> baseClassList = baseClassService.list(queryWrapper1);
                        if (ObjectUtil.isNotNull(baseClassList) && baseClassList.size() == 1) {
                            textbook.setGradeId(baseClassList.get(0).getGradeId());
                        }
                    }
                    //插入教材数据
                    textbook.setCreateDate(new Date());
                    textbookTextbookMapper.insert(textbook);

                    //插入班级和教材关系
                    for (Long classId : classIdList) {
                        textbookTextbookClassRelationMapper.insert(new TextbookClassRelation() {{
                            setCreateDate(new Date());
                            setTextbookId(textbook.getId());
                            setClassId(classId);
                        }});
                    }

                    //添加教材征订记录
                    textbookTextbookSubscriptionRecordMapper.insert(new TextbookSubscriptionRecord() {{
                        setCreateDate(new Date());
                        setTextbookId(textbook.getId());
                        setWfTextbookSubscriptionId(wfTextbookSubscription.getId());
                        setWfTextbookSubscriptionItemId(wfTextbookSubscriptionItem.getId());//该字段存入征订项的id，征订项中有所属征订记录
                    }});
                } else {

                    //征订的教材在教材管理,进行班级的和记录的管理
                    Textbook textbook = textbookList.get(0);

                    //班级不为空
                    if (ObjectUtil.isNotNull(wfTextbookSubscriptionItem.getClassIds()) && !wfTextbookSubscriptionItem.getClassIds().equals("")) {
                        //将班级ids转换为List
                        String classIds = wfTextbookSubscriptionItem.getClassIds();
                        String[] classIdStrs = classIds.split(",");
                        for (String classIdStr : classIdStrs) {
                            textbookTextbookClassRelationMapper.insert(new TextbookClassRelation() {{
                                setCreateDate(new Date());
                                setTextbookId(textbook.getId());
                                setClassId(Long.parseLong(classIdStr));
                            }});
                        }
                    }
                    //添加教材征订记录
                    textbookTextbookSubscriptionRecordMapper.insert(new TextbookSubscriptionRecord() {{
                        setCreateDate(new Date());
                        setTextbookId(textbook.getId());
                        setWfTextbookSubscriptionId(wfTextbookSubscription.getId());
                        setWfTextbookSubscriptionItemId(wfTextbookSubscriptionItem.getId());//该字段存入正定项的id，征订项中有所属征订记录
                    }});
                }
            }
        }
        return true;
    }

    /**
     * 添加作业本规则
     *
     * @param dataId
     * @return
     */
    @Override
    @Transactional
    public Boolean dataHandleAddExerciseBookNode(Long dataId) {
        WfExerciseBook wfExerciseBook = wfExerciseBookService.selectById(dataId);
        if (ObjectUtil.isNotNull(wfExerciseBook) && ObjectUtil.isNotNull(wfExerciseBook.getWfExerciseBookItemList()) && wfExerciseBook.getWfExerciseBookItemList().size() > 0) {
            for (WfExerciseBookItem wfExerciseBookItem : wfExerciseBook.getWfExerciseBookItemList()) {
                Long semesterId = wfExerciseBook.getBaseSemesterId();
                String bookName = wfExerciseBookItem.getSubscriptionType();//作业本的选择类型对应教材管理的书名
                LambdaQueryWrapper<Textbook> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper
                        .eq(Textbook::getBookName, bookName)
                        .eq(Textbook::getBaseSemesterId, semesterId);
                List<Textbook> textbookList = this.list(queryWrapper);
                //征订的作业本没有在教材管理
                if (ObjectUtil.isNull(textbookList) || textbookList.size() == 0) {
                    Textbook textbook = new Textbook() {{
                        setIssn("/");
                        setIsbn("/");
                        if (ObjectUtil.isNotNull(wfExerciseBookItem.getSubscriptionType()) && wfExerciseBookItem.getSubscriptionType().equals(ExerciseBookeTypeEnum.ExerciseBook1.getCode())) {
                            setBookName(ExerciseBookeTypeEnum.ExerciseBook1.getValue());
                        }
                        if (ObjectUtil.isNotNull(wfExerciseBookItem.getSubscriptionType()) && wfExerciseBookItem.getSubscriptionType().equals(ExerciseBookeTypeEnum.ExerciseBook2.getCode())) {
                            setBookName(ExerciseBookeTypeEnum.ExerciseBook2.getValue());
                        }
                        setPublishingHouse("/");
                        setEditorInChief("/");
                        setBaseSemesterId(wfExerciseBook.getBaseSemesterId());
                        setVersion("/");
                        setIsTextbookPlan("/");
                        setTextbookType(TextbookTypeEnum.TExerciseBook.getCode());
                        setSpecificationsModels((ObjectUtil.isNull(wfExerciseBookItem.getSpecificationsModels()) || StringUtils.isBlank(wfExerciseBookItem.getSpecificationsModels())) ? "/" : wfExerciseBookItem.getSpecificationsModels());
                        //年级id
                        if (ObjectUtil.isNotNull(wfExerciseBook.getClassId()) && wfExerciseBook.getClassId() > 0) {
                            LambdaQueryWrapper<BaseClass> queryWrapper1 = new LambdaQueryWrapper<>();
                            queryWrapper1
                                    .eq(BaseClass::getId, wfExerciseBook.getClassId());
                            BaseClass baseClass = baseClassService.getOne(queryWrapper1);
                            if (ObjectUtil.isNotNull(baseClass)) {
                                setGradeId(baseClass.getGradeId());
                            }
                        }
                        setAppraisalPrice((ObjectUtil.isNull(wfExerciseBookItem.getAppraisalPrice())) ? new BigDecimal(0) : wfExerciseBookItem.getAppraisalPrice());
                        setPrice(new BigDecimal(0));
                        setDiscount(10D);
                        setSubtotal(new BigDecimal(0));
                        setStock(0);
                    }};

                    //插入教材数据
                    textbook.setCreateDate(new Date());
                    textbookTextbookMapper.insert(textbook);

                    //插入班级和教材关系
                    if (ObjectUtil.isNotNull(wfExerciseBook.getClassId()) && wfExerciseBook.getClassId() > 0) {
                        textbookTextbookClassRelationMapper.insert(new TextbookClassRelation() {{
                            setCreateDate(new Date());
                            setTextbookId(textbook.getId());
                            setClassId(wfExerciseBook.getClassId());
                        }});
                    }


                    //添加教材征订记录
                    textbookTextbookSubscriptionRecordMapper.insert(new TextbookSubscriptionRecord() {{
                        setCreateDate(new Date());
                        setTextbookId(textbook.getId());
                        setWfTextbookSubscriptionId(wfExerciseBook.getId());
                    }});
                } else {
                    //征订的教材在教材管理,进行班级的和记录的管理
                    Textbook textbook = textbookList.get(0);

                    //班级不为空
                    if (ObjectUtil.isNotNull(wfExerciseBook.getClassId()) && wfExerciseBook.getClassId() > 0) {
                        textbookTextbookClassRelationMapper.insert(new TextbookClassRelation() {{
                            setCreateDate(new Date());
                            setTextbookId(textbook.getId());
                            setClassId(wfExerciseBook.getClassId());
                        }});

                    }
                    //添加教材征订记录
                    textbookTextbookSubscriptionRecordMapper.insert(new TextbookSubscriptionRecord() {{
                        setCreateDate(new Date());
                        setTextbookId(textbook.getId());
                        setWfTextbookSubscriptionId(wfExerciseBook.getId());
                    }});
                }
            }
        }
        return true;
    }

    @Override
    public List<TextbookSubscriptionRecordVo> subscriptionList(Long id) {
        Textbook textbook = this.getById(id);
        List<TextbookSubscriptionRecordVo> recordVos = new ArrayList<>();
        //是作业本
        if (textbook.getTextbookType().equals(TextbookTypeEnum.TExerciseBook.getCode())) {
            recordVos = textbookTextbookMapper.exerciseBookSubscriptionList(id);
            for (TextbookSubscriptionRecordVo recordVo : recordVos) {
                recordVo.setIssn("/");
                recordVo.setPublishingHouse("/");
                recordVo.setEditorInChief("/");
                recordVo.setIsTextbookPlanCn("/");
                recordVo.setCourseName("/");
                recordVo.setGradeName("/");
                recordVo.setTeacherSubscriptionNumber(0);
                recordVo.setTeacherReferenceNumber(0);
            }
        }
        //是教材或者教辅
        if (textbook.getTextbookType().equals(TextbookTypeEnum.TTextbook.getCode()) || textbook.getTextbookType().equals(TextbookTypeEnum.TMaterials.getCode())) {
            recordVos = textbookTextbookMapper.subscriptionList(id);
            for (TextbookSubscriptionRecordVo recordVo : recordVos) {
                if (ObjectUtil.isNull(recordVo) || StrUtil.isEmpty(recordVo.getClassIds())) {
                    recordVos.remove(recordVo);
                    if (recordVos.isEmpty()) {
                        break;
                    }
                    continue;
                }
                String[] split = recordVo.getClassIds().split(",");
                List<String> ids = new ArrayList<>();
                for (String classId : split) {
                    ids.add(classId.trim());
                }
                List<TextbookSubscriptionClassVo> classInfo = textbookTextbookMapper.getClassInfo(ids);
                String useClass = "";
                for (int i = 0; i < classInfo.size(); i++) {
                    if (i >= 1) {
                        useClass += ",";
                    }
                    TextbookSubscriptionClassVo classVo = classInfo.get(i);
                    useClass += classVo.getName();
                }
                recordVo.setUseClass(useClass);
            }
        }

        return recordVos;
    }

    @Override
    public TextbookVo getInfoByissn(String issn) {
        TextbookVo infoByissn = textbookTextbookMapper.getInfoByissn(issn);
        if (infoByissn == null) {
            return null;
        }
        List<TextbookClassRelation> classRelationList = textbookTextbookClassRelationMapper.selectList(
                new QueryWrapper<TextbookClassRelation>().lambda().eq(TextbookClassRelation::getTextbookId, infoByissn.getId())
        );
        infoByissn.setTextbookClassRelationList(BeanUtil.copyToList(classRelationList, TextbookClassRelationVo.class));
        return infoByissn;
    }

    @Override
    public List<TextbookWarehouseRecordListVo> warehouseList(Long id) {
        List<TextbookWarehouseRecordListVo> result = textbookTextbookMapper.warehouseList(id);
        if (!result.isEmpty()) {
            return result;
        }
        return new ArrayList<>();
    }

    @Override
    public List<TextbookClassRelation> getClassRelation(Long id) {
        List<TextbookClassRelation> classRelation = textbookTextbookMapper.getClassRelation(id);
        if (!classRelation.isEmpty()) {
            return classRelation;
        }
        return new ArrayList<>();
    }

    @Override
    public List<TextbookIssueRecordListVo> issueList(Long id) {
        List<TextbookIssueRecordListVo> result = textbookTextbookMapper.issueList(id);
        if (!result.isEmpty()) {
            return result;
        }
        return new ArrayList<>();
    }

    @Override
    public List<WfTextbookClaimListVo> claimList(Long id) {
        List<WfTextbookClaimListVo> result = new ArrayList<>();
        //教材领取分为两种
        //教师领取
        MPJLambdaWrapper<TextbookIssueRecord> queryIssueRecord = new MPJLambdaWrapper<>();
        queryIssueRecord
                .eq(TextbookIssueRecord::getTextbookId, id)
                .eq(TextbookIssueRecord::getIssueMode, "im_teacher");
        List<TextbookIssueRecord> textbookIssueRecordList = textbookIssueRecordMapper.selectJoinList(TextbookIssueRecord.class, queryIssueRecord);
        for (TextbookIssueRecord t : textbookIssueRecordList) {
            MPJLambdaWrapper<TextbookIssueRecord> queryTeaClaimVo = new MPJLambdaWrapper<>();
            queryTeaClaimVo
                    .selectAs(BaseSemester::getName, WfTextbookClaimListVo::getSemesterName)
                    .selectAs(XjrUser::getName, WfTextbookClaimListVo::getName)
                    .selectAs(XjrUser::getUserName, WfTextbookClaimListVo::getUserName)
                    .selectAs(TextbookIssueRecord::getCreateDate, WfTextbookClaimListVo::getClaimDate)
                    .leftJoin(XjrUser.class, XjrUser::getId, TextbookIssueRecord::getReceiveUserId)
                    .leftJoin(WfTextbookClaim.class, WfTextbookClaim::getId, TextbookIssueRecord::getDataId)
                    .leftJoin(BaseSemester.class, BaseSemester::getId, WfTextbookClaim::getBaseSemesterId)
                    .eq(TextbookIssueRecord::getId, t.getId());
            WfTextbookClaimListVo wfTextbookClaimListVo = textbookIssueRecordMapper.selectJoinOne(WfTextbookClaimListVo.class, queryTeaClaimVo);
            for (int j = 0; j < t.getIssueNumber(); j++) {
                wfTextbookClaimListVo.setClaimIdentity("教师");
                wfTextbookClaimListVo.setClassName("/");
                result.add(wfTextbookClaimListVo);
            }
        }
        //学生领取
        MPJLambdaWrapper<TextbookStudentClaim> queryStuClaimVo = new MPJLambdaWrapper<>();
        queryStuClaimVo
                .select("'学生' as claimIdentity")
                .selectAs(BaseClass::getName, WfTextbookClaimListVo::getClassName)
                .selectAs(BaseSemester::getName, WfTextbookClaimListVo::getSemesterName)
                .selectAs(XjrUser::getName, WfTextbookClaimListVo::getName)
                .selectAs(XjrUser::getUserName, WfTextbookClaimListVo::getUserName)
                .selectAs(TextbookStudentClaim::getCreateDate, WfTextbookClaimListVo::getClaimDate)
                .leftJoin(XjrUser.class, XjrUser::getId, TextbookStudentClaim::getStudentUserId)
                .leftJoin(BaseSemester.class, BaseSemester::getId, TextbookStudentClaim::getBaseSemesterId)
                .leftJoin(BaseClass.class, BaseClass::getId, TextbookStudentClaim::getClassId)
                .eq(TextbookStudentClaim::getTextbookId, id)
                .eq(TextbookStudentClaim::getIsClaim, 1);
        List<WfTextbookClaimListVo> wfTextbookClaimListVoList = textbookStudentClaimMapper.selectJoinList(WfTextbookClaimListVo.class, queryStuClaimVo);

        result.addAll(wfTextbookClaimListVoList);
        return result;
    }

    @Override
    public List<TextbookStandingExportQueryVo> listTextbookStandingExportQuery(TextbookStandingExportQuerytDto dto) {
        return textbookTextbookMapper.listTextbookStandingExportQuery(dto);
    }

    @Override
    public List<TextbookSubscriptionExportQueryVo> listTextbookSubscriptionExportQuery(TextbookSubscriptionExportQueryDto dto) {
        List<TextbookSubscriptionExportQueryVo> result = textbookTextbookMapper.listTextbookSubscriptionExportQuery(dto);
        //将班级转换为中文
        for (TextbookSubscriptionExportQueryVo to : result) {
            if (to != null && to.getClassIds() != null && !("").equals(to.getClassIds())) {
                List<Long> classIdList = new ArrayList<>();
                String[] classIdStrs = to.getClassIds().split(",");
                for (String classIdStr : classIdStrs) {
                    classIdList.add(Long.parseLong(classIdStr.trim()));
                }
                LambdaQueryWrapper<BaseClass> baseClassLambdaQueryWrapper = new LambdaQueryWrapper<>();
                baseClassLambdaQueryWrapper
                        .in(BaseClass::getId, classIdList);
                List<BaseClass> baseClassList = baseClassService.list(baseClassLambdaQueryWrapper);
                if (baseClassList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < baseClassList.size(); i++) {
                        sb.append(baseClassList.get(i).getName());
                        if (i != baseClassList.size() - 1) {
                            sb.append(",");
                        }
                    }
                    to.setUseClass(sb.toString());
                }
            }
        }
        return result;
    }

    @Override
    public ByteArrayOutputStream listTextbookClaimExportQuery(TextbookClaimExportQueryDto dto) {
        List<TextbookClaimExportQueryVo> customerList = textbookTextbookMapper.listTextbookClaimExportQuery(dto);

        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        //内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设计内容居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);// 水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        contentWriteCellStyle.setWrapped(true); //设置自动换行;
        // 设置字体
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 12);//设置字体大小
        contentWriteFont.setFontName("宋体"); //设置字体名字
        contentWriteCellStyle.setWriteFont(contentWriteFont);//在样式用应用设置的字体;
        //设置样式;
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置底边框;
        contentWriteCellStyle.setBottomBorderColor((short) 0);//设置底边框颜色;
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);  //设置左边框;
        contentWriteCellStyle.setLeftBorderColor((short) 0);//设置左边框颜色;
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);//设置右边框;
        contentWriteCellStyle.setRightBorderColor((short) 0);//设置右边框颜色;
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);//设置顶边框;
        contentWriteCellStyle.setTopBorderColor((short) 0); ///设置顶边框颜色;

        //设置头部样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景颜色
//        headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE1.getIndex());
//        headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);

        // 字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("宋体");//设置字体名字
        headWriteFont.setFontHeightInPoints((short) 14);//设置字体大小
        headWriteFont.setBold(true);//字体加粗
        headWriteCellStyle.setWriteFont(headWriteFont); //在样式用应用设置的字体;

        // 样式
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置底边框;
        headWriteCellStyle.setBottomBorderColor((short) 0);//设置底边框颜色;
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);  //设置左边框;
        headWriteCellStyle.setLeftBorderColor((short) 0);//设置左边框颜色;
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);//设置右边框;
        headWriteCellStyle.setRightBorderColor((short) 0);//设置右边框颜色;
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);//设置顶边框;
        headWriteCellStyle.setTopBorderColor((short) 0); //设置顶边框颜色;

        headWriteCellStyle.setWrapped(true);  //设置自动换行;

        //设置头部标题居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//设置水平对齐的样式为居中对齐;
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);  //设置垂直对齐的样式为居中对齐;
        headWriteCellStyle.setShrinkToFit(true);//设置文本收缩至合适

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        try (ExcelWriter excelWriter = EasyExcel.write(bot, TextbookClaimExportQueryVo.class).registerWriteHandler(horizontalCellStyleStrategy).build()) {
            //已经写入的行
            int rowIndex = 0;
            //已经写入的表
            int tableIndex = 0;
            // 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build();

            //sheet的表头
            List<List<String>> sheetHeadList = new ArrayList<List<String>>();
            sheetHeadList.add(new ArrayList<String>() {{
                add("铜梁执教中心班级教材教辅发放情况表");
            }});
            //sheet的表头合并策略
            ExcelFillCellMergePrevColUtil sheetHeadColumn = new ExcelFillCellMergePrevColUtil();
            sheetHeadColumn.add(rowIndex, 0, 9);
            //这是一个sheet表头的table
            WriteTable writeSheetHeadTable = EasyExcel.writerTable(tableIndex).needHead(Boolean.TRUE).head(sheetHeadList).registerWriteHandler(sheetHeadColumn).build();
            excelWriter.write(new ArrayList<>(), writeSheet, writeSheetHeadTable);

            //对返回的集合进行处理
            //现针对学期进行分组
            Map<Long, List<TextbookClaimExportQueryVo>> groupedBySemester = customerList.stream()
                    .collect(Collectors.groupingBy(TextbookClaimExportQueryVo::getBaseSemesterId));
            Iterator<Map.Entry<Long, List<TextbookClaimExportQueryVo>>> groupedBySemesterIterator = groupedBySemester.entrySet().iterator();
            while (groupedBySemesterIterator.hasNext()) {
                Map.Entry<Long, List<TextbookClaimExportQueryVo>> groupedBySemesterEntry = groupedBySemesterIterator.next();
                Long key = groupedBySemesterEntry.getKey();
                List<TextbookClaimExportQueryVo> value = groupedBySemesterEntry.getValue();

                Map<Long, List<TextbookClaimExportQueryVo>> groupedBySemesterByClass = value.stream()
                        .collect(Collectors.groupingBy(TextbookClaimExportQueryVo::getClassId));
                Iterator<Map.Entry<Long, List<TextbookClaimExportQueryVo>>> groupedBySemesterByClassIdIterator = groupedBySemesterByClass.entrySet().iterator();
                while (groupedBySemesterByClassIdIterator.hasNext()) {
                    Map.Entry<Long, List<TextbookClaimExportQueryVo>> groupedBySemesterByClassIdEntry = groupedBySemesterByClassIdIterator.next();
                    Long k = groupedBySemesterByClassIdEntry.getKey();
                    List<TextbookClaimExportQueryVo> v = groupedBySemesterByClassIdEntry.getValue();

                    //这是一个table的表头
                    List<List<String>> tableHeadList = new ArrayList<List<String>>();
                    tableHeadList.add(new ArrayList<String>() {{
                        add("日期:" + v.get(0).getBaseSemesterIdCn() + " 班级：" + v.get(0).getClassIdCn() + " 班主任：" + v.get(0).getHeadTeacherName() + " 教室：" + v.get(0).getClassRoomName() + " ");
                    }});
                    //table的表头合并策略
                    ExcelFillCellMergePrevColUtil tableHeadColumn = new ExcelFillCellMergePrevColUtil();
                    tableHeadColumn.add(++rowIndex, 0, 9);
                    //这是一个table表头的table
                    WriteTable writeTableHeadTable = EasyExcel.writerTable(++tableIndex).needHead(Boolean.TRUE).head(tableHeadList).registerWriteHandler(tableHeadColumn).build();
                    excelWriter.write(new ArrayList<>(), writeSheet, writeTableHeadTable);

                    Map<String, List<TextbookClaimExportQueryVo>> groupedByTextbookType = v.stream()
                            .collect(Collectors.groupingBy(TextbookClaimExportQueryVo::getTextbookTypeCn));
                    Iterator<Map.Entry<String, List<TextbookClaimExportQueryVo>>> groupedByTextbookTypeIterator = groupedByTextbookType.entrySet().iterator();
                    int index = 1;
                    BigDecimal total = new BigDecimal("0");
                    while (groupedByTextbookTypeIterator.hasNext()) {
                        Map.Entry<String, List<TextbookClaimExportQueryVo>> groupedByTextbookTypeEntry = groupedByTextbookTypeIterator.next();
                        String kk = groupedByTextbookTypeEntry.getKey();
                        List<TextbookClaimExportQueryVo> vv = groupedByTextbookTypeEntry.getValue();
                        if (index == 1) {
                            //添加小计
                            ExcelFillCellMergePrevColUtil subtotalColumn = new ExcelFillCellMergePrevColUtil();
                            subtotalColumn.add(rowIndex + vv.size() + 2, 1, 4);
                            BigDecimal subtotal = new BigDecimal("0");
                            for (TextbookClaimExportQueryVo tv : vv) {
                                subtotal = subtotal.add(tv.getSubtotal() == null ? new BigDecimal("0") : tv.getSubtotal());
                            }
                            BigDecimal finalSubtotal = subtotal;
                            vv.add(new TextbookClaimExportQueryVo() {{
                                setTextbookTypeCn(vv.get(0).getTextbookTypeCn());
                                setBookName("小计");
                                setSubtotal(finalSubtotal);
                            }});
                            total = total.add(finalSubtotal);

                            // 调用合并单元格工具类，此工具类是根据工程名称相同则合并后面数据
                            int mergeRowIndex = rowIndex + 1;
                            int[] mergeColumeIndex = {0};
                            ExcelMergeUtil excelFillCellMergeStrategy = new ExcelMergeUtil(mergeRowIndex, mergeColumeIndex);

                            // 第一次必须指定需要头，table 会继承sheet的配置，sheet配置了不需要，table 默认也是不需要
                            WriteTable writeContentTable = EasyExcel.writerTable(++tableIndex).needHead(Boolean.TRUE).registerWriteHandler(subtotalColumn).registerWriteHandler(excelFillCellMergeStrategy).build();
                            // 第一次写入会创建头
                            excelWriter.write(vv, writeSheet, writeContentTable);

                            rowIndex += (1 + vv.size());
                        } else {
                            //添加小计
                            ExcelFillCellMergePrevColUtil subtotalColumn = new ExcelFillCellMergePrevColUtil();
                            subtotalColumn.add(rowIndex + vv.size() + 1, 1, 4);
                            BigDecimal subtotal = new BigDecimal("0");
                            for (TextbookClaimExportQueryVo tv : vv) {
                                subtotal = subtotal.add(tv.getSubtotal());
                            }
                            BigDecimal finalSubtotal = subtotal;
                            vv.add(new TextbookClaimExportQueryVo() {{
                                setTextbookTypeCn(vv.get(0).getTextbookTypeCn());
                                setBookName("小计");
                                setSubtotal(finalSubtotal);
                            }});
                            total = total.add(finalSubtotal);
                            // 调用合并单元格工具类，此工具类是根据工程名称相同则合并后面数据
                            int mergeRowIndex = rowIndex;
                            int[] mergeColumeIndex = {0};
                            ExcelMergeUtil excelFillCellMergeStrategy = new ExcelMergeUtil(mergeRowIndex, mergeColumeIndex);

                            // 不需要头
                            WriteTable writeContentTable = EasyExcel.writerTable(++tableIndex).needHead(Boolean.FALSE).registerWriteHandler(subtotalColumn).registerWriteHandler(excelFillCellMergeStrategy).build();
                            excelWriter.write(vv, writeSheet, writeContentTable);

                            rowIndex += (vv.size());
                        }
                        index++;
                    }
                    //添加合计
                    BigDecimal finalTotal = total;
                    List<TextbookClaimExportQueryVo> totalList = new ArrayList<>();
                    totalList.add(new TextbookClaimExportQueryVo() {{
                        setTextbookTypeCn("合计");
                        setSubtotal(finalTotal);
                    }});
                    //-合并策略
                    ExcelFillCellMergePrevColUtil totaColumn = new ExcelFillCellMergePrevColUtil();
                    totaColumn.add(++rowIndex, 0, 5);
                    //这是一个合计的table
                    WriteTable writeTotalTable = EasyExcel.writerTable(++tableIndex).needHead(Boolean.FALSE).registerWriteHandler(totaColumn).build();
                    excelWriter.write(totalList, writeSheet, writeTotalTable);
                }
            }
        }
        return bot;
    }

    @Override
    @Transactional
    public Boolean excelImport(InputStream inputStream) {
        EasyExcel.read(inputStream, TextbookImportDto.class, new PageReadListener<TextbookImportDto>(dataList -> {
            if (dataList.isEmpty()) {
                throw new MyException("导入数据为空");
            }
            saveData(dataList);
        })).sheet().doRead();

        return true;
    }

    private void saveData(List<TextbookImportDto> dataList) {
        //查询所有需要的数据
        //学科组
        List<SubjectGroup> subjectGroupList = subjectGroupMapper.selectList(new LambdaQueryWrapper<>());
        Map<String, Long> subjectGroupNameAndIdMap = subjectGroupList.stream().collect(Collectors.toMap(SubjectGroup::getGroupName, SubjectGroup::getId, (k1, k2) -> k1));

        //使用年级
        List<BaseGrade> baseGradeList = baseGradeMapper.selectList(new LambdaQueryWrapper<>());
        Map<String, Long> baseGradeNameAndIdMap = baseGradeList.stream().collect(Collectors.toMap(BaseGrade::getName, BaseGrade::getId, (k1, k2) -> k1));

        //使用班级
        List<BaseClass> baseClassList = baseClassService.list();
        Map<String, Long> baseClassNameAndIdMap = baseClassList.stream().collect(Collectors.toMap(BaseClass::getName, BaseClass::getId, (k1, k2) -> k1));

        //使用课程
        List<BaseCourseSubject> baseCourseSubjectList = baseCourseSubjectMapper.selectList(new LambdaQueryWrapper<>());
        Map<String, Long> baseCourseSubjectNameAndIdMap = baseCourseSubjectList.stream().collect(Collectors.toMap(BaseCourseSubject::getName, BaseCourseSubject::getId, (k1, k2) -> k1));

        //使用学期
        List<BaseSemester> baseSemesterList = baseSemesterMapper.selectList(new LambdaQueryWrapper<>());
        Map<String, Long> baseSemesterNameAndIdMap = baseSemesterList.stream().collect(Collectors.toMap(BaseSemester::getName, BaseSemester::getId, (k1, k2) -> k1));

        //批量插入或更新数据
        for (TextbookImportDto textbookImportDto : dataList) {
            TextbookCoreAttribute textbookCoreAttribute = new TextbookCoreAttribute();
            BeanUtils.copyProperties(textbookImportDto, textbookCoreAttribute);

            Textbook textbook = new Textbook();
            BeanUtils.copyProperties(textbookImportDto, textbook);

            // 处理学科组映射
            String groupName = textbookImportDto.getGroupName();
            Long subjectGroupId = Optional.ofNullable(groupName)
                    .map(subjectGroupNameAndIdMap::get)
                    .orElse(null);
            textbook.setSubjectGroupId(subjectGroupId);

            // 处理课程映射
            String courseName = textbookImportDto.getCourseName();
            Long courseSubjectId = Optional.ofNullable(courseName)
                    .map(baseCourseSubjectNameAndIdMap::get)
                    .orElse(null);
            textbook.setCourseSubjectId(courseSubjectId);

            // 处理年级映射
            String useGrade = textbookImportDto.getUseGrade();
            Long gradeId = Optional.ofNullable(useGrade)
                    .map(baseGradeNameAndIdMap::get)
                    .orElse(null);
            textbook.setGradeId(gradeId);

            // 处理是否教材计划字段
            String isTextbookPlanCn = textbookImportDto.getIsTextbookPlanCn();
            String isTextbookPlan = Optional.ofNullable(isTextbookPlanCn)
                    .filter("是"::equals)
                    .map(s -> "yes")
                    .orElse("no");
            textbook.setIsTextbookPlan(isTextbookPlan);

            // 处理教材类型映射
            String textbookTypeCn = textbookImportDto.getTextbookTypeCn();
            String textbookTypeCode = Optional.ofNullable(textbookTypeCn)
                    .map(TextbookTypeEnum::getCode)
                    .orElse(null);
            textbook.setTextbookType(textbookTypeCode);

            // 处理学期映射
            String useSemester = textbookImportDto.getUseSemester();
            Long baseSemesterId = Optional.ofNullable(useSemester)
                    .map(baseSemesterNameAndIdMap::get)
                    .orElse(null);
            textbook.setBaseSemesterId(baseSemesterId);

            // 处理班级映射
            List<Long> classIdList = Optional.ofNullable(textbookImportDto.getUseClass())
                    .map(classNames -> Arrays.stream(classNames.split(","))
                            .map(String::trim)
                            .map(baseClassNameAndIdMap::get)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList()))
                    .orElse(Collections.emptyList());


            // 判断导入的教材是否已经存在，根据教材的 ISBN 码和使用的学期判断
            LambdaQueryWrapper<Textbook> textbookLambdaQueryWrapper = new LambdaQueryWrapper<>();
            textbookLambdaQueryWrapper
                    .eq(Textbook::getIssn, textbook.getIssn())
                    .eq(Textbook::getBaseSemesterId, textbook.getBaseSemesterId())
            ;

            Textbook oldTextbook = this.getOne(textbookLambdaQueryWrapper);



            // 已经存在，更新数据
            if (oldTextbook != null) {
                // 更新教材数据
                textbookTextbookMapper.updateById(textbook);

                // 先删除使用班级的信息，再新增
                LambdaQueryWrapper<TextbookClassRelation> textbookClassRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
                textbookClassRelationLambdaQueryWrapper
                        .eq(TextbookClassRelation::getTextbookId, textbook.getId());

                textbookTextbookClassRelationMapper.delete(textbookClassRelationLambdaQueryWrapper);

                // 批量插入班级关系
                for (Long classId : classIdList) {
                    textbookTextbookClassRelationMapper.insert(new TextbookClassRelation() {{
                        setCreateDate(new Date());
                        setTextbookId(textbook.getId());
                        setClassId(classId);
                    }});
                }
            } else {
                textbookCoreAttributeService.save(textbookCoreAttribute);

                textbook.setTextbookCoreAttributeId(textbookCoreAttribute.getId());
                // 插入教材数据
                textbookTextbookMapper.insert(textbook);

                //插入班级和教材关系
                for (Long classId : classIdList) {
                    textbookTextbookClassRelationMapper.insert(new TextbookClassRelation() {{
                        setCreateDate(new Date());
                        setTextbookId(textbook.getId());
                        setClassId(classId);
                    }});
                }
            }
        }
    }

    @Override
    @Transactional
    public Boolean deliverWarehouse(AddTextbookWarehouseRecordDto dto) {
        //根据id获取教材管理记录
        Textbook textbook = this.getById(dto.getTextbookId());
        if (ObjectUtil.isNull(textbook)) {
            throw new MyException("入库失败，该教材不存在");
        }

        BigDecimal price = ObjectUtil.isNull(dto.getPrice()) ? new BigDecimal(0) : dto.getPrice();
        Double discount = ObjectUtil.isNull(dto.getDiscount()) ? 10 : dto.getDiscount();
        BigDecimal subtotal = price.multiply(new BigDecimal(discount / 10));
        //更新总的库存数量
        this.updateById(new Textbook() {
            {
                setId(textbook.getId());
                Integer oldStock = ObjectUtil.isNull(textbook.getStock()) ? 0 : textbook.getStock();
                setStock(oldStock + (ObjectUtil.isNull(dto.getWarehouseNumber()) ? 0 : dto.getWarehouseNumber()));
                setPrice(price);
                setDiscount(discount);
                setSubtotal(subtotal);
                setModifyDate(new Date());
            }
        });
        //添加入库记录
        TextbookWarehouseRecord textbookWarehouseRecord = BeanUtil.toBean(dto, TextbookWarehouseRecord.class);
        textbookWarehouseRecord.setWarehouseMode(WarehouseModeEnum.WmManual.getCode());
        textbookWarehouseRecord.setDiscount(discount);
        textbookWarehouseRecord.setSubtotal(subtotal);
        textbookWarehouseRecord.setCreateDate(new Date());
        QueryWrapper<TextbookWarehouseRecord> queryWrapperSortcode = new QueryWrapper<>();
        queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
        TextbookWarehouseRecord t = textbookClassWarehouseService.getOne(queryWrapperSortcode);
        textbookWarehouseRecord.setSortCode(t.getSortCode() + 1);
        textbookClassWarehouseService.save(textbookWarehouseRecord);

        return true;
    }


}
