package com.app.service.basics;

import com.app.constant.SchoolConstant;
import com.app.dto.PageResult;
import com.app.dto.basics.GradeClassDto;
import com.app.dto.basics.ResponseSchoolDto;
import com.app.dto.basics.operation.SchoolDto;
import com.app.dto.basics.search.SearchSchoolDto;
import com.app.entity.basics.School;
import com.app.entity.guardian.GuardianChild;
import com.app.mapper.basics.SchoolMapper;
import com.app.mapper.guardian.GuardianChildMapper;
import com.app.service.guardian.GuardianChildService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 功能描述：学校
 *
 * @Auther: 梁展鹏
 * @Date: 2018/7/24 11:38
 */
@Slf4j
@Service
public class SchoolService {

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private GuardianChildMapper guardianChildMapper;

    @Autowired
    private GuardianChildService guardianChildService;

    /**
     * 功能描述：根据[学校标识]获取[学校名称]
     *
     * @param id
     * @return
     */
    public String getName(String id) {
        if (!StringUtils.isEmpty(id)) {
            Optional<School> optional = findById(id);
            if (optional.isPresent()) {
                return optional.get().getName();
            }
        }

        return "";
    }

    public Optional<School> findById(String id) {
        return Optional.ofNullable(schoolMapper.selectById(id));
    }

    /**
     * 功能描述：查询[城市名称]下的所有学校
     *
     * @param city 城市名称
     * @return
     */
    public List<School> findByCity(String city) {
        return schoolMapper.findByCityAndIsDelFalse(city);
    }

    /**
     * 功能描述：查询所有学校
     *
     * @return
     */
    public PageResult<ResponseSchoolDto> page(SearchSchoolDto params) {
        IPage<ResponseSchoolDto> _page = schoolMapper.getList(params, new Page(params.getPage(), params.getSize()));
        return new PageResult(params.getPage(), params.getSize(), _page.getTotal(), _page.getRecords());
    }

    /**
     * 功能描述：获取[学校]的年级班级
     *
     * @param schoolId
     * @return
     */
    public List<GradeClassDto> findByGradeClass(String schoolId) {
        Optional<School> optional = findById(schoolId);
        if (optional.isPresent()) {
            School school = optional.get();
            return SchoolConstant.getSchoolClass4GradeYear(school.getGradeYear());
        }

        return Collections.EMPTY_LIST;
    }

    /**
     * 功能描述：保存/更新[开课]
     *
     * @param school
     * @return
     */
    public School saveOrUpdate(SchoolDto school) {
        School _school;
        if (StringUtils.isEmpty(school.getId())) {
            _school = new School();
            _school.setName(school.getName());
            _school.setGradeYear(school.getGradeYear());
            _school.setProvince(school.getProvince());
            _school.setCity(school.getCity());
            _school.setArea(school.getArea());
            _school.setRemarks(school.getRemarks());
            _school.setOrganId(school.getOrganId());
            schoolMapper.insert(_school);
        } else {
            Optional<School> optional = findById(school.getId());
            _school = optional.get();
            _school.setName(school.getName());
            _school.setGradeYear(school.getGradeYear());
            _school.setProvince(school.getProvince());
            _school.setCity(school.getCity());
            _school.setArea(school.getArea());
            _school.setRemarks(school.getRemarks());
            _school.setOrganId(school.getOrganId());
            schoolMapper.updateById(_school);
        }

        return _school;
    }

    /**
     * 功能描述：替换[学校]删除状态
     *
     * @param id
     */
    public void handleIsDel(String id) {
        Optional<School> optional = findById(id);
        if (optional.isPresent()) {
            School school = optional.get();
            school.setIsDel(!school.getIsDel());
            schoolMapper.updateById(school);
        }
    }

    /**
     * 功能描述：把[学校]各个年级升级，高年级做毕业处理
     *
     * @param schoolId 学校标识
     */
    public void upLevel(String schoolId) {
        Optional<School> optionalSchool = findById(schoolId);
        if (!optionalSchool.isPresent()) {
            return;
        }

        /* 查询学校的年级设置 */
        School school = optionalSchool.get();
        for (String gradeYear : school.getGradeYear().split(",")) {
            // todo add by 梁展鹏 这里漏了一种情况，假如是9年制、12年制的学校。高年级不应该毕业。而是直升...
            // 解决方案：全部gradeName从中文更换为数字方式。客户端重新翻译展示
            graduateBySchoolId(schoolId, gradeYear); // 高年级置为毕业
            upLevelBySchoolId(schoolId, gradeYear); // 低年级全部升一级
        }
    }

    /**
     * 功能描述：替换[学校]删除状态
     *
     * @param schoolId  学校标识
     * @param gradeYear 学校年级设置
     */
    private void upLevelBySchoolId(String schoolId, String gradeYear) {
        for (String gradeName : SchoolConstant.getSchoolByUpLevel(gradeYear)) {
            /* 查询年级的学生 */
            List<GuardianChild> guardianChildList = guardianChildService.findBySchoolIdAndGradeName(schoolId, gradeName);

            for (GuardianChild guardianChild : guardianChildList) {
                guardianChild.setGradeName(guardianChild.getGradeName() + 1);
//                guardianChild.setGradeName(SchoolConstant.getSchoolNextGradeName(gradeYear, gradeName));
                guardianChildMapper.updateById(guardianChild);
            }
        }
    }

    /**
     * 功能描述：把学校高年级的学生设置为毕业状态
     *
     * @param schoolId  学校标识
     * @param gradeYear 学校年级设置
     */
    private void graduateBySchoolId(String schoolId, String gradeYear) {
        String gradeName = SchoolConstant.getSchoolByIsGraduate(gradeYear); // 年级名称

        /* 查询学校现有的最高年级学生 */
        List<GuardianChild> guardianChildList = guardianChildService.findBySchoolIdAndGradeName(schoolId, gradeName);

        /* 把对应的学生置为毕业 */
        for (GuardianChild guardianChild : guardianChildList) {
            guardianChild.setIsGraduate(Boolean.TRUE);
            guardianChildMapper.updateById(guardianChild);
        }
    }

}
