package com.zhongzheng.modules.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.course.domain.MajorCategory;
import com.zhongzheng.modules.user.bo.UserEditBo;
import com.zhongzheng.modules.user.bo.UserSchoolInfoAddBo;
import com.zhongzheng.modules.user.bo.UserSchoolInfoEditBo;
import com.zhongzheng.modules.user.bo.UserSchoolInfoQueryBo;
import com.zhongzheng.modules.user.domain.User;
import com.zhongzheng.modules.user.domain.UserSchoolInfo;
import com.zhongzheng.modules.user.mapper.UserSchoolInfoMapper;
import com.zhongzheng.modules.user.service.IUserSchoolInfoService;
import com.zhongzheng.modules.user.service.IUserService;
import com.zhongzheng.modules.user.vo.UserSchoolInfoVo;
import com.zhongzheng.modules.user.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户学校信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-06-24
 */
@Service
public class UserSchoolInfoServiceImpl extends ServiceImpl<UserSchoolInfoMapper, UserSchoolInfo> implements IUserSchoolInfoService {



    @Autowired
    private IUserService userService;





    @Override
    public UserSchoolInfoVo queryById(Long userSchoolId){
        UserSchoolInfo db = this.baseMapper.selectById(userSchoolId);
        return BeanUtil.toBean(db, UserSchoolInfoVo.class);
    }

    @Override
    public UserSchoolInfoVo queryByUserId(Long userId) {
        UserSchoolInfo info = getOne(new LambdaQueryWrapper<UserSchoolInfo>()
                .eq(UserSchoolInfo::getUserId,userId)
                .last("limit 1"));
        return BeanUtil.toBean(info, UserSchoolInfoVo.class);
    }

    @Override
    public List<UserSchoolInfoVo> queryList(UserSchoolInfoQueryBo bo) {
        LambdaQueryWrapper<UserSchoolInfo> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getSchoolName()), UserSchoolInfo::getSchoolName, bo.getSchoolName());
        lqw.eq(StrUtil.isNotBlank(bo.getFullTimeSchool()), UserSchoolInfo::getFullTimeSchool, bo.getFullTimeSchool());
        lqw.eq(StrUtil.isNotBlank(bo.getAdmissionTime()), UserSchoolInfo::getAdmissionTime, bo.getAdmissionTime());
        lqw.eq(StrUtil.isNotBlank(bo.getGraduationTime()), UserSchoolInfo::getGraduationTime, bo.getGraduationTime());
        lqw.eq(StrUtil.isNotBlank(bo.getEducation()), UserSchoolInfo::getEducation, bo.getEducation());
        lqw.eq(StrUtil.isNotBlank(bo.getAcademicDegree()), UserSchoolInfo::getAcademicDegree, bo.getAcademicDegree());
        lqw.eq(StrUtil.isNotBlank(bo.getEducationalSystem()), UserSchoolInfo::getEducationalSystem, bo.getEducationalSystem());
        lqw.eq(StrUtil.isNotBlank(bo.getDepartment()), UserSchoolInfo::getDepartment, bo.getDepartment());
        lqw.eq(StrUtil.isNotBlank(bo.getMajor()), UserSchoolInfo::getMajor, bo.getMajor());
        lqw.eq(StrUtil.isNotBlank(bo.getGrade()), UserSchoolInfo::getGrade, bo.getGrade());
        lqw.eq(StrUtil.isNotBlank(bo.getStudentStatusImg()), UserSchoolInfo::getStudentStatusImg, bo.getStudentStatusImg());
        lqw.eq(bo.getStatus() != null, UserSchoolInfo::getStatus, bo.getStatus());
        return entity2Vo(this.list(lqw));
    }



    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<UserSchoolInfoVo> entity2Vo(Collection<UserSchoolInfo> collection) {
        List<UserSchoolInfoVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, UserSchoolInfoVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<UserSchoolInfo> page = (Page<UserSchoolInfo>)collection;
            Page<UserSchoolInfoVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(UserSchoolInfoAddBo bo) {
        UserSchoolInfo add = BeanUtil.toBean(bo, UserSchoolInfo.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        return this.save(add);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(UserSchoolInfoEditBo bo,Boolean isAdmin) throws IllegalAccessException {
        UserSchoolInfo update = BeanUtil.toBean(bo, UserSchoolInfo.class);
        validEntityBeforeSave(update);

        if(!isAdmin){
            //后台操作不增加积分
            //增加学习的积分


        }

        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }



    private Boolean increaseUser(UserVo userVo,Long score){
        User user = BeanUtil.toBean(userVo, User.class);
        user.setIntegral(score);
        user.setUpdateTime(DateUtils.getNowTime());
        return userService.updateById(user);
    }


    public Integer  countUser(UserSchoolInfoEditBo userVo) throws IllegalAccessException {
        // Java的反射
        Field[] field = userVo.getClass().getDeclaredFields();
        int count = 0;
        for(int i=0; i<field.length; i++){
            Field f = field[i];
            f.setAccessible(true);
            if (f.get(userVo) != null){
                count++;
            }
        }
        return count;
    }
    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(UserSchoolInfo entity){
        //TODO 做一些数据校验,如唯一约束

    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
