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

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.base.constant.SchoolBaseConstants;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolStudent;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolStudentService;
import cn.iocoder.yudao.module.base.service.SchoolNotifyMessageSendService;
import cn.iocoder.yudao.module.course.entity.Process;
import cn.iocoder.yudao.module.course.entity.SchoolCourseOrder;
import cn.iocoder.yudao.module.course.service.ProcessService;
import cn.iocoder.yudao.module.course.service.SchoolCourseOrderService;
import cn.iocoder.yudao.module.course.vo.ProcessVO;
import cn.iocoder.yudao.module.exam.entity.ExamBatch;
import cn.iocoder.yudao.module.exam.entity.ExamBatchItem;
import cn.iocoder.yudao.module.exam.service.ExamBatchItemService;
import cn.iocoder.yudao.module.exam.service.ExamBatchService;
import cn.iocoder.yudao.module.exam.service.impl.ExamBatchItemServiceImpl;
import cn.iocoder.yudao.module.exam.vo.ExamBatchItemNewVO;
import cn.iocoder.yudao.module.jx.domain.StudentScoreInput;
import cn.iocoder.yudao.module.jx.mapper.StudentScoreInputMapper;
import cn.iocoder.yudao.module.jx.service.StudentScoreInputService;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
public class StudentScoreInputServiceImpl implements StudentScoreInputService {
    @Autowired
    private ProcessService processService;

    @Autowired
    private ExamBatchService examBatchService;

    @Autowired
    private ExamBatchItemService examBatchItemService;

    @Autowired
    private DlDriveSchoolStudentService dlDriveSchoolStudentService;

    @Autowired
    private ExamBatchItemServiceImpl examBatchItemServiceImpl;

    @Autowired
    private StudentScoreInputMapper studentScoreInputMapper;

    @Autowired
    private SchoolCourseOrderService schoolCourseOrderService;

    @Resource
    private RoleApi roleApi;

    @Autowired
    private SchoolNotifyMessageSendService schoolNotifyMessageSendService;

    @Resource
    private AdminUserApi userApi;

    /**
     * 录入学员成绩
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scoreInput(StudentScoreInput studentScoreInput) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO sysUser = userApi.getUser(userId);
        // 获取当前进度信息，设置考试成绩等信息
        ProcessVO  processVO = BeanUtils.toBean(processService.getById(studentScoreInput.getProcessId()), ProcessVO.class);
        processVO.setExamStatus(studentScoreInput.getExamStatus());
        processVO.setExamScore(studentScoreInput.getExamScore());
        processVO.setExamTime(studentScoreInput.getExamTime());
        processVO.setExamNum(studentScoreInput.getExamNum());
        processVO.setStatus(studentScoreInput.getStatus());
        processVO.setImages(studentScoreInput.getImages());
        processVO.setRemark(studentScoreInput.getRemark());
        processVO.setInputName(sysUser.getNickname());
        processVO.setInputUserId(sysUser.getId());
        processService.updateById(processVO);

        // 如果是科2和科3 需要创建批次信息
        if(studentScoreInput.getSubject() == 2 || studentScoreInput.getSubject() == 3){

            if("1".equals(studentScoreInput.getExamStatus())){
               // 向会计和出纳发送信息
                Long tenantId = TenantContextHolder.getTenantId();
                List<UserDTO> kjStaffList = roleApi.selectUserListByRoleCode(tenantId, "kj");
                List<UserDTO> cnStaffList = roleApi.selectUserListByRoleCode(tenantId, "cn");
                List<UserDTO> allStaffList = new ArrayList<>();
                allStaffList.addAll(kjStaffList);
                allStaffList.addAll(cnStaffList);
                DlDriveSchoolStudent studentByUserId = dlDriveSchoolStudentService.getStudentByUserId(studentScoreInput.getUserId());
                String studentIdCard = null;
                if(studentByUserId != null){
                    studentIdCard = studentByUserId.getIdCard();
                }
                if (allStaffList != null && !allStaffList.isEmpty()) {
                    String officeMessage = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_AUDIT_WAIT, studentScoreInput.getUserName(), studentIdCard, studentScoreInput.getCourseName(), studentScoreInput.getSubject());
                    for (UserDTO staff : allStaffList) {
                        schoolNotifyMessageSendService.sendMessage(staff.getId(), officeMessage, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, tenantId);
                    }
                }

            }
            // 生成批次信息
            ExamBatch  examBatch = new ExamBatch();
            String timestamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
            examBatch.setBatchName(timestamp);
            examBatch.setCourseId(studentScoreInput.getCourseId());
            examBatch.setCourseName(studentScoreInput.getCourseName());
            examBatch.setCoachId(studentScoreInput.getCoachId());
            examBatch.setCoachName(studentScoreInput.getCoachName());
            examBatch.setStartTime(studentScoreInput.getStartTime());
            examBatch.setEndTime(studentScoreInput.getEndTime());
            examBatch.setSubject(studentScoreInput.getSubject());
            examBatch.setAddrId(studentScoreInput.getAddrId());
            examBatch.setAddr(studentScoreInput.getAddr());
            examBatch.setRemark(studentScoreInput.getRemark());
            examBatch.setImages(studentScoreInput.getImages());
            examBatch.setTransWay(studentScoreInput.getTransWay());
            examBatchService.save(examBatch);

            // 生成批次子表信息
            ExamBatchItem examBatchItem = new ExamBatchItem();
            examBatchItem.setBatchId(examBatch.getId());
            examBatchItem.setUserId(studentScoreInput.getUserId());
            examBatchItem.setUserName(studentScoreInput.getUserName());
            examBatchItem.setFraction(studentScoreInput.getExamScore());
            examBatchItem.setIfPass("1".equals(studentScoreInput.getExamStatus()));
            examBatchItem.setImages(studentScoreInput.getImages());
            examBatchItemService.save(examBatchItem);
            // 更新批次通过率
            examBatchItemServiceImpl.updateBatchPassRate(examBatch.getId());
        }
        if(studentScoreInput.getSubject() == 4 && "1".equals(studentScoreInput.getExamStatus())){
            // 修改订单表的拿证时间
            schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                  .eq(SchoolCourseOrder::getCourseId, studentScoreInput.getCourseId())
                  .eq(SchoolCourseOrder::getUserId, studentScoreInput.getUserId())
                  .eq(SchoolCourseOrder::getCoachUserId, studentScoreInput.getCoachId())
                    .in(SchoolCourseOrder::getPaymentStatus, Arrays.asList("2", "3", "4"))
                    .eq(SchoolCourseOrder::getIfEnd, false)
                    .eq(SchoolCourseOrder::getIfAssignmentCoach, true)
                    .set(SchoolCourseOrder::getPassTime, studentScoreInput.getExamTime()));
        }
        if(studentScoreInput.getSubject() == 3 && "1".equals(studentScoreInput.getExamStatus())){
            schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                    .eq(SchoolCourseOrder::getCourseId, studentScoreInput.getCourseId())
                    .eq(SchoolCourseOrder::getUserId, studentScoreInput.getUserId())
                    .eq(SchoolCourseOrder::getCoachUserId, studentScoreInput.getCoachId())
                    .in(SchoolCourseOrder::getPaymentStatus, Arrays.asList("2", "3", "4"))
                    .eq(SchoolCourseOrder::getIfEnd, false)
                    .eq(SchoolCourseOrder::getIfAssignmentCoach, true)
                    .set(SchoolCourseOrder::getGradTime, studentScoreInput.getExamTime()));
        }
        // 修改下一课程状态
        this.updateNextSubjectStatus(studentScoreInput);
    }

    /**
     * 更新下一个科目的状态
     */
    public void updateNextSubjectStatus(StudentScoreInput studentScoreInput) {
        Process process = processService.getById(studentScoreInput.getProcessId());
        // 通过考试
        if(studentScoreInput.getExamStatus().equals("1")){

            if(process.getSubject() == 4){
                /*dlDriveSchoolStudentService.adminUpdateStudentPassAndGradTime(studentScoreInput.getExamTime(), null, studentScoreInput.getUserId(), studentScoreInput.getCourseId(), studentScoreInput.getTenantId());*/
            } else if (process.getSubject() == 3) {
                processService.update(Wrappers.lambdaUpdate(Process.class)
                        .eq(Process::getCourseId, studentScoreInput.getCourseId())
                        .eq(Process::getUserId, studentScoreInput.getUserId())
                        .eq(Process::getCoachId, studentScoreInput.getCoachId())
                        .eq(Process::getSubject, 4)
                        .set(Process::getStatus, 1));
                /*dlDriveSchoolStudentService.adminUpdateStudentPassAndGradTime(null,studentScoreInput.getExamTime(), studentScoreInput.getUserId(), studentScoreInput.getCourseId(), studentScoreInput.getTenantId());*/
            } else if (process.getSubject() == 2) {
                processService.update(Wrappers.lambdaUpdate(Process.class)
                        .eq(Process::getCourseId, studentScoreInput.getCourseId())
                        .eq(Process::getUserId, studentScoreInput.getUserId())
                        .eq(Process::getCoachId, studentScoreInput.getCoachId())
                        .eq(Process::getSubject, 3)
                        .ne(Process::getStatus, 2)
                        .set(Process::getStatus, 1));
            } else if (process.getSubject() == 1) {
                processService.update(Wrappers.lambdaUpdate(Process.class)
                        .eq(Process::getCourseId, studentScoreInput.getCourseId())
                        .eq(Process::getUserId, studentScoreInput.getUserId())
                        .eq(Process::getCoachId, studentScoreInput.getCoachId())
                        .eq(Process::getSubject, 2)
                        .set(Process::getStatus, 1));
            }
        } else {
            process.setStatus("1");
            processService.updateById(process);
        }

    }

    /**
     * 修改学员成绩
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scoreEdit(StudentScoreInput studentScoreInput) {

        // 获取当前进度信息，设置考试成绩等信息
        ProcessVO  processVO = BeanUtils.toBean(processService.getById(studentScoreInput.getProcessId()), ProcessVO.class);
        processVO.setExamStatus(studentScoreInput.getExamStatus());
        processVO.setExamScore(studentScoreInput.getExamScore());
        processVO.setExamTime(studentScoreInput.getExamTime());
        processVO.setExamNum(studentScoreInput.getExamNum());
        processVO.setStatus(studentScoreInput.getStatus());
        processVO.setImages(studentScoreInput.getImages());
        processVO.setRemark(studentScoreInput.getRemark());
        processService.updateById(processVO);

        // 如果是科2和科3 需要查询批次信息,修改对应批次子表的信息以及批次的通过率
        if(studentScoreInput.getSubject() == 3 || studentScoreInput.getSubject() == 2){
            ExamBatchItemNewVO examBatchItemNewVOS = studentScoreInputMapper.selectBatch(studentScoreInput);
            if(examBatchItemNewVOS.getBatchId() != null && examBatchItemNewVOS.getBatchItemId()!= null){
                examBatchItemService.update(Wrappers.lambdaUpdate(ExamBatchItem.class)
                        .eq(ExamBatchItem::getId, examBatchItemNewVOS.getBatchItemId())
                        .eq(ExamBatchItem::getUserId, studentScoreInput.getUserId())
                        .set(ExamBatchItem::getFraction, studentScoreInput.getExamScore())
                       .set(ExamBatchItem::getIfPass, "1".equals(studentScoreInput.getExamStatus()))
                      .set(ExamBatchItem::getImages, studentScoreInput.getImages()));

                examBatchItemServiceImpl.updateBatchPassRateNew(examBatchItemNewVOS.getBatchId());
            }
        }
        if(studentScoreInput.getSubject() == 4 && "1".equals(studentScoreInput.getExamStatus())){
          // 如果是科目四，需要修改订单表的拿证时间
            schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                    .eq(SchoolCourseOrder::getCourseId, studentScoreInput.getCourseId())
                    .eq(SchoolCourseOrder::getUserId, studentScoreInput.getUserId())
                    .eq(SchoolCourseOrder::getCoachUserId, studentScoreInput.getCoachId())
                    .in(SchoolCourseOrder::getPaymentStatus, Arrays.asList("2", "3", "4"))
                    .eq(SchoolCourseOrder::getIfEnd, false)
                    .eq(SchoolCourseOrder::getIfAssignmentCoach, true)
                    .set(SchoolCourseOrder::getPassTime, studentScoreInput.getExamTime()));
        } else if (studentScoreInput.getSubject() == 4 && "0".equals(studentScoreInput.getExamStatus())) {
            schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                    .eq(SchoolCourseOrder::getCourseId, studentScoreInput.getCourseId())
                    .eq(SchoolCourseOrder::getUserId, studentScoreInput.getUserId())
                    .eq(SchoolCourseOrder::getCoachUserId, studentScoreInput.getCoachId())
                    .in(SchoolCourseOrder::getPaymentStatus, Arrays.asList("2", "3", "4"))
                    .eq(SchoolCourseOrder::getIfEnd, false)
                    .eq(SchoolCourseOrder::getIfAssignmentCoach, true)
                    .set(SchoolCourseOrder::getPassTime, null));
        } else if (studentScoreInput.getSubject() == 3 && "1".equals(studentScoreInput.getExamStatus())) {
            schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                    .eq(SchoolCourseOrder::getCourseId, studentScoreInput.getCourseId())
                    .eq(SchoolCourseOrder::getUserId, studentScoreInput.getUserId())
                    .eq(SchoolCourseOrder::getCoachUserId, studentScoreInput.getCoachId())
                    .in(SchoolCourseOrder::getPaymentStatus, Arrays.asList("2", "3", "4"))
                    .eq(SchoolCourseOrder::getIfEnd, false)
                    .eq(SchoolCourseOrder::getIfAssignmentCoach, true)
                    .set(SchoolCourseOrder::getGradTime, studentScoreInput.getExamTime()));
        } else if (studentScoreInput.getSubject() == 3 && "0".equals(studentScoreInput.getExamStatus())) {
            schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                    .eq(SchoolCourseOrder::getCourseId, studentScoreInput.getCourseId())
                    .eq(SchoolCourseOrder::getUserId, studentScoreInput.getUserId())
                    .eq(SchoolCourseOrder::getCoachUserId, studentScoreInput.getCoachId())
                    .in(SchoolCourseOrder::getPaymentStatus, Arrays.asList("2", "3", "4"))
                    .eq(SchoolCourseOrder::getIfEnd, false)
                    .eq(SchoolCourseOrder::getIfAssignmentCoach, true)
                    .set(SchoolCourseOrder::getGradTime, null));
        }
    }


}
