package cn.iocoder.yudao.module.exam.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.constant.SchoolBaseConstants;
import cn.iocoder.yudao.module.base.service.SchoolNotifyMessageSendService;
import cn.iocoder.yudao.module.course.mapper.ProcessMapper;
import cn.iocoder.yudao.module.exam.entity.ExamBatch;
import cn.iocoder.yudao.module.exam.entity.ExamBatchItem;
import cn.iocoder.yudao.module.exam.mapper.ExamBatchMapper;
import cn.iocoder.yudao.module.exam.service.ExamBatchItemService;
import cn.iocoder.yudao.module.exam.service.ExamBatchService;
import cn.iocoder.yudao.module.exam.vo.ExamBatchItemNewVO;
import cn.iocoder.yudao.module.exam.vo.ExamBatchItemVO;
import cn.iocoder.yudao.module.exam.vo.ExamBatchNewVO;
import cn.iocoder.yudao.module.exam.vo.ExamBatchVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static cn.iocoder.yudao.module.base.utils.DriveSchoolBaseUtil.getSubjectStr;


/**
 * 考试批次主表 Service 实现类
 *
 * @author 若依
 */
@Service
public class ExamBatchServiceImpl extends ServiceImpl<ExamBatchMapper, ExamBatch> implements ExamBatchService {
    @Autowired
    private ExamBatchMapper examBatchMapper;
    @Autowired
    private ProcessMapper processMapper;
    @Autowired
    @Lazy
    private ExamBatchItemService examBatchItemService;
    @Resource
    private SchoolNotifyMessageSendService schoolNotifyMessageSendService;

    /**
     * 分页查询
     *
     * @param pageReqVO TODO
     * @param page      TODO
     * @author vinjor-M
     * @date 15:03 2025/1/14
     **/
    @Override
    public IPage<ExamBatchVO> queryListPage(ExamBatchVO pageReqVO, Page<ExamBatchVO> page) {
        if(StringUtils.isEmpty(pageReqVO.getTimeType())){
            //不是首页过来的，那么代表是教练自己查自己的所有考试记录
            Long userId = SecurityFrameworkUtils.getLoginUserId();
            pageReqVO.setCoachId(userId);
        }else {
            //首页过来的，默认查全部的数据
            String startTimeStr = "";
            String endTimeStr = "";
            if("more".equals(pageReqVO.getTimeType())){
                if(StringUtils.isNotEmpty(pageReqVO.getStartTimeSearch())){
                    startTimeStr = pageReqVO.getStartTimeSearch()+" 00:00:01";
                }
                if(StringUtils.isNotEmpty(pageReqVO.getEndTimeSearch())) {
                    endTimeStr = pageReqVO.getEndTimeSearch() + " 23:59:59";
                }
            }else if("month".equals(pageReqVO.getTimeType())){
                //当月
                startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 00:00:01";
                endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 23:59:59";
            }else if("day".equals(pageReqVO.getTimeType())){
                //当天
                startTimeStr = DateUtil.formatDate(DateUtil.date())+" 00:00:01";
                endTimeStr = DateUtil.formatDate(DateUtil.date())+" 23:59:59";
            }
            pageReqVO.setStartTimeSearch(startTimeStr);
            pageReqVO.setEndTimeSearch(endTimeStr);
        }
        IPage<ExamBatchVO> rtnList = examBatchMapper.queryListPage(pageReqVO, page);
        return rtnList;
    }

    @Override
    public IPage<ExamBatchItemNewVO> queryListPageNew(ExamBatchVO pageReqVO, Page<ExamBatchItemNewVO> page) {
        if(StringUtils.isEmpty(pageReqVO.getTimeType())){
            //不是首页过来的，那么代表是教练自己查自己的所有考试记录
            Long userId = SecurityFrameworkUtils.getLoginUserId();
            pageReqVO.setCoachId(userId);
        }else {
            //首页过来的，默认查全部的数据
            String startTimeStr = "";
            String endTimeStr = "";
            if("more".equals(pageReqVO.getTimeType())){
                if(StringUtils.isNotEmpty(pageReqVO.getStartTimeSearch())){
                    startTimeStr = pageReqVO.getStartTimeSearch()+" 00:00:01";
                }
                if(StringUtils.isNotEmpty(pageReqVO.getEndTimeSearch())) {
                    endTimeStr = pageReqVO.getEndTimeSearch() + " 23:59:59";
                }
            }else if("month".equals(pageReqVO.getTimeType())){
                //当月
                startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 00:00:01";
                endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 23:59:59";
            }else if("day".equals(pageReqVO.getTimeType())){
                //当天
                startTimeStr = DateUtil.formatDate(DateUtil.date())+" 00:00:01";
                endTimeStr = DateUtil.formatDate(DateUtil.date())+" 23:59:59";
            }
            pageReqVO.setStartTimeSearch(startTimeStr);
            pageReqVO.setEndTimeSearch(endTimeStr);
        }
//        IPage<ExamBatchItemNewVO> rtnList = ;
        return examBatchMapper.queryListPageNew(pageReqVO, page);
    }

    /**
     * 送考
     *
     * @param examBatchVO
     * @author vinjor-M
     * @date 23:11 2025/1/20
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createObj(ExamBatchVO examBatchVO) {
        //生成批次编号
        String timestamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        examBatchVO.setBatchName(timestamp);
        this.save(examBatchVO);
        //处理子表数据
        List<ExamBatchItem> itemList = new ArrayList<>();
        examBatchVO.getItemList().forEach(item->{
            ExamBatchItem batchItem = new ExamBatchItem();
            BeanUtils.copyProperties(item,batchItem);
            batchItem.setBatchId(examBatchVO.getId());
            itemList.add(batchItem);
        });
        //存子表数据
        examBatchItemService.saveBatch(itemList);
        //更新每个学生对应学习进度表考试的状态，设置为 已送考
        List<Long> userIdList = examBatchVO.getItemList().stream().map(ExamBatchItem::getUserId).collect(Collectors.toList());
        processMapper.updateProcessBatch(userIdList,examBatchVO.getCourseId(),examBatchVO.getSubject(),examBatchVO.getCoachId());

        // 准备信息内容
        String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_EXAM_BATCH, examBatchVO.getCourseName(), getSubjectStr(examBatchVO.getSubject()), DateUtil.format(examBatchVO.getStartTime(), "yyyy-MM-dd HH:mm:ss"), DateUtil.format(examBatchVO.getEndTime(), "yyyy-MM-dd HH:mm:ss"), examBatchVO.getAddr());

        itemList.forEach(item->{
            // 发送消息
            schoolNotifyMessageSendService.sendMessage(item.getUserId(), message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_MEMBER, item.getTenantId());
        });
    }

    /**
     * 查某一批次考试详情
     *
     * @param id 批次ID
     * @return cn.iocoder.yudao.module.exam.vo.ExamBatchVO
     * @author vinjor-M
     * @date 13:37 2025/1/21
     **/
    @Override
    public ExamBatchVO selectOneById(String id) {
        ExamBatch examBatch = this.getById(id);
        ExamBatchVO examBatchVO = new ExamBatchVO();
        BeanUtils.copyProperties(examBatch,examBatchVO);
        //查子表数据
        List<ExamBatchItemVO> itemVOList = examBatchItemService.selectListByBatchId(id);
        if(null!=itemVOList){
            examBatchVO.setItemList(itemVOList);
        }
        return examBatchVO;
    }

    /**
     * 某一教练学员通过和未通过列表
     */
    @Override
    public IPage<ExamBatchNewVO> getStudentByCoachId(int subject, Long coachId, String ifPass, String name, String sort, String timeType, String startTime, String endTime, Page<ExamBatchNewVO> page) {
        String startTimeStr = "";
        String endTimeStr = "";
        if("more".equals(timeType)){
            if(StringUtils.isNotEmpty(startTime)){
                startTimeStr = startTime+" 00:00:01";
            }
            if(StringUtils.isNotEmpty(endTime)) {
                endTimeStr = endTime + " 23:59:59";
            }
        }else if("month".equals(timeType)){
            //当月
            startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 00:00:01";
            endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 23:59:59";
        }else if("day".equals(timeType)){
            //当天
            startTimeStr = DateUtil.formatDate(DateUtil.date())+" 00:00:01";
            endTimeStr = DateUtil.formatDate(DateUtil.date())+" 23:59:59";
        }
        return examBatchMapper.getStudentByCoachId(subject,coachId,ifPass,name,sort,startTimeStr,endTimeStr,page);
    }

}
