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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.entity.BaseSemester;
import com.xjrsoft.module.base.service.IBaseClassService;
import com.xjrsoft.module.base.service.IBaseSemesterService;
import com.xjrsoft.module.student.entity.BaseStudent;
import com.xjrsoft.module.student.entity.BaseStudentSchoolRoll;
import com.xjrsoft.module.teacher.entity.AttendanceRecord;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.teacher.mapper.XjrUserMapper;
import com.xjrsoft.module.textbook.dto.TeacherCheckByStuDto;
import com.xjrsoft.module.textbook.dto.TeacherCheckByclassDto;
import com.xjrsoft.module.textbook.dto.TeacherCheckStuClaimDto;
import com.xjrsoft.module.textbook.dto.TextbookClaimStudentConfirmDto;
import com.xjrsoft.module.textbook.entity.Textbook;
import com.xjrsoft.module.textbook.entity.TextbookStudentClaim;
import com.xjrsoft.module.textbook.mapper.TextbookStudentClaimMapper;
import com.xjrsoft.module.textbook.mapper.WfTextbookClaimItemMapper;
import com.xjrsoft.module.textbook.mapper.WfTextbookClaimMapper;
import com.xjrsoft.module.textbook.service.ITextbookStudentClaimService;
import com.xjrsoft.module.textbook.vo.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @title: 学生教材认领记录
 * @Author szs
 * @Date: 2023-12-26
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class TextbookStudentClaimServiceImpl extends MPJBaseServiceImpl<TextbookStudentClaimMapper, TextbookStudentClaim> implements ITextbookStudentClaimService {

    private final XjrUserMapper xjrUserMapper;

    private final TextbookStudentClaimMapper textbookStudentClaimMapper;
    private final IBaseSemesterService baseSemesterService;

    private final IBaseClassService baseClassService;

    private final WfTextbookClaimMapper wfTextbookClaimMapper;

    private final WfTextbookClaimItemMapper wfTextbookClaimItemMapper;

    @Override
    public TextbookClaimStudentConfirmVo getStudentConfirmList(TextbookClaimStudentConfirmDto dto) {
        //获取当前登录学生的信息
        MPJLambdaWrapper<XjrUser> queryUser = new MPJLambdaWrapper<>();
        queryUser.selectAs(XjrUser::getName, TextbookClaimStudentConfirmVo::getStudentName).selectAs(BaseStudent::getStudentId, TextbookClaimStudentConfirmVo::getStudentId).selectAs(BaseClass::getName, TextbookClaimStudentConfirmVo::getClassCN).leftJoin(BaseStudent.class, BaseStudent::getUserId, XjrUser::getId).leftJoin(BaseStudentSchoolRoll.class, BaseStudentSchoolRoll::getUserId, XjrUser::getId).leftJoin(BaseClass.class, BaseClass::getId, BaseStudentSchoolRoll::getClassId).eq(XjrUser::getId, StpUtil.getLoginIdAsLong()).disableSubLogicDel().orderByDesc(AttendanceRecord::getId);
        TextbookClaimStudentConfirmVo textbookClaimStudentConfirmVo = xjrUserMapper.selectJoinOne(TextbookClaimStudentConfirmVo.class, queryUser);
        if (ObjectUtil.isNull(textbookClaimStudentConfirmVo)) {
            throw new MyException("登录信息出错，请重新登录");
        }

        //根据学期id查出学期名称
        BaseSemester baseSemester = baseSemesterService.getById(dto.getBaseSemesterId());
        textbookClaimStudentConfirmVo.setBaseSemesterCN(baseSemester.getName());

        dto.setStudentUserId(StpUtil.getLoginIdAsLong());

        List<TextbookClaimVO> textbookClaimVOList = textbookStudentClaimMapper.getTextbookClaimList(dto);

        textbookClaimStudentConfirmVo.setTextbookClaimVoList(textbookClaimVOList);
        return textbookClaimStudentConfirmVo;
    }

    @Override
    public List<TextbookStudentSemesterVo> getStudentSemesterList() {
        //获取当前学生领取记录的所有学期
        MPJLambdaWrapper<TextbookStudentClaim> qwerySemester = new MPJLambdaWrapper<>();
        qwerySemester
                .distinct()
                .disableSubLogicDel()
                .selectAs(BaseSemester::getName, TextbookStudentSemesterVo::getBaseSemesterIdCN)
                .select(TextbookStudentClaim.class, x -> VoToColumnUtil.fieldsToColumns(TextbookStudentSemesterVo.class).contains(x.getProperty()))
                .leftJoin(BaseSemester.class, BaseSemester::getId, TextbookStudentClaim::getBaseSemesterId)
                .eq(TextbookStudentClaim::getStudentUserId, StpUtil.getLoginIdAsLong());
        List<TextbookStudentSemesterVo> textbookStudentSemesterVoList = this.selectJoinList(TextbookStudentSemesterVo.class, qwerySemester);
        if (ObjectUtil.isNull(textbookStudentSemesterVoList) && textbookStudentSemesterVoList.size() == 0) {
            return null;
        }
        //为每个学期添加未领取人数
        for (TextbookStudentSemesterVo textbookStudentSemesterVo : textbookStudentSemesterVoList) {
            LambdaQueryWrapper<TextbookStudentClaim> queryWrapperNotClaimNum = new LambdaQueryWrapper<>();
            queryWrapperNotClaimNum.eq(TextbookStudentClaim::getStudentUserId, StpUtil.getLoginIdAsLong()).eq(TextbookStudentClaim::getBaseSemesterId, textbookStudentSemesterVo.getBaseSemesterId()).eq(TextbookStudentClaim::getIsClaim, 0);
            Long notClaimNum = this.count(queryWrapperNotClaimNum);
            textbookStudentSemesterVo.setNotClaimNum(notClaimNum);
        }
        return textbookStudentSemesterVoList;
    }

    @Override
    public IPage<TeacherCheckByclassVo> getTeacherCheckByclassList(TeacherCheckByclassDto dto) {
        //根据当前班主任用户查出所管理的班级Id
        LambdaQueryWrapper<BaseClass> queryWrapperClassId = new LambdaQueryWrapper<>();
        queryWrapperClassId.eq(BaseClass::getTeacherId, StpUtil.getLoginIdAsLong());
        List<BaseClass> baseClassList = baseClassService.list(queryWrapperClassId);
        if (ObjectUtil.isNull(baseClassList) && baseClassList.size() == 0) {
            return null;
        }

        List<Long> classIdList = new ArrayList<>();
        for (BaseClass baseClass : baseClassList) {
            classIdList.add(baseClass.getId());
        }
        dto.setClassIdList(classIdList);

        IPage<TeacherCheckByclassVo> teacherCheckByclassVoList = textbookStudentClaimMapper.getTeacherCheckByclassList(ConventPage.getPage(dto), dto);

        //为每本书添加数据
//        for (TeacherCheckByclassVo t : teacherCheckByclassVoList.getRecords()) {
//            MPJLambdaWrapper<WfTextbookClaim> qweryActualReceivedNum = new MPJLambdaWrapper<>();
//            qweryActualReceivedNum
//                    .disableSubLogicDel()
//                    .selectSum(WfTextbookClaimItem::getIssueNumber, TeacherCheckByclassVo::getActualReceivedNum)
//                    .leftJoin(WfTextbookClaimItem.class, WfTextbookClaimItem::getWfTextbookClaimId, WfTextbookClaim::getId)
//                    .eq(WfTextbookClaim::getClassId, t.getClassId())
//                    .eq(WfTextbookClaimItem::getTextbookId, t.getTextbookId());
//            TeacherCheckByclassVo teacherCheckByclassVo = wfTextbookClaimMapper.selectJoinOne(TeacherCheckByclassVo.class, qweryActualReceivedNum);
//
//            t.setActualReceivedNum(teacherCheckByclassVo.getActualReceivedNum());
//
//            LambdaQueryWrapper<TextbookStudentClaim> queryActualClaimNum = new LambdaQueryWrapper<>();
//            queryActualClaimNum
//                    .eq(TextbookStudentClaim::getClassId, t.getClassId())
//                    .eq(TextbookStudentClaim::getTextbookId, t.getTextbookId())
//                    .eq(TextbookStudentClaim::getIsClaim, 1);
//            Long actualClaimNum = this.count(queryActualClaimNum);
//            t.setActualClaimNum(actualClaimNum);
//        }
        return teacherCheckByclassVoList;
    }

    @Override
    public IPage<TeacherCheckByStuVo> getTeacherCheckByStuList(TeacherCheckByStuDto dto) {
        //根据当前班主任用户查出所管理的班级Id
        LambdaQueryWrapper<BaseClass> queryWrapperClassId = new LambdaQueryWrapper<>();
        queryWrapperClassId.eq(BaseClass::getTeacherId, StpUtil.getLoginIdAsLong());
        List<BaseClass> baseClassList = baseClassService.list(queryWrapperClassId);
        if (ObjectUtil.isNull(baseClassList) && baseClassList.size() == 0) {
            return null;
        }

        List<Long> classIdList = new ArrayList<>();
        for (BaseClass baseClass : baseClassList) {
            classIdList.add(baseClass.getId());
        }
        dto.setClassIdList(classIdList);

        //将班上所有学生进行分组,查询出list集合
        IPage<TeacherCheckByStuVo> teacherCheckByStuVoList = textbookStudentClaimMapper.getTeacherCheckByStuList(ConventPage.getPage(dto), dto);

        //为每个学生添加教材领取记录集合
        //学生id集合
//        List<Long> stuIdList = new ArrayList<>();
//        for (TeacherCheckByStuVo teacherCheckByStuVo : teacherCheckByStuVoList.getRecords()) {
//            stuIdList.add(teacherCheckByStuVo.getStudentUserId());
//        }
//        //一次查出所有学生的所有书籍
//        if(stuIdList.size() > 0){
//            List<TextbookClaimVO> textbookClaimVOList = textbookStudentClaimMapper.getTextbookClaimVOList(stuIdList);
//        }

        for (TeacherCheckByStuVo t : teacherCheckByStuVoList.getRecords()) {
            List<TextbookClaimVO> textbookClaimVOList = textbookStudentClaimMapper.getTextbookClaimVOList(t.getStudentUserId());
            t.setTextbookClaimVOList(textbookClaimVOList);
        }
        return teacherCheckByStuVoList;
    }


    @Override
    @Transactional
    public Boolean updateByIds(List<Long> textbookStudentClaimIds) {
        this.update(new TextbookStudentClaim() {{
            setModifyUserId(StpUtil.getLoginIdAsLong());
            setModifyDate(new Date());
            setIsClaim(1);
        }},Wrappers.<TextbookStudentClaim>query().lambda()
                .in(TextbookStudentClaim::getId, textbookStudentClaimIds));
//        for (Long textbookStudentClaimId : textbookStudentClaimIds) {
//            this.updateById(new TextbookStudentClaim() {{
//                setModifyUserId(StpUtil.getLoginIdAsLong());
//                setModifyDate(new Date());
//                setId(textbookStudentClaimId);
//                setIsClaim(1);
//            }});
//        }
        return true;
    }

    @Override
    public List<TeacherCheckStuClaimVo> getTeacherCheckStuClaimList(TeacherCheckStuClaimDto dto) {
        List<TeacherCheckStuClaimVo> teacherCheckStuClaimVos = textbookStudentClaimMapper.getTeacherCheckStuClaimList(dto);
        return teacherCheckStuClaimVos;
    }

    @Override
    public List<TextbookClaimVO> getTeacherGetStuNoClaimList(Long studentUserId) {
        MPJLambdaWrapper<TextbookStudentClaim> queryTextbookClaimVOList = new MPJLambdaWrapper<>();
        queryTextbookClaimVOList.selectAs(TextbookStudentClaim::getId, TextbookClaimVO::getTextbookStudentClaimId).selectAs(Textbook::getBookName, TextbookClaimVO::getBookName).select(TextbookStudentClaim.class, x -> VoToColumnUtil.fieldsToColumns(TextbookClaimVO.class).contains(x.getProperty())).leftJoin(Textbook.class, Textbook::getId, TextbookStudentClaim::getTextbookId).eq(TextbookStudentClaim::getStudentUserId, studentUserId).disableSubLogicDel();
        List<TextbookClaimVO> textbookClaimVOList = this.selectJoinList(TextbookClaimVO.class, queryTextbookClaimVOList);
        return textbookClaimVOList;
    }
}
