package com.jojubanking.boot.module.system.service.student;

import cn.hutool.core.collection.CollUtil;
import com.jojubanking.boot.framework.common.exception.ServiceException;
import com.jojubanking.boot.module.system.controller.admin.user.vo.user.UserImportExcelVO;
import com.jojubanking.boot.module.system.controller.admin.user.vo.user.UserImportRespVO;
import com.jojubanking.boot.module.system.controller.admin.xymain.vo.xyMainExportReqVO;
import com.jojubanking.boot.module.system.controller.app.xytjinfo.vo.studentJfListVO;
import com.jojubanking.boot.module.system.convert.user.UserConvert;
import com.jojubanking.boot.module.system.dal.dataobject.order.OrderDO;
import com.jojubanking.boot.module.system.dal.dataobject.user.AdminUserDO;
import com.jojubanking.boot.module.system.dal.dataobject.xymain.xyMainDO;
import com.jojubanking.boot.module.system.dal.dataobject.xyrw.XyrwDO;
import com.jojubanking.boot.module.system.util.xytj.VeDate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.jojubanking.boot.module.system.controller.admin.student.vo.*;
import com.jojubanking.boot.module.system.dal.dataobject.student.StudentDO;
import com.jojubanking.boot.framework.common.pojo.PageResult;

import com.jojubanking.boot.module.system.convert.student.StudentConvert;
import com.jojubanking.boot.module.system.dal.mysql.student.StudentMapper;

import static com.jojubanking.boot.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jojubanking.boot.module.system.enums.ErrorCodeConstants.*;

/**
 * 学生信息 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public Long createStudent(StudentCreateReqVO createReqVO) {
        // 插入
        StudentDO student = StudentConvert.INSTANCE.convert(createReqVO);
        studentMapper.insert(student);
        // 返回
        return student.getId();
    }

    @Override
    public void updateStudent(StudentUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateStudentExists(updateReqVO.getId());
        // 更新
        StudentDO updateObj = StudentConvert.INSTANCE.convert(updateReqVO);
        studentMapper.updateById(updateObj);
    }

    @Override
    public void updateOrderByNotify(StudentDO studentDO){
        studentMapper.updateOrderByNotify(studentDO);
    }
    @Override
    public void updateOrderByConfirm(StudentDO studentDO){
        studentMapper.updateOrderByConfirm(studentDO);
    }


    @Override
    public void updateStudentXyrwName(StudentDO studentDO){
        studentMapper.updateXyrwName(studentDO);
    }

    @Override
    public void deleteStudent(Long id) {
        // 校验存在
        this.validateStudentExists(id);
        // 删除
        studentMapper.deleteById(id);
    }

    private void validateStudentExists(Long id) {
        if (studentMapper.selectById(id) == null) {
            throw exception(STUDENT_NOT_EXISTS);
        }
    }

    @Override
    public StudentDO getStudent(Long id) {
        return studentMapper.selectById(id);
    }

    @Override
    public List<StudentDO> getStudentList(Collection<Long> ids) {
        return studentMapper.selectBatchIds(ids);
    }
    @Override
    public List<studentJfListVO> getStudentListSimple(String openid, String batchno) {
        return studentMapper.selectbyopenid(openid, batchno);
    }
    @Override
    public StudentDO getStudentListInit(String nationid, String batchno) {
        return studentMapper.selectByNationidForTJ(nationid, batchno);
    }

    @Override
    public PageResult<StudentDO> getStudentPage(StudentPageReqVO pageReqVO, XyrwDO xyrwDO) {
        return studentMapper.selectPage(pageReqVO, xyrwDO);
    }
    @Override
    public PageResult<StudentDO> getStudentHisPage(StudentPageReqVO pageReqVO, XyrwDO xyrwDO) {
        return studentMapper.selectHisPage(pageReqVO, xyrwDO);
    }

    @Override
    public List<StudentDO> getStudentList(StudentExportReqVO exportReqVO) {
        return studentMapper.selectList(exportReqVO);
    }

    @Override
    public List<StudentDO> getStudentListForXy(StudentExportReqVO exportReqVO) {
        return studentMapper.selectListXy(exportReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public StudentImportRespVO importUsers(List<StudentImportExcelVO> importStudents, boolean isUpdateSupport, List<XyrwDO> listXyrw) {
        if (CollUtil.isEmpty(importStudents)) {
            throw exception(USER_IMPORT_LIST_IS_EMPTY);
        }

        StudentImportRespVO respVO = StudentImportRespVO.builder().createStudentnames(new ArrayList<>())
                .updateStudentnames(new ArrayList<>()).failureStudentnames(new LinkedHashMap<>()).build();

        importStudents.forEach(importStudent -> {
            // 校验，判断是否有不符合的原因
//            try {
//                checkCreateOrUpdate(null, null, importStudent.getMobile(), importStudent.getEmail(),
//                        importUser.getDeptId(), null);
//            } catch (ServiceException ex) {
//                respVO.getFailureUsernames().put(importStudent.getName(), ex.getMessage());
//                return;
//            }

            // 判断如果不存在，在进行插入
            StudentDO existStudent = studentMapper.selectByNationidForTJ(importStudent.getNationId(), listXyrw.get(0).getBatchno());
            if (existStudent == null) {
                StudentDO newStudent = StudentConvert.INSTANCE.convert(importStudent);
                newStudent.setStatus(0);
                newStudent.setFeeflag(0);
                newStudent.setDeleted(false);
                newStudent.setCreateTime(VeDate.getNowDate());
                newStudent.setUpdateTime(VeDate.getNowDate());
                newStudent.setBatchno(listXyrw.get(0).getBatchno());
                newStudent.setBatchname(listXyrw.get(0).getBatchName());
                newStudent.setPatid("0");
                studentMapper.insert(newStudent);
                respVO.getCreateStudentnames().add(importStudent.getName());
                return;
            }else{
                // 如果存在，判断是否允许更新
                if (!isUpdateSupport) {
                    respVO.getFailureStudentnames().put(importStudent.getName(), TJR_STUDENT_EXISTS.getMsg());
                    return;
                }
                StudentDO updateStudent = StudentConvert.INSTANCE.convert(importStudent);
                updateStudent.setId(existStudent.getId());
                studentMapper.updateById(updateStudent);
                respVO.getUpdateStudentnames().add(importStudent.getName());
            }
        });
        return respVO;
    }

}
