package yangtz.cs.liu.campus.service.impl.schoolDcwj;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.constant.DcwjType;
import yangtz.cs.liu.campus.constant.EmployeeType;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolDcwj.*;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMapper;
import yangtz.cs.liu.campus.mapper.schoolDcwj.*;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMapper;
import yangtz.cs.liu.campus.mapper.student.SchoolStudentMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.service.schoolDcwj.ISchoolDcwjService;
import yangtz.cs.liu.campus.vo.schoolDcwj.DawjVo;
import yangtz.cs.liu.campus.vo.schoolDcwj.DcwjSenateVo;
import yangtz.cs.liu.wechat.vo.schoolDcwj.SchoolDcwjVo;
import yangtz.cs.liu.wechat.vo.schoolDcwj.Vo_SchoolDcwj;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static yangtz.cs.liu.campus.constant.DcwjType.PUSHP;
import static yangtz.cs.liu.campus.constant.DcwjType.PUSHT;

/**
 * 调查问卷Service业务层处理
 *
 * @author wengxiulin
 * @date 2023-02-27
 */
@Service
public class SchoolDcwjServiceImpl extends ServiceImpl<SchoolDcwjMapper, SchoolDcwj> implements ISchoolDcwjService {
    @Autowired
    private SchoolDcwjMapper schoolDcwjMapper;

    @Autowired
    private SchoolDcwjRyMapper schoolDcwjRyMapper;

    @Autowired
    private SchoolDcwjNrMapper schoolDcwjNrMapper;

    @Autowired
    private SchoolDcwjAnMapper schoolDcwjAnMapper;

    @Autowired
    private SchoolDcwjPushMapper pushMapper;

    @Autowired
    private SchoolGradeMapper gradeMapper;

    @Autowired
    private SchoolTeacherMapper teacherMapper;

    @Autowired
    private SchoolClassMapper classMapper;

    @Autowired
    private SchoolStudentMapper studentMapper;

    /**
     * 查询调查问卷列表
     *
     * @param schoolDcwj 调查问卷
     * @return 调查问卷
     */
    @Override
    public List<SchoolDcwj> selectSchoolDcwjList(SchoolDcwj schoolDcwj) {
        return schoolDcwjMapper.selectSchoolDcwjList(schoolDcwj);
    }

    //按级部过滤
    @Override
    public List<DawjVo> queryList(List<Long> idList, SchoolDcwj schoolDcwj) {
        List<DawjVo> list = schoolDcwjMapper.queryList(idList, schoolDcwj);
        //查询所在级部的调查问卷
       /* LambdaQueryWrapper<SchoolDcwj> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotNull(schoolDcwj.getDcwjName()),SchoolDcwj::getDcwjName,schoolDcwj.getDcwjName())
                .eq(isNotNull(schoolDcwj.getDcwjZt()),SchoolDcwj::getDcwjZt,schoolDcwj.getDcwjZt())
                .in(isNotNull(idList),SchoolDcwj::getGradeId,idList)
                .orderByDesc(SchoolDcwj::getCreateTime)
                ;
        List<SchoolDcwj> dcwjs = schoolDcwjMapper.selectList(lqw);*/

        //处理数据
        for (DawjVo ad : list) {
            /*DawjVo vo = new DawjVo();
            BeanUtils.copyProperties(ad,vo);*/
            //获取范围
            if (StringUtils.isNotNull(ad.getGradeId())) {
                SchoolGrade grade = gradeMapper.selectById(ad.getGradeId());
                //为了防止脏数据的影响
                if (StringUtils.isNotNull(grade)) {
                    ad.setScope(grade.getGradeName() + grade.getSchoolYear() + "学年学生");
                }
            }
            //list.add(vo);
        }
        return list;
    }

    /**
     * 修改调查问卷
     *
     * @param schoolDcwj 调查问卷
     * @return 结果
     */
    @Override
    public int updateSchoolDcwj(SchoolDcwj schoolDcwj) {
        schoolDcwj.setUpdateTime(DateUtils.getNowDate());
        return schoolDcwjMapper.updateSchoolDcwj(schoolDcwj);
    }

    /**
     * 批量删除调查问卷
     *
     * @param ids 需要删除的调查问卷主键
     * @return 结果
     */
    @Override
    public int deleteSchoolDcwjByIds(Long[] ids) {
        return schoolDcwjMapper.deleteSchoolDcwjByIds(ids);
    }

    /**
     * 删除调查问卷信息
     *
     * @param id 调查问卷主键
     * @return 结果
     */
    @Override
    public int deleteSchoolDcwjById(Long id) {
        return schoolDcwjMapper.deleteSchoolDcwjById(id);
    }


    /**
     * wx获取调查问卷列表 ==>家长
     */
    @Override
    public List<Vo_SchoolDcwj> getDcwjList(Long studentId, String state) {
        List<Vo_SchoolDcwj> dcwjList = schoolDcwjMapper.getDcwjList(studentId, state);
        return dcwjList;
    }

    /**
     * wx获取调查问卷列表 ==>教职工
     */
    @Override
    public List<Vo_SchoolDcwj> teacherGetDcwjList(Long teacherId, String state) {
        List<Vo_SchoolDcwj> dcwjList = schoolDcwjMapper.teacherGetDcwjList(teacherId, state);
        return dcwjList;
    }

    /**
     * 教务管理-问卷调查-列表查看
     */
    @Override
    public List<DcwjSenateVo> senateList(SchoolDcwj schoolDcwj) {
        List<DcwjSenateVo> list = schoolDcwjMapper.senateList(schoolDcwj);
        for (DcwjSenateVo vo : list) {
            String scope = "";
            LambdaQueryWrapper<SchoolDcwjPush> pushLqw = new LambdaQueryWrapper<>();
            pushLqw.eq(SchoolDcwjPush::getDcwjId, vo.getId()).orderByDesc(SchoolDcwjPush::getCreateTime);
            List<SchoolDcwjPush> pushes = pushMapper.selectList(pushLqw);
            for (SchoolDcwjPush push : pushes) {
                //推送类型为教师
                if (PUSHT.equals(push.getPubType())) {
                    scope = "全体教师";
                    vo.setPubType(PUSHT);
                    break;
                } else {
                    //推送类型为家长
                    vo.setPubType(PUSHP);
                    //获取范围
                    if (StringUtils.isNotNull(push.getGradeId())) {
                        SchoolGrade grade = gradeMapper.selectById(push.getGradeId());
                        //为了防止脏数据的影响
                        if (StringUtils.isNotNull(grade)) {
                            scope += grade.getGradeName() + grade.getSchoolYear() + "学年学生;";
                        }
                    }
                }
            }
            vo.setScope(scope);
        }
        return list;
    }

    /**
     * 教务管理-问卷调查-新增
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int senateAdd(DcwjSenateVo senateVo) {
        //先插主表内容
        SchoolDcwj dcwj = new SchoolDcwj();
        BeanUtils.copyProperties(senateVo, dcwj);
        dcwj.setDcwjZt(DcwjType.UNPUBLISHED);
        dcwj.insert();
        int num = schoolDcwjMapper.insert(dcwj);
        //插子表
        if (num > 0) {
            //推送类型为教师
            if (PUSHT.equals(senateVo.getPubType())) {
                SchoolDcwjPush push = new SchoolDcwjPush();
                push.setDcwjId(dcwj.getId());
                push.setPubType(senateVo.getPubType());
                push.insert();
                pushMapper.insert(push);
            } else {
                //推送类型为家长
                List<Long> gradeIds = senateVo.getGradeIds();
                if (StringUtils.isNull(gradeIds) || gradeIds.size() == 0) {
                    throw new ServiceException("您还没有选择要推送给哪些级部的家长");
                }
                for (Long gradeId : gradeIds) {
                    SchoolDcwjPush push = new SchoolDcwjPush();
                    push.setDcwjId(dcwj.getId());
                    push.setPubType(senateVo.getPubType());
                    push.setGradeId(gradeId);
                    push.insert();
                    pushMapper.insert(push);
                }
            }
        }
        return num;
    }

    /**
     * 教务管理-问卷调查-详细信息
     */
    @Override
    public DcwjSenateVo senateQueryInfo(Long id) {
        DcwjSenateVo vo = new DcwjSenateVo();
        SchoolDcwj dcwj = schoolDcwjMapper.selectById(id);
        BeanUtils.copyProperties(dcwj, vo);
        //子表内容
        LambdaQueryWrapper<SchoolDcwjPush> pushLqw = new LambdaQueryWrapper<>();
        pushLqw.eq(SchoolDcwjPush::getDcwjId, id);
        List<SchoolDcwjPush> pushes = pushMapper.selectList(pushLqw);
        /*if(StringUtils.isNull(pushes) || pushes.size() == 0){

        }*/
        List<Long> gradeIds = new ArrayList<>();
        for (SchoolDcwjPush p : pushes) {
            if (PUSHT.equals(p.getPubType())) {
                //推送为老师，，只会存在一条数据
                vo.setPubType(p.getPubType());
                break;
            } else {
                gradeIds.add(p.getGradeId());
            }
        }
        //推送为家长
        if (StringUtils.isNotNull(gradeIds) && gradeIds.size() > 0) {
            vo.setPubType(DcwjType.PUSHP);
            vo.setGradeIds(gradeIds);
            List<SchoolGrade> gradeList = gradeMapper.selectBatchIds(gradeIds);
            vo.setGradeName(gradeList.stream().map(SchoolGrade::getGradeName).collect(Collectors.joining(",")));
        }
        return vo;
    }

    /**
     * 教务管理-问卷调查-修改
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int senateEdit(DcwjSenateVo senateVo) {
        //先修主表内容
        SchoolDcwj dcwj = new SchoolDcwj();
        BeanUtils.copyProperties(senateVo, dcwj);
        dcwj.update();
        int num = schoolDcwjMapper.updateById(dcwj);
        //更子表
        if (num > 0) {
            //先删除子表
            LambdaQueryWrapper<SchoolDcwjPush> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SchoolDcwjPush::getDcwjId, senateVo.getId());
            pushMapper.delete(lqw);
            //推送类型为教师
            if (PUSHT.equals(senateVo.getPubType())) {
                SchoolDcwjPush push = new SchoolDcwjPush();
                push.setDcwjId(dcwj.getId());
                push.setPubType(senateVo.getPubType());
                push.insert();
                pushMapper.insert(push);
            } else {
                //推送类型为家长
                List<Long> gradeIds = senateVo.getGradeIds();
                if (StringUtils.isNull(gradeIds) || gradeIds.size() == 0) {
                    throw new ServiceException("您还没有选择要推送给哪些级部的家长");
                }
                for (Long gradeId : gradeIds) {
                    SchoolDcwjPush push = new SchoolDcwjPush();
                    push.setDcwjId(dcwj.getId());
                    push.setPubType(senateVo.getPubType());
                    push.setGradeId(gradeId);
                    push.insert();
                    pushMapper.insert(push);
                }
            }
        }
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int senatePub(Long id) {
        //查看是否有子数据，没有子数据不能发布
        LambdaQueryWrapper<SchoolDcwjNr> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolDcwjNr::getDcwjId, id);
        List<SchoolDcwjNr> list = schoolDcwjNrMapper.selectList(lqw);
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("该调查问卷暂无问卷内容，无法发布");
        }

        //查询出是推送给家长还是教师
        LambdaQueryWrapper<SchoolDcwjPush> pushLqw = new LambdaQueryWrapper<>();
        pushLqw.eq(SchoolDcwjPush::getDcwjId, id);
        List<SchoolDcwjPush> pushes = pushMapper.selectList(pushLqw);
        for (SchoolDcwjPush push : pushes) {
            if (PUSHT.equals(push.getPubType())) {
                //推送给全体教工类型的教师
                SchoolTeacher t = new SchoolTeacher();
                //设置用户类型为教工
                t.setEmployeeType(EmployeeType.TEACH);
                List<SchoolTeacher> teacherList = teacherMapper.getAllTeachers(t);
                if (StringUtils.isNull(teacherList) || teacherList.size() == 0){
                    throw new ServiceException("系统中暂无教职工类型为教工的教师，无法发布");
                }
                //把教工存到调查问卷的接收人
                for (SchoolTeacher teacher : teacherList){
                    SchoolDcwjRy schoolDcwjRy = new SchoolDcwjRy();
                    schoolDcwjRy.insert();
                    schoolDcwjRy.setDcwjId(id);
                    schoolDcwjRy.setTeacherId(teacher.getId());
                    schoolDcwjRy.setRyZdzt(DcwjType.FILLINON);
                    schoolDcwjRyMapper.insert(schoolDcwjRy);
                }
                break;
            }else {
                //推送给级部家长
                LambdaQueryWrapper<SchoolClass> lqwClass = new LambdaQueryWrapper<>();
                //查出学生所在的班级
                lqwClass.eq(SchoolClass::getGradeId, push.getGradeId());
                List<SchoolClass> schoolClassList = classMapper.selectList(lqwClass);
                for (SchoolClass schoolClass : schoolClassList) {
                    //查出班级所有下所有学生
                    LambdaQueryWrapper<SchoolStudent> lqwStudent = new LambdaQueryWrapper<>();
                    lqwStudent.eq(SchoolStudent::getClassId, schoolClass.getId());
                    List<SchoolStudent> schoolStudents = studentMapper.selectList(lqwStudent);
                    //把学生存到调查问卷的接收人
                    for (SchoolStudent schoolStudent : schoolStudents) {
                        SchoolDcwjRy schoolDcwjRy = new SchoolDcwjRy();
                        schoolDcwjRy.insert();
                        schoolDcwjRy.setDcwjId(id);
                        schoolDcwjRy.setStudentId(schoolStudent.getId());
                        schoolDcwjRy.setRyZdzt(DcwjType.FILLINON);
                        schoolDcwjRyMapper.insert(schoolDcwjRy);
                    }
                }
            }
        }

        //修改状态
        SchoolDcwj dcwj = schoolDcwjMapper.selectById(id);
        dcwj.setDcwjZt(DcwjType.PUBLISHED);
        dcwj.update();
        return schoolDcwjMapper.updateById(dcwj);
    }

    //教务-撤回
    @Override
    public int senateWithdraw(Long id) {
        //撤回的话，首先删除根据主键删an表，再删除ry表，最后修改主表状态
        LambdaQueryWrapper<SchoolDcwjAn> anLqw = new LambdaQueryWrapper<>();
        anLqw.eq(SchoolDcwjAn::getDcwjId,id);
        schoolDcwjAnMapper.delete(anLqw);

        LambdaQueryWrapper<SchoolDcwjRy> ryLqw = new LambdaQueryWrapper<>();
        ryLqw.eq(SchoolDcwjRy::getDcwjId,id);
        schoolDcwjRyMapper.delete(ryLqw);

        //修改状态
        SchoolDcwj dcwj = schoolDcwjMapper.selectById(id);
        dcwj.setDcwjZt(DcwjType.UNPUBLISHED);
        dcwj.update();
        return schoolDcwjMapper.updateById(dcwj);
    }


}
