package com.vctgo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.DateUtils;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.*;
import com.vctgo.system.api.domain.dto.ObserveChildhoodDto;
import com.vctgo.system.api.domain.dto.ObserveChildhoodNewDto;
import com.vctgo.system.api.domain.dto.ObserverTreeClassChildDto;
import com.vctgo.system.api.domain.dto.ToySysClassSettingDto;
import com.vctgo.system.domain.SysAreaSetting;
import com.vctgo.system.domain.SysCity;
import com.vctgo.system.domain.SysReClassUser;
import com.vctgo.system.domain.dto.SysClassSettingDto;
import com.vctgo.system.domain.dto.SysTreeClassInfo;
import com.vctgo.system.domain.vo.SysDownLocation;
import com.vctgo.system.mapper.*;
import com.vctgo.system.service.ISysClassSettingService;
import com.vctgo.system.service.ISysDictDataService;
import com.vctgo.system.util.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 班级设置Service业务层处理
 *
 * @author caesar
 * @date 2023-05-30
 */
@Slf4j
@Service
public class SysClassSettingServiceImpl extends ServiceImpl<SysClassSettingMapper, SysClassSetting> implements ISysClassSettingService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysClassSettingServiceImpl.class);

    private final static String CHECK_EXCEL_ROW = "第%s行 %s列 内容错误请检查";
    private final static String PATTER_YEAR = "^([0-9]{4})$";

    @Autowired
    private SysClassSettingMapper sysClassSettingMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysReClassUserMapper sysReClassUserMapper;

    @Autowired
    private SysReLocationClassMapper sysReLocationClassMapper;

    @Autowired
    private SysLocationSettingMapper sysLocationSettingMapper;

    /**
     * 查询班级设置
     *
     * @param id 班级设置主键
     * @return 班级设置
     */
    @Override
    public SysClassSetting selectSysClassSettingById(Long id) {
        return sysClassSettingMapper.selectById(id);
    }

    /**
     * 查询班级设置列表-分页
     *
     * @param sysClassSetting 班级设置
     * @return 班级设置
     */
    @Override
    public IPage<SysClassSetting> selectSysClassSettingPage(SysClassSetting sysClassSetting) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        IPage<SysClassSetting> pageData = sysClassSettingMapper.selectClassReInfoList(mpPage, sysClassSetting);

        Map<String, Object> params = new HashMap<>();
        params.put("tenantType", SecurityUtils.getTenantType());
        params.put("tenantId", SecurityUtils.getTenantId());
        List<SysUser> sysUserList = sysUserMapper.selectUserListByParams(params);
        Map<Long, String> sysUserMap = sysUserList.stream().filter(element -> element.getUserId() != null).collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
        pageData.getRecords().stream().forEach(obj -> {
            if (sysUserMap.containsKey(obj.getCreateById())) {
                obj.setCreateBy(sysUserMap.get(obj.getCreateById()));
            }
        });
        return pageData;
    }

    @Override
    public List<SysClassSetting> selectSysClassSettingBookList(SysClassSetting sysClassSetting) {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted,ConstantUtils.IS_DELETED_0);
        sysClassSettingWrapper.orderByDesc(SysClassSetting::getEnrollmentYear);
        sysClassSettingWrapper.orderByAsc(SysClassSetting::getGradeIn);
        sysClassSettingWrapper.orderByAsc(SysClassSetting::getClassNumber);
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectList(sysClassSettingWrapper);

        LambdaQueryWrapper<SysReClassUser> sysReClassUserWrapper = new LambdaQueryWrapper<>();
        sysReClassUserWrapper.eq(SysReClassUser::getIsDeleted,ConstantUtils.IS_DELETED_0);
        sysReClassUserWrapper.eq(SysReClassUser::getBindUserId,SecurityUtils.getUserId());
        sysReClassUserWrapper.select(SysReClassUser::getClassId);
        List<SysReClassUser> sysReClassUserList = sysReClassUserMapper.selectList(sysReClassUserWrapper);
        if(CollectionUtils.isEmpty(sysReClassUserList)){
            return  new ArrayList<>();
        }

        List<String> classIdList = sysReClassUserList.stream().map(SysReClassUser::getClassId).map(String::valueOf).collect(Collectors.toList());
        sysClassSettingList = sysClassSettingList.stream().filter(sysClassSettingTmp -> classIdList.contains(sysClassSettingTmp.getId().toString())).collect(Collectors.toList());
        return sysClassSettingList;
    }

    @Override
    public List<SysClassSettingDto> selectAreaClassList(SysClassSetting sysClassSetting) {
        sysClassSetting.setTenantId(SecurityUtils.getTenantId());
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10000L));
        IPage<SysClassSetting> pageData = sysClassSettingMapper.selectClassReInfoList(mpPage, sysClassSetting);
        List<SysClassSettingDto> sysClassSettingDtos =new ArrayList<>();
        if (!pageData.getRecords().isEmpty()) {
            List<SysClassSetting> records = pageData.getRecords();
            List<SysClassSetting> collect = records.stream().filter(v -> StringUtils.isNotEmpty(v.getLocationIdList())).collect(Collectors.toList());
            for (SysClassSetting sysClassSetting1 : collect) {
                 SysClassSettingDto sysClassSettingDto = new SysClassSettingDto();
                 sysClassSettingDto.setClassAlias(sysClassSetting1.getClassName());
                 String locationIdList = sysClassSetting1.getLocationIdList();
                 //只找教室
                 List<SysAreaSetting> sysAreaSettings = sysClassSettingMapper.selectAreaByLocationIdList(locationIdList);
                 if(CollectionUtils.isNotEmpty(sysAreaSettings)){
                     sysClassSettingDto.setAreaSettingList(sysAreaSettings);
                     sysClassSettingDtos.add(sysClassSettingDto);
                 }

            }
            //其他
            List<SysAreaSetting> sysAreaSettings = sysClassSettingMapper.selectOthreArea(sysClassSetting);
            if(CollectionUtils.isNotEmpty(sysAreaSettings)){
                SysClassSettingDto sysClassSettingDto = new SysClassSettingDto();
                sysClassSettingDto.setClassAlias("其他");
                sysClassSettingDto.setAreaSettingList(sysAreaSettings);
                sysClassSettingDtos.add(sysClassSettingDto);

            }
        }
        return sysClassSettingDtos;
    }

    @Override
    public List<SysClassSetting> getEnrollmentYearList() {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted, "0");
        sysClassSettingWrapper.groupBy(SysClassSetting::getEnrollmentYear);
        sysClassSettingWrapper.select(SysClassSetting::getEnrollmentYear);
        return sysClassSettingMapper.selectList(sysClassSettingWrapper);
    }

    /**
     * 查询班级设置列表
     *
     * @param sysClassSetting 班级设置
     * @return 班级设置
     */
    @Override
    public List<SysClassSetting> selectSysClassSettingList(SysClassSetting sysClassSetting) {
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectSysClassSettingList(sysClassSetting);
        for (int i = 0; i < sysClassSettingList.size(); i++) {
            SysClassSetting sysClassSettingTmp = sysClassSettingList.get(i);
            sysClassSettingTmp.setIndex(String.valueOf(i + 1));
            sysClassSettingTmp.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, sysClassSettingTmp.getCreateTime()));
            sysClassSettingTmp.setBindLocationString(sysClassSettingTmp.getLocationName());
        }
        return sysClassSettingList;
    }

    /**
     * 查询年级列表
     */
    @Override
    public List<String> gradeInList() {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted, "0");
        sysClassSettingWrapper.select(SysClassSetting::getGradeIn);
        sysClassSettingWrapper.groupBy(SysClassSetting::getGradeIn);
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectList(sysClassSettingWrapper);
        return sysClassSettingList.isEmpty() ? new ArrayList<>() : sysClassSettingList.stream().map(SysClassSetting::getGradeIn).collect(Collectors.toList());
    }

    /**
     * 通过年级获取对应的班级列表
     */
    @Override
    public List<SysClassSetting> selectClassListByGradeIn(String gradeIn) {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted, "0");
        sysClassSettingWrapper.eq(StringUtils.isNotEmpty(gradeIn), SysClassSetting::getGradeIn, gradeIn);
        sysClassSettingWrapper.select(SysClassSetting::getGradeIn);
        sysClassSettingWrapper.groupBy(SysClassSetting::getGradeIn);
        return sysClassSettingMapper.selectList(sysClassSettingWrapper);
    }

    /**
     * 获取班级树形结构
     *
     * @return 班级设置
     */
    @Override
    public List<SysTreeClassInfo> selectSysTreeClassList() {
        Long tenantId = SecurityUtils.getTenantId();
        return sysClassSettingMapper.selectSysTreeClassList(tenantId);
    }

    /**
     * 获取班级树形结构
     *
     * @return 班级设置
     */
    @Override
    public SysTreeClassInfo selectSysTreeClassInfo() {
        Integer tenantType = SecurityUtils.getTenantType();
        Long tenantId = SecurityUtils.getTenantId();
        String tenantName = SecurityUtils.getTenantName();
        if (tenantType == 1) {
            throw new ServiceException("请切换到指定的幼儿园进行操作");
        }
        SysTreeClassInfo sysTreeClassInfo = new SysTreeClassInfo();
        sysTreeClassInfo.setCode(tenantId);
        sysTreeClassInfo.setName(tenantName);
        sysTreeClassInfo.setLevel(1);
        List<SysTreeClassInfo> childrenList = sysClassSettingMapper.selectClassTreeLevelTwoList(tenantId);
        List<SysTreeClassInfo> grandsonList = sysClassSettingMapper.selectClassTreeLevelThreeList(tenantId);
        List<SysTreeClassInfo> filterGrandsonList = new ArrayList<>();
        for (SysTreeClassInfo children : childrenList) {
            filterGrandsonList = grandsonList.stream().filter(obj -> children.getEnrollmentYear().equals(obj.getEnrollmentYear())
                    && children.getGradeIn().equals(obj.getGradeIn())).collect(Collectors.toList());
            children.setChildren(filterGrandsonList);
        }
        sysTreeClassInfo.setChildren(childrenList);
        return sysTreeClassInfo;
    }

    /**
     * 获取班级学生树形结构
     *
     * @return 班级设置
     */
    @Override
    public List<ObserverTreeClassChildDto> getTreeClassChildList(ObserveChildhoodNewDto observeChildhoodDto) {
        Integer tenantType = SecurityUtils.getTenantType();
        Long tenantId = SecurityUtils.getTenantId();
        observeChildhoodDto.setTenantId(tenantId);
        String tenantName = SecurityUtils.getTenantName();
//        if (tenantType == 1) {
//            throw new ServiceException("请切换到指定的幼儿园进行操作");
//        }
//        SysTreeClassInfo sysTreeClassInfo = new SysTreeClassInfo();
//        sysTreeClassInfo.setCode(tenantId);
//        sysTreeClassInfo.setName(tenantName);
//        sysTreeClassInfo.setLevel(1);
        List<ObserverTreeClassChildDto>resultDto = new ArrayList<>();

        List<ObserveChildhoodNewDto> childrenList = sysClassSettingMapper.selectTreeClassChildList(observeChildhoodDto);
        //提取第一级  年级
        if(CollectionUtils.isNotEmpty(childrenList)){
            Map<Long, List<ObserveChildhoodNewDto>> gradeMap =
                    childrenList.stream().collect(Collectors.groupingBy(ObserveChildhoodNewDto::getCode) );
            for (Long key : gradeMap.keySet()) {
                ObserverTreeClassChildDto grade = new ObserverTreeClassChildDto();
                grade.setCode(gradeMap.get(key).get(0).getCode());
                grade.setGradeName(gradeMap.get(key).get(0).getGradeName());
                grade.setLevel(1);
                List<ObserveChildhoodNewDto> classList=gradeMap.get(key);
                Map<Long, List<ObserveChildhoodNewDto>> classMap =
                        classList.stream().collect(Collectors.groupingBy(ObserveChildhoodNewDto::getClassId) );
                //提取第二级  班级
                List<ObserverTreeClassChildDto>classresultList = new ArrayList<>();
                for (Long classkey : classMap.keySet()) {

                    ObserverTreeClassChildDto class1 = new ObserverTreeClassChildDto();
                    class1.setClassId(classMap.get(classkey).get(0).getClassId());
                    class1.setClassName(classMap.get(classkey).get(0).getClassName());
                    class1.setLevel(2);
                    //第三级 学生
                    class1.setChildren(classMap.get(classkey));
                    classresultList.add(class1);
                    grade.setChildren(classresultList);
                }
                resultDto.add(grade);
            }
        }
        return resultDto;
    }

    /**
     * 新增班级设置
     *
     * @param sysClassSettingList 班级设置
     * @return 结果
     */
    @Override
    public int insertSysClassSetting(List<SysClassSetting> sysClassSettingList) {
        sysClassSettingList.stream().forEach(obj -> obj.setClassName(transferClassName(obj.getGradeIn(), obj.getClassNumber())));
        return saveBatch(sysClassSettingList) ? 1 : 0;
    }

    /**
     * 修改班级设置
     *
     * @param sysClassSetting 班级设置
     * @return 结果
     */
    @Override
    public int updateSysClassSetting(SysClassSetting sysClassSetting) {
        sysClassSetting.setClassName(transferClassName(sysClassSetting.getGradeIn(), sysClassSetting.getClassNumber()));
        return sysClassSettingMapper.updateById(sysClassSetting);
    }

    /**
     * 批量删除班级设置
     *
     * @param ids 需要删除的班级设置主键
     * @return 结果
     */
    @Override
    public int deleteSysClassSettingByIds(Long[] ids) {
        return sysClassSettingMapper.deleteSysClassSettingByIds(ids);
    }

    /**
     * 删除班级设置信息
     *
     * @param id 班级设置主键
     * @return 结果
     */
    @Override
    public int deleteSysClassSettingById(Long id) {
        return sysClassSettingMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void importFile(MultipartFile file) throws Exception {
        ExcelUtil<SysClassSettingDto> util = new ExcelUtil<>(SysClassSettingDto.class);
        List<SysClassSettingDto> sysClassSettingDtoList = util.importExcel(file.getInputStream(), 1);
        if (sysClassSettingDtoList.isEmpty()) {
            throw new ServiceException("上传文件内容不能为空");
        }

        sysClassSettingDtoList.removeIf(Objects::isNull);
        if (sysClassSettingDtoList.isEmpty()) {
            throw new ServiceException("请上传正确格式的excel文件");
        }

        HashSet<String> repeatClassNumberSet = new HashSet<>();
        sysClassSettingDtoList.forEach(sysClassSettingDto -> repeatClassNumberSet.add(sysClassSettingDto.getEnrollmentYear() + "|" + sysClassSettingDto.getGradeIn() + "|" + sysClassSettingDto.getClassNumber()));
        if (repeatClassNumberSet.size() < sysClassSettingDtoList.size()) {
            throw new SecurityException("请先删除表格中的重复数据<相同入学年份、年级、班级编号>再上传");
        }
        HashSet<String> repeatClassAliasSet = new HashSet<>();
        List<String> repeatClassAliasList = new ArrayList<>();
        sysClassSettingDtoList.stream().filter(obj -> StringUtils.isNotBlank(obj.getClassAlias())).forEach(sysClassSettingDto -> {
            repeatClassAliasSet.add(sysClassSettingDto.getEnrollmentYear() + "|" + sysClassSettingDto.getGradeIn() + "|" + sysClassSettingDto.getClassAlias().trim());
            repeatClassAliasList.add(sysClassSettingDto.getEnrollmentYear() + "|" + sysClassSettingDto.getGradeIn() + "|" + sysClassSettingDto.getClassAlias().trim());
        });
        if (repeatClassAliasSet.size() != repeatClassAliasList.size()) {
            throw new SecurityException("请先删除表格中的重复数据<相同入学年份、年级、班级别名>再上传");
        }
        // 获取年级列表
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("toy_release_grade");
        List<SysDictData> gradeDataList = sysDictDataService.selectDictDataList(sysDictData);
        List<String> gradeLabelList = gradeDataList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());

        // 获取班级列表
        sysDictData.setDictType("toy_release_class");
        List<SysDictData> classDataList = sysDictDataService.selectDictDataList(sysDictData);
        List<String> classLabelList = classDataList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());

        // 获取当前幼儿园所有的班级列表
        List<SysClassSetting> sysClassSettings = sysClassSettingMapper.selectSysClassSettingList(SysClassSetting.builder().isDeleted("0").build());
        HashSet<String> classNumberSet = new HashSet<>();
        HashSet<String> classAliasSet = new HashSet<>();
        sysClassSettings.forEach(sysClassSettingTmp -> {
            classNumberSet.add(sysClassSettingTmp.getEnrollmentYear() + "|" + sysClassSettingTmp.getGradeIn() + "|" + sysClassSettingTmp.getClassNumber());
            if (StringUtils.isNotBlank(sysClassSettingTmp.getClassAlias())) {
                classAliasSet.add(sysClassSettingTmp.getEnrollmentYear() + "|" + sysClassSettingTmp.getGradeIn() + "|" + sysClassSettingTmp.getClassAlias());
            }
        });

        // 检查格式是否正确
        for (int i = 1; i <= sysClassSettingDtoList.size(); i++) {
            SysClassSettingDto sysClassSettingDto = sysClassSettingDtoList.get(i - 1);

            if (StringUtils.isEmpty(sysClassSettingDto.getEnrollmentYear())
                    || !Pattern.compile(PATTER_YEAR).matcher(sysClassSettingDto.getEnrollmentYear()).find()) {
                throw new ServiceException(String.format(CHECK_EXCEL_ROW, i, "入学年份"));
            }

            if (StringUtils.isEmpty(sysClassSettingDto.getGradeIn())
                    || !gradeLabelList.contains(sysClassSettingDto.getGradeIn())) {
                throw new ServiceException(String.format(CHECK_EXCEL_ROW, i, "所在年级"));
            }

            if (StringUtils.isEmpty(sysClassSettingDto.getClassNumber())
                    || !classLabelList.contains(sysClassSettingDto.getClassNumber())) {
                throw new ServiceException(String.format(CHECK_EXCEL_ROW, i, "班级编号"));
            }

            if (StringUtils.isNotEmpty(sysClassSettingDto.getClassAlias())
                    && sysClassSettingDto.getClassAlias().length() > 6) {
                throw new ServiceException(String.format("第%s行 %s列 长度不能超过6", i, "班级别名"));
            }

//            if(classAliasString.contains(sysClassSettingDto.getClassAlias())){
//                throw new ServiceException(String.format("第%s行 %s列 班级别名重复!", i, "班级别名"));
//            }

            String enrollmentYear = sysClassSettingDto.getEnrollmentYear();
            String gradeIn = gradeLabelList.contains(sysClassSettingDto.getGradeIn()) ? gradeDataList.stream().filter(gradeData -> gradeData.getDictLabel().equals(sysClassSettingDto.getGradeIn())).findFirst().get().getDictValue() : "";
            String classNumber = classLabelList.contains(sysClassSettingDto.getClassNumber()) ? classDataList.stream().filter(classData -> classData.getDictLabel().equals(sysClassSettingDto.getClassNumber())).findFirst().get().getDictValue() : "";
            String classAlias = sysClassSettingDto.getClassAlias();
            if (classNumberSet.contains(enrollmentYear + "|" + gradeIn + "|" + classNumber)) {
                throw new ServiceException(String.format("第%s行数据与已有数据<相同入学年份、年级、班级编号>重复", i));
            }
            if (StringUtils.isNotBlank(classAlias) && classAliasSet.contains(enrollmentYear + "|" + gradeIn + "|" + classAlias)) {
                throw new ServiceException(String.format("第%s行数据与已有数据<相同入学年份、年级、班级别名>重复", i));
            }
        }

        List<SysClassSetting> sysClassSettingList = new ArrayList<>();
        sysClassSettingDtoList.forEach(sysClassSettingDto -> sysClassSettingList.add(SysClassSetting.builder()
                .enrollmentYear(sysClassSettingDto.getEnrollmentYear())
                .classAlias(sysClassSettingDto.getClassAlias())
                .classNumber(classDataList.stream().filter(classData -> Objects.equals(classData.getDictLabel(), sysClassSettingDto.getClassNumber())).findFirst().get().getDictValue())
                .gradeIn(gradeDataList.stream().filter(gradeData -> Objects.equals(gradeData.getDictLabel(), sysClassSettingDto.getGradeIn())).findFirst().get().getDictValue())
                .build()));
        sysClassSettingList.stream().forEach(obj -> obj.setClassName(transferClassName(obj.getGradeIn(), obj.getClassNumber())));
        saveBatch(sysClassSettingList);
    }

    @Override
    public List<SysClassSetting> repeatCheck(SysClassSetting sysClassSetting) {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.ne(sysClassSetting.getId() != null, SysClassSetting::getId, sysClassSetting.getId());
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted, "0");
        sysClassSettingWrapper.and(qw -> qw.eq(StringUtils.isNotEmpty(sysClassSetting.getClassAlias()), SysClassSetting::getClassAlias, sysClassSetting.getClassAlias())
                .or().eq(StringUtils.isNotEmpty(sysClassSetting.getClassNumber()), SysClassSetting::getClassNumber, sysClassSetting.getClassNumber()));
//        sysClassSettingWrapper.eq(StrUtils.isNotEmpty(sysClassSetting.getClassAlias()), SysClassSetting::getClassAlias, sysClassSetting.getClassAlias());
//        sysClassSettingWrapper.eq(StrUtils.isNotEmpty(sysClassSetting.getClassNumber()), SysClassSetting::getClassNumber, sysClassSetting.getClassNumber());
        sysClassSettingWrapper.eq(SysClassSetting::getEnrollmentYear, sysClassSetting.getEnrollmentYear());
        sysClassSettingWrapper.eq(SysClassSetting::getGradeIn, sysClassSetting.getGradeIn());
        return sysClassSettingMapper.selectList(sysClassSettingWrapper);
    }

    /**
     * 通过位置id获取已绑定的班级列表
     *
     * @param locationId 位置id
     * @return
     */
    @Override
    public List<SysClassSetting> bindClassList(String locationId) {

        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectSysClassSettingBind(locationId);
        setClassName(sysClassSettingList);
        return sysClassSettingList;
    }

    /**
     * 通过位置id获取未绑定的班级列表
     *
     * @param locationId 位置id
     * @return
     */
    @Override
    public List<SysClassSetting> unBindClassList(String locationId) {
        return sysClassSettingMapper.selectSysClassSettingUnBind(locationId);
    }

    private void setClassName(List<SysClassSetting> sysClassSettingList) {
        // 获取年级列表
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("toy_release_grade");
        List<SysDictData> gradeDataList = sysDictDataService.selectDictDataList(sysDictData);

        // 获取班级列表
//        sysDictData.setDictType("toy_release_class");
//        List<SysDictData> classDataList = sysDictDataService.selectDictDataList(sysDictData);

        // 遍历设置班级名称
        sysClassSettingList.forEach(sysClassSetting -> {
            String gradeIn = gradeDataList.stream().filter(gradeData -> gradeData.getDictValue().equals(sysClassSetting.getGradeIn())).findFirst().get().getDictLabel();
//            String classNumber = classDataList.stream().filter(classData -> classData.getDictValue().equals(sysClassSetting.getClassNumber())).findFirst().get().getDictLabel();
            sysClassSetting.setClassName(gradeIn.replace("班", "") + sysClassSetting.getClassNumber() + "班");
        });
    }

    private static String transferClassName(String gradeIn, String classNumber) {
        StringBuffer className = new StringBuffer();
        if (ConstantUtils.GRADE_IN_1.equals(gradeIn)) {
            className.append("小");
        } else if (ConstantUtils.GRADE_IN_2.equals(gradeIn)) {
            className.append("中");
        } else if (ConstantUtils.GRADE_IN_3.equals(gradeIn)) {
            className.append("大");
        }
        try {
//            int number = Integer.parseInt(classNumber);
//            className.append(convert(number));
            className.append(classNumber);
            className.append("班");
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        }
        return className.toString();
    }

    public static String convert(int number) {
        //数字对应的汉字
        String[] num = {"一", "二", "三", "四", "五", "六", "七", "八", "九"};
        //单位
        String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "万亿"};
        //将输入数字转换为字符串
        String result = java.lang.String.valueOf(number);
        //将该字符串分割为数组存放
        char[] ch = result.toCharArray();
        //结果 字符串
        String str = "";
        int length = ch.length;
        for (int i = 0; i < length; i++) {
            int c = (int) ch[i] - 48;
            if (c != 0) {
                str += num[c - 1] + unit[length - i - 1];
            }
        }
        System.out.println(str);
        return str;
    }

    /**
     * 删除幼儿园管理基本信息信息
     *
     * @param ids 幼儿园管理基本信息主键
     * @return 结果
     */
    @Override
    public int logicalDeleteByIds(Long[] ids) {
        SysClassSetting sysClassSetting = new SysClassSetting();
        sysClassSetting.setUpdateById(SecurityUtils.getUserId());
        sysClassSetting.setUpdateBy(SecurityUtils.getUsername());
        sysClassSetting.setUpdateTime(new Date());
        sysClassSetting.setIsDeleted(ConstantUtils.IS_DELETED_1);
        int successCount = sysClassSettingMapper.updateDeletedStatusByIds(ids, sysClassSetting);
        return successCount;
    }

    /**
     * 导出班级批量上传模板
     */
    @Override
    public ResponseEntity<InputStreamResource> exportBatchUploadTemplate(String fileName, HttpServletResponse response, HttpServletRequest request) {
        //ByteArrayInputStream byteArrayInputStream = null;
        //HttpHeaders headers = new HttpHeaders();
        //try {
        //    String requestTemplateUrl = minioUrl + File.separator + SecurityConstants.DETAILS_TENANT + "9999" + File.separator + ConstantUtils.TOY_IMPORT_TEMPLATE + File.separator + fileName;
        //    LOGGER.info("导出班级批量上传模板：" + requestTemplateUrl);
        //    byteArrayInputStream = new ByteArrayInputStream(Jsoup.connect(requestTemplateUrl.replaceAll("\\\\","/")).ignoreContentType(true).method(Connection.Method.GET).execute().bodyAsBytes());
        //    headers.add("Content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        //} catch (IOException e) {
        //    e.printStackTrace();
        //    throw new SecurityException("导出班级批量上传模板失败");
        //}
        //return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(byteArrayInputStream));
        return null;
    }

    @Override
    public Long[] getLocationIdList(Long[] ids) {
        return sysClassSettingMapper.getLocationIdList(ids);
    }

    @Override
    public List<SysDownLocation> getDownLocationList(SysClassSetting sysClassSetting) {
        return sysClassSettingMapper.getDownLocationList(sysClassSetting);
    }

    /**
     * 通过老师信息获取当前老师绑定的班级信息
     *
     * @param userId 教师Id
     * @return
     */
    @Override
    public List<SysClassSetting> selectSysClassUserByUserId(Long userId) {
        return sysClassSettingMapper.selectSysClassUserByUserId(userId.toString());
    }


    /**
     * 通过老师信息获取当前老师绑定的班级列表
     *
     * @param userId 教师Id
     * @return
     */
    @Override
    public List<SysClassSetting> selectSysClassListByUserId(Long userId) {
        List<SysClassSetting> classSettingList = sysClassSettingMapper.selectSysClassUserByUserId(userId.toString());
        for (SysClassSetting classSetting : classSettingList){
            if (ConstantUtils.GRADE_IN_1.equals(classSetting.getGradeIn())) {
                classSetting.setGradeInDesc("小班");
            }
            if (ConstantUtils.GRADE_IN_2.equals(classSetting.getGradeIn())) {
                classSetting.setGradeInDesc("中班");
            }
            if (ConstantUtils.GRADE_IN_3.equals(classSetting.getGradeIn())) {
                classSetting.setGradeInDesc("大班");
            }
            classSetting.setClassAliasDesc(classSetting.getGradeInDesc().replace("班", "") + classSetting.getClassNumber() + "班（" + classSetting.getEnrollmentYear() + "）");
        }
        return classSettingList;
    }

    /**
     * 通过班级Id获取位置和区域信息
     *
     * @param classId 班级Id
     * @return
     */
    @Override
    public AjaxResult selectLocationAndAreaByClassId(String classId) {
        return AjaxResult.success(sysClassSettingMapper.selectLocationAndAreaByClassId(classId));
    }

    /**
     /**
     * 通过年级或班级Id获取位置和区域信息
     *
     * @param gradeIn  年级
     * @param classIds 班级
     * @param selectType 查询类型  1  查询全部  2  按照条件查询
     * @return
     */
    @Override
    public AjaxResult selectLocationAndAreaByGradeInAndClass(String[] gradeIn, String[] classIds, String selectType) {

        if("1".equals(selectType)){
            return AjaxResult.success(sysClassSettingMapper.selectLocationAndAreaList());
        }

        return AjaxResult.success(sysClassSettingMapper.selectLocationAndAreaByGradeInAndClass(gradeIn, classIds));
    }

    /**
     * 通过位置Id获取位置和区域信息
     *
     * @param locationIds 位置Id
     * @return
     */
    @Override
    public AjaxResult selectLocationAndAreaByLocationId(String[] locationIds) {

        // 通过位置Id获取关联位置和区域信息
        List<SysReLocationArea> sysReLocationAreaList = sysClassSettingMapper.selectLocationAndAreaByLocationId(locationIds);

        // 通过位置id获取绑定的年级信息
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectClassListByLocationIds(locationIds);
        sysReLocationAreaList.forEach(sysReLocationArea -> {
            List<SysClassSetting> classSettingList = sysClassSettingList.stream().filter(sysClassSetting -> sysClassSetting.getBindLocationString().equals(sysReLocationArea.getLocationId().toString())).collect(Collectors.toList());
            sysReLocationArea.setSysClassSettingList(classSettingList);
        });
        return AjaxResult.success(sysReLocationAreaList);
    }

    /**
     * 通过位置Id获取位置和区域信息
     *
     * @return
     */
    @Override
    public AjaxResult selectLocationIdAndClass() {
        return AjaxResult.success(sysReLocationClassMapper.selectLocationAndClass());
    }

    @Override
    public AjaxResult selectGradeIn() {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted, ConstantUtils.IS_DELETED_0);
        sysClassSettingWrapper.select(SysClassSetting::getGradeIn);
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectList(sysClassSettingWrapper);
        if (CollectionUtils.isEmpty(sysClassSettingList)) {
            return AjaxResult.success();
        }
        List<String> gradeInList = sysClassSettingList.stream().map(SysClassSetting::getGradeIn).collect(Collectors.toList());
        return AjaxResult.success(gradeInList);
    }

    @Override
    public AjaxResult selectClass(String[] gradeIn) {
        LambdaQueryWrapper<SysClassSetting> sysClassSettingWrapper = new LambdaQueryWrapper<>();
        sysClassSettingWrapper.eq(SysClassSetting::getIsDeleted, ConstantUtils.IS_DELETED_0);
        sysClassSettingWrapper.in(Objects.nonNull(gradeIn) && 0 != gradeIn.length, SysClassSetting::getGradeIn, gradeIn);
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectList(sysClassSettingWrapper);
        return AjaxResult.success(sysClassSettingList);
    }

    /**
     * 获取区域列表
     *
     * @return
     */
    @Override
    public AjaxResult selectArea(String[] classIds, String[] locationIds) {
        List<SysAreaSetting> sysAreaSettings = sysClassSettingMapper.selectAreaList(classIds, locationIds);
        sysAreaSettings = sysAreaSettings.stream().distinct().collect(Collectors.toList());
        return AjaxResult.success(CollectionUtils.isEmpty(sysAreaSettings) ?  new ArrayList<>():sysAreaSettings);
    }

    /**
     * 获取位置列表
     *
     * @return
     */
    @Override
    public AjaxResult selectLocation() {
        LambdaQueryWrapper<SysLocationSetting> sysLocationSettingWrapper = new LambdaQueryWrapper<>();
        sysLocationSettingWrapper.eq(SysLocationSetting::getIsDeleted,ConstantUtils.IS_DELETED_0);
        List<SysLocationSetting> sysLocationSettingList = sysLocationSettingMapper.selectList(sysLocationSettingWrapper);
        if(CollectionUtils.isEmpty(sysLocationSettingList)){
            return AjaxResult.success();
        }
        Map<String, List<SysLocationSetting>> mapLocation = sysLocationSettingList.stream().collect(Collectors.groupingBy(SysLocationSetting::getAttribute));
        return AjaxResult.success(mapLocation);
    }

    @Override
    public List<SysClassSetting> getClassListByLocationId(Long locationId) {
        return sysClassSettingMapper.getClassListByLocationId(locationId);
    }

    @Override
    public List<SysClassSettingDto> getClassListByLocationIdList(List<Long> locationIds) {
        return sysClassSettingMapper.getClassListByLocationIdList(locationIds);
    }

    @Override
    public List<ToySysClassSettingDto> getLocationByGradeIn(ToySysClassSettingDto sysClassSettingDto) {
        return sysClassSettingMapper.getLocationByGradeIn(sysClassSettingDto);
    }

    @Override
    public List<SysClassSetting> getClassSetting(String[] locationIds) {
        return sysClassSettingMapper.getClassSetting(locationIds);
    }

    @Override
    public List<SysClassSetting> selectClassSettingAndLocation() {
        List<SysClassSetting> sysClassSettingList = sysClassSettingMapper.selectClassSettingAndLocation();
        List<String> classIdList = sysClassSettingList.stream().map(SysClassSetting::getId).map(String::valueOf).collect(Collectors.toList());
        List<SysLocationSetting> sysLocationSettingList = sysClassSettingMapper.selectLocationList(classIdList.stream().map(String::valueOf).toArray(String[]::new));
        sysClassSettingList.forEach(sysClassSetting -> {
            Long id = sysClassSetting.getId();
            List<SysLocationSetting> sysLocationSettingListTmp = sysLocationSettingList.stream().filter(sysLocationSetting -> sysLocationSetting.getClassId().longValue() == id.longValue()).collect(Collectors.toList());
            sysClassSetting.setSysLocationSettingList(sysLocationSettingListTmp);
        });
        return sysClassSettingList;
    }

    @Override
    public SysClassSetting getClassSettingInfo(Long id) {
        return sysClassSettingMapper.getClassSettingInfo(id);
    }
}
