package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.ClassUtils;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.*;
import org.dromara.system.mapper.StudentInfoOldMapper;
import org.dromara.system.mapper.StudentLiveOldMapper;
import org.dromara.system.mapper.StudentMindOldMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.StudentInfoBo;
import org.dromara.system.domain.vo.StudentInfoVo;
import org.dromara.system.mapper.StudentInfoMapper;
import org.dromara.system.service.IStudentInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 学生档案信息Service业务层处理
 *
 * @author Lion Li
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class StudentInfoServiceImpl implements IStudentInfoService {

    private final StudentInfoMapper baseMapper;
    private final StudentInfoOldMapper studentInfoOldMapper;
    private final StudentLiveOldMapper studentLiveOldMapper;
    private final StudentMindOldMapper studentMindOldMapper;

    /**
     * 查询学生档案信息
     */
    @Override
    public StudentInfoVo queryById(Long id){
        return baseMapper.selectStudentInfoById(id);
    }

    /**
     * 查询学生档案信息列表
     */
    @Override
    public TableDataInfo<StudentInfoVo> queryPageList(StudentInfoBo bo, PageQuery pageQuery) {

        LoginUser user = LoginHelper.getLoginUser();
        Map<String, Object> params = bo.getParams();
        String role = "";
        if (params != null && params.size() > 0) {
            role = (String) params.get("role");
        }
        if("parents".equals(role)){
            bo.setParentsId(user.getUserId());
        }
        //return baseMapper.selectStudentInfoList(pageQuery,bo);

        QueryWrapper<StudentInfo> lqw = buildQueryWrapper(bo);
        Page<StudentInfoVo> result = baseMapper.selectStudentInfoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }



    /**
     * 查询学生档案信息列表
     */
    @Override
    public List<StudentInfoVo> queryList(StudentInfoBo bo) {
        QueryWrapper<StudentInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectStudentInfo(lqw);
    }

    private QueryWrapper<StudentInfo> buildQueryWrapper(StudentInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<StudentInfo> lqw = Wrappers.query();
        lqw.eq(bo.getStudentId() != null && bo.getStudentId()!= 0L, "s.student_id", bo.getStudentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), "s.name", bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), "s.sex", bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), "s.age", bo.getAge());
        lqw.like(StringUtils.isNotBlank(bo.getFamilyName()), "s.family_name", bo.getFamilyName());
        lqw.eq(StringUtils.isNotBlank(bo.getSchool()), "s.school", bo.getSchool());
        lqw.eq(StringUtils.isNotBlank(bo.getStudentNumber()), "s.student_number", bo.getStudentNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), "s.id_card", bo.getIdCard());
        lqw.eq(StringUtils.isNotBlank(bo.getIsNearsightedness()), "s.is_nearsightedness", bo.getIsNearsightedness());
        lqw.eq(StringUtils.isNotBlank(bo.getDegreeMyopia()), "s.degree_myopia", bo.getDegreeMyopia());
        lqw.eq(StringUtils.isNotBlank(bo.getIsFarsightedness()), "s.is_farsightedness", bo.getIsFarsightedness());
        lqw.eq(StringUtils.isNotBlank(bo.getFarsightedness()), "s.farsightedness", bo.getFarsightedness());
        lqw.eq(StringUtils.isNotBlank(bo.getHeight()), "s.height", bo.getHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getWeight()), "s.weight", bo.getWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getBloodType()), "s.blood_type", bo.getBloodType());
        lqw.eq(StringUtils.isNotBlank(bo.getPoliticalStatus()), "s.political_status", bo.getPoliticalStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getHealth()), "s.health", bo.getHealth());
        lqw.eq(StringUtils.isNotBlank(bo.getMind()), "s.mind", bo.getMind());
        lqw.eq(StringUtils.isNotBlank(bo.getEmergencyContact()), "s.emergency_contact", bo.getEmergencyContact());
        lqw.eq(StringUtils.isNotBlank(bo.getEmergencyContactTelephone()), "s.emergency_contact_telephone", bo.getEmergencyContactTelephone());
        lqw.like(StringUtils.isNotBlank(bo.getFatherName()), "s.father_name", bo.getFatherName());
        lqw.eq(StringUtils.isNotBlank(bo.getFatherTelephone()), "s.father_telephone", bo.getFatherTelephone());
        lqw.like(StringUtils.isNotBlank(bo.getMotherName()), "s.mother_name", bo.getMotherName());
        lqw.eq(StringUtils.isNotBlank(bo.getMotherTelephone()), "s.mother_telephone", bo.getMotherTelephone());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), "s.address", bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getIsMedicalHistory()), "s.is_medical_history", bo.getIsMedicalHistory());
        lqw.eq(StringUtils.isNotBlank(bo.getIsLset()), "s.is_lset", bo.getIsLset());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPoverty()), "s.is_poverty", bo.getIsPoverty());
        lqw.eq(StringUtils.isNotBlank(bo.getClassId()), "f.class_id", bo.getClassId());
        lqw.eq(bo.getParentsId()!= null && bo.getParentsId()!= 0L, "f.parents_id", bo.getParentsId());
        lqw.orderByDesc("s.create_time");
        return lqw;
    }

    /**
     * 新增学生档案信息
     */
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Void> insertByBo(StudentInfoBo bo) {
        //查询数据库是否存在信息
        StudentInfoBo student = new StudentInfoBo();
        student.setStudentId(bo.getStudentId());
        QueryWrapper<StudentInfo> lqw = buildQueryWrapper(student);
        List<StudentInfoVo> studentInfos = baseMapper.selectStudentInfo(lqw);
        if(studentInfos!=null && studentInfos.size()>0){
            return R.fail("该学生已存在，请勿重复添加");
        }

        //新增 心理健康
        StudentMindOld studentMindOld = new StudentMindOld();
        ClassUtils.copyProperties(student, studentMindOld);
        studentMindOld.setCreateTime(DateUtils.getNowDate());
        studentMindOld.setUpdateTime(DateUtils.getNowDate());
        studentMindOldMapper.insert(studentMindOld);

        //新增 身高体重
        StudentLiveOld studentLiveOld = new StudentLiveOld();
        ClassUtils.copyProperties(student, studentLiveOld);
        studentLiveOld.setCreateTime(DateUtils.getNowDate());
        studentLiveOld.setUpdateTime(DateUtils.getNowDate());
        studentLiveOldMapper.insert(studentLiveOld);

        StudentInfo add = MapstructUtils.convert(bo, StudentInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 修改学生档案信息
     */
    @SneakyThrows
    @Override
    public Boolean updateByBo(StudentInfoBo bo) {
        //查询修改前数据
        StudentInfoVo student = baseMapper.selectStudentInfoByStudentId(bo.getStudentId());
        StudentInfoOld studentInfoOld = new StudentInfoOld();
        ClassUtils.copyProperties(student, studentInfoOld);
        studentInfoOld.setCreateTime(DateUtils.getNowDate());
        studentInfoOld.setUpdateTime(bo.getCreateTime());
        studentInfoOldMapper.insert(studentInfoOld);
        bo.setId(student.getId());
        bo.setUpdateTime(DateUtils.getNowDate());
        StudentInfo update = MapstructUtils.convert(bo, StudentInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(StudentInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除学生档案信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<Map<String, Object>> statistics(StudentInfoBo bo) {
        if(StringUtils.isEmpty(bo.getClassId())){
            return R.fail("请选择班级");
        }
        int zs = 0;
        int nan = 0;
        int nv = 0;
        int js = 0;
        int ls = 0;
        int pk = 0;
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<StudentInfo> lqw = buildQueryWrapper(bo);
        List<StudentInfoVo> studentInfoList = baseMapper.selectStudentInfo(lqw);
        if(studentInfoList!=null && studentInfoList.size()>0){
            for (StudentInfoVo info : studentInfoList) {
                zs++;
                if(StringUtils.isNotEmpty(info.getSex()) && info.getSex().equals("1")){
                    nan++;
                }else{
                    nv++;
                }

                if(StringUtils.isNotEmpty(info.getIsNearsightedness()) && info.getIsNearsightedness().equals("1")){
                    js++;
                }
                if(StringUtils.isNotEmpty(info.getIsLset()) && info.getIsLset().equals("1")){
                    ls++;
                }
                if(StringUtils.isNotEmpty(info.getIsPoverty()) && info.getIsPoverty().equals("1")){
                    pk++;
                }
            }
        }
        map.put("zs",zs);
        map.put("nan",nan);
        map.put("nv",nv);
        map.put("js",js);
        map.put("ls",ls);
        map.put("pk",pk);

        return R.ok("成功",map);
    }
}
