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

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.enums.GenderEnum;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.base.entity.BaseSemester;
import com.xjrsoft.module.base.service.IBaseSemesterService;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.student.dto.BaseStudentScholarshipApplicantCategoryPageDto;
import com.xjrsoft.module.student.entity.BaseStudentScholarshipApplicant;
import com.xjrsoft.module.student.entity.BaseStudentScholarshipCategory;
import com.xjrsoft.module.student.mapper.BaseStudentMapper;
import com.xjrsoft.module.student.mapper.BaseStudentScholarshipApplicantMapper;
import com.xjrsoft.module.student.service.IBaseStudentScholarshipApplicantService;
import com.xjrsoft.module.student.service.IBaseStudentScholarshipCategoryService;
import com.xjrsoft.module.student.vo.BaseStudentScholarshipApplicantCategoryPageVo;
import com.xjrsoft.module.student.vo.BaseStudentScholarshipApplicantPageVo;
import com.xjrsoft.module.student.vo.ScholarshipApplicantImportVo;
import com.xjrsoft.module.student.vo.StudentInfoVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @title: 奖学金申请
 * @Author dzx
 * @Date: 2023-11-23
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class BaseStudentScholarshipApplicantServiceImpl extends MPJBaseServiceImpl<BaseStudentScholarshipApplicantMapper, BaseStudentScholarshipApplicant> implements IBaseStudentScholarshipApplicantService {
    private final BaseStudentScholarshipApplicantMapper applicantMapper;
    private final IBaseSemesterService semesterService;
    private final IBaseStudentScholarshipCategoryService categoryService;
    private final IUserService userService;
    @Override
    public Page<BaseStudentScholarshipApplicantCategoryPageVo> getScholarshiPage(Page<BaseStudentScholarshipApplicantCategoryPageDto> page, BaseStudentScholarshipApplicantCategoryPageDto dto) {
        Page<BaseStudentScholarshipApplicantCategoryPageVo> result = applicantMapper.getScholarshiPage(page, dto);
        return result;
    }


    private final BaseStudentScholarshipApplicantMapper scholarshipApplicantMapper;

    private final BaseStudentMapper studentMapper;

    @Override
    public Boolean processDataHandler(Long dataId) {
        if (dataId == null) {
            return false;
        }
        // 原始数据
        BaseStudentScholarshipApplicant scholarshipApplicant = scholarshipApplicantMapper.selectById(dataId);
        // 获取学生信息
        StudentInfoVo studentInfo = studentMapper.getStudentInfo(scholarshipApplicant.getApplicantUserId());
        scholarshipApplicant.setGradeName(studentInfo.getGradeName());
        scholarshipApplicant.setClassName(studentInfo.getClassName());
        scholarshipApplicant.setName(studentInfo.getStudentName());
        scholarshipApplicant.setStudentId(studentInfo.getStudentId());
        scholarshipApplicant.setGenderName(GenderEnum.getValue(studentInfo.getGender()));
        scholarshipApplicant.setEnrollTypeCn(studentInfo.getEnrollmentType());
        scholarshipApplicant.setMajorName(studentInfo.getMajorName());

        return updateById(scholarshipApplicant);
    }

    @Override
    public List<Map<String, String>> importData(MultipartFile file) throws IOException {
        List<ScholarshipApplicantImportVo> dataList = EasyExcel.read(file.getInputStream()).headRowNumber(3).head(ScholarshipApplicantImportVo.class).sheet().doReadSync();
        List<BaseStudentScholarshipApplicant> applicantList = this.list(
                new QueryWrapper<BaseStudentScholarshipApplicant>().lambda()
                        .select(BaseStudentScholarshipApplicant::getId)
                        .select(BaseStudentScholarshipApplicant.class,x -> VoToColumnUtil.fieldsToColumns(BaseStudentScholarshipApplicantPageVo.class).contains(x.getProperty()))
                        .eq(BaseStudentScholarshipApplicant::getStatus, 1)
        );

        List<Long> userIds = applicantList.stream().map(BaseStudentScholarshipApplicant::getApplicantUserId).collect(Collectors.toList());
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().in(User::getId, userIds)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));

        List<BaseSemester> semesterList = semesterService.list(
                new QueryWrapper<BaseSemester>().lambda()
                        .select(BaseSemester::getId)
                        .select(BaseSemester.class, x -> VoToColumnUtil.fieldsToColumns(BaseSemester.class).contains(x.getProperty()))
                        .eq(BaseSemester::getDeleteMark, DeleteMark.NODELETE.getCode())
        );
        Map<String, Long> semesterMap = semesterList.stream().collect(Collectors.toMap(BaseSemester::getName, BaseSemester::getId));

        List<BaseStudentScholarshipCategory> categoryList = categoryService.list(
                new QueryWrapper<BaseStudentScholarshipCategory>().lambda()
                        .select(BaseStudentScholarshipCategory::getId)
                        .select(BaseStudentScholarshipCategory.class, x -> VoToColumnUtil.fieldsToColumns(BaseStudentScholarshipCategory.class).contains(x.getProperty()))
                        .eq(BaseStudentScholarshipCategory::getDeleteMark, DeleteMark.NODELETE.getCode())
        );

        Map<String, BaseStudentScholarshipCategory> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseStudentScholarshipCategory::getName, x -> x));
        Map<String, Long> categorySemeterMap = categoryList.stream().collect(Collectors.toMap(BaseStudentScholarshipCategory::getName, BaseStudentScholarshipCategory::getBaseSemesterId));

        List<Map<String, String>> errorList = new ArrayList<>();
        List<BaseStudentScholarshipApplicant> updateList = new ArrayList<>();
        for (ScholarshipApplicantImportVo importVo : dataList) {
            List<String> errorMsg = new ArrayList<>();
            if(StrUtil.isEmpty(importVo.getSemesterName()) || StrUtil.isEmpty(importVo.getName()) || StrUtil.isEmpty(importVo.getCredentialNumber())
            || StrUtil.isEmpty(importVo.getScholarshipCategoryName()) || importVo.getScholarshipLevel() == null){
                errorMsg.add("有未填写的列");
            }
            if(semesterMap.get(importVo.getSemesterName()) == null){
                errorMsg.add("学期填写不正确");
            }
            Long semesterId = semesterMap.get(importVo.getSemesterName());
            if(categoryMap.get(importVo.getScholarshipCategoryName()) == null){
                errorMsg.add("奖学金名称填写不正确");
            }
            BaseStudentScholarshipCategory category = categoryMap.get(importVo.getScholarshipCategoryName());
            for (BaseStudentScholarshipApplicant applicant : applicantList) {
                User user = userMap.get(applicant.getApplicantUserId());
                Long baseSemesterId = categorySemeterMap.get(importVo.getScholarshipCategoryName());
                if(baseSemesterId.equals(semesterId)
                        && importVo.getName().equals(user.getName())
                        && importVo.getCredentialNumber().equals(user.getCredentialNumber())){
                    applicant.setBaseStudentScholarshipCategoryId(category.getId());
                    applicant.setReviewStatus(1);
                    applicant.setAmount(category.getTotalAmount());
                    applicant.setScholarshipLevel(importVo.getScholarshipLevel());
                    updateList.add(applicant);
                }
            }
            if(!errorMsg.isEmpty()){
                LinkedHashMap<String, String> map = new LinkedHashMap<>();
                map.put("学期", importVo.getSemesterName());
                map.put("姓名", importVo.getName());
                map.put("身份证号", importVo.getCredentialNumber());
                map.put("奖学金名称", importVo.getScholarshipCategoryName());
                map.put("获奖等级", importVo.getScholarshipLevel() + "");
                map.put("错误信息", errorMsg.toString().replace("[", "").replace("]", ""));
                errorList.add(map);
            }
        }
        if(!updateList.isEmpty()){
            this.updateBatchById(updateList);
        }
        return errorList;
    }
}
