package yangtz.cs.liu.campus.controller.message;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.core.utils.HolidayDateUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.domain.message.SchoolMessageParentsPushs;
import yangtz.cs.liu.campus.domain.message.SchoolMessagePush;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGradeMentor;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import yangtz.cs.liu.campus.service.message.ISchoolMessageParentsPushsDetailsService;
import yangtz.cs.liu.campus.service.message.ISchoolMessageParentsPushsService;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.vo.student.SchoolStudentParentVO;

import static yangtz.cs.liu.campus.constant.MessageConstant.NORMAL;

/**
 * 家长端消息推送Controller
 *
 * @author ruoyi
 * @date 2022-10-28
 */
@RestController
@RequestMapping("/messageParentsPushs")
public class SchoolMessageParentsPushsController extends BaseController
{
    @Autowired
    private ISchoolMessageParentsPushsService parentsPushsService;

    @Autowired
    private ISchoolGradeMentorService gradeMentorService;

    @Autowired
    private ISchoolGradeService gradeService;

    @Autowired
    private ISchoolClassService schoolClassService;

    @Autowired
    private ISchoolStudentParentService schoolStudentParentService;

    @Autowired
    private ISchoolMessageParentsPushsDetailsService detailsService;

    /**
     * 家长端消息列表
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolMessageParentsPushs messageParentsPushs) {
        startPage();
        List<SchoolMessageParentsPushs> list = parentsPushsService.queryList(messageParentsPushs);
        return getDataTable(list);
    }

    //查询本级部下发送的家长信息推送
    @GetMapping("/gradeList")
    public TableDataInfo gradeList(SchoolMessageParentsPushs messageParentsPushs) {
        List<SchoolGrade> gradeIds = gradeMentorService.selectGradeList(getUserId());
        if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
            //若管理员此时不是级部成员，则查出所有级部
            if(1L == getUserId()){
                LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
                lqw.orderByAsc(SchoolGrade::getGradeValue);
                gradeIds = gradeService.list(lqw);
                if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                    throw new ServiceException("暂无级部信息，查询不出级部下的任何信息");
                }
            }else{
                throw new ServiceException("您不在任何级部工作，无法查看级部下的任何信息");
            }
        }
        //获取级部id并排重
        List<Long> idList = gradeIds.stream().map(SchoolGrade::getId).distinct().collect(Collectors.toList());
        //获取班级信息
        List<SchoolClass> schoolClassList = schoolClassService.getClassList(idList,new SchoolClass());
        if(StringUtils.isNull(schoolClassList) || schoolClassList.size() == 0){
            return getDataTable(new ArrayList<>());
        }
        //获取班级id并排重
        List<Long> classIdList = schoolClassList.stream().map(SchoolClass::getId).distinct().collect(Collectors.toList());
        List<SchoolStudentParentVO> pList = schoolStudentParentService.selectTeacherParent(classIdList,new SchoolStudentParentVO());
        if(StringUtils.isNull(pList) || pList.size() == 0){
            return getDataTable(new ArrayList<>());
        }
        //获取所有家长信息
        List<SchoolStudentParent> schoolStudentParents = schoolStudentParentService.list();
        //获取家长的用户id
        List<Long> pIdList = new ArrayList<>();
        for(SchoolStudentParentVO vo : pList){
//            SchoolStudentParent p = schoolStudentParentService.getById(vo.getId());
            for (SchoolStudentParent schoolStudentParent : schoolStudentParents) {
                if (vo.getId().equals(schoolStudentParent.getId())){
                    pIdList.add(schoolStudentParent.getUserId());
                }
            }
//            pIdList.add(p.getUserId());
        }
        //获取几张信息推送ID
        List<Long> pushIds = parentsPushsService.queryDetailsList(pIdList);
        if(StringUtils.isNull(pushIds) || pushIds.size() == 0){
            return getDataTable(new ArrayList<>());
        }
        startPage();
        List<SchoolMessageParentsPushs> list = parentsPushsService.queryGradeList(pushIds,messageParentsPushs);
        return getDataTable(list);
    }

    /**
     * 新增
     * @return
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody @Validated SchoolMessageParentsPushs parentsPushs) {
        parentsPushs.setState(NORMAL);//将状态改为正常
        boolean flag = parentsPushsService.save(parentsPushs);
        if(flag){
            //获取当前学年
//            int schoolYear = HolidayDateUtil.getSchoolYear();
            // TODO 修改最新学年
            int schoolYear = gradeService.isNewSchoolYear();
            //获取当前级部(存在当前登录人在多个级部工作)
            //List<SchoolGrade> gradeIds = gradeMentorService.selectGrades(getUserId(),schoolYear);
            List<SchoolGrade> gradeIds = gradeMentorService.selectGradeList(getUserId());
            if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                //若管理员此时不是级部成员，则查出所有级部
                if(1L == getUserId()){
                    LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
                    lqw.orderByAsc(SchoolGrade::getGradeValue);
                    gradeIds = gradeService.list(lqw);
                    if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                        throw new ServiceException("暂无级部信息，查询不出级部下的任何信息");
                    }
                }else{
                    throw new ServiceException("您不在任何级部工作，无法查看级部下的任何信息");
                }
            }
            //获取级部id并排重
            List<Long> idList = gradeIds.stream().map(SchoolGrade::getId).distinct().collect(Collectors.toList());
            //获取级部下最新学年班级
            SchoolClass sc = new SchoolClass();
            sc.setSchoolYear(schoolYear);
            List<SchoolClass> schoolClassList = schoolClassService.getClassList(idList,sc);
            //级部下无班级
            if(StringUtils.isNull(schoolClassList) || schoolClassList.size() == 0){
                throw new ServiceException("抱歉，您所在级部，在当前学年没有任何班级信息，新增失败");
            }
            //获取班级id并排重
            List<Long> classIdList = schoolClassList.stream().map(SchoolClass::getId).distinct().collect(Collectors.toList());
            //获取登录人所在的各级部下的家长信息
            List<SchoolStudentParentVO> list = schoolStudentParentService.selectTeacherParent(classIdList,new SchoolStudentParentVO());
            //无家长信息
            if(StringUtils.isNull(list) || list.size() == 0){
                return AjaxResult.success();
            }
            //添加推送到的本级部下的家长
            detailsService.saveDetails(parentsPushs.getId(),list);
        }
        return toAjax(flag);
    }

    /**
     * 修改
     * @return
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated SchoolMessageParentsPushs parentsPushs) {
        if(StringUtils.isNull(parentsPushs.getId())){
            throw new ServiceException("id为空，修改失败");
        }
        return toAjax(parentsPushsService.updateById(parentsPushs));
    }

    /**
     * 修改状态
     */
    @PutMapping("/changeState/{id}")
    public AjaxResult changeState(@PathVariable("id") Long id, String state) {
        if (StringUtils.isBlank(state)) {
            return AjaxResult.error("修改状态失败");
        }
        LambdaUpdateWrapper<SchoolMessageParentsPushs> luw = new LambdaUpdateWrapper<>();
        luw.eq(SchoolMessageParentsPushs::getId, id).set(SchoolMessageParentsPushs::getState, state);
        return toAjax(parentsPushsService.update(luw));
    }


    /**
     * 查询详情
     * @param id
     * @return
     */
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(parentsPushsService.getById(id));
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@PathVariable("ids") List<Long> ids) {
        return toAjax(parentsPushsService.deletePushList(ids));
    }

    /**
     * 导出
     *
     * @param ids
     * @return
     */
    @PostMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") List<Long> ids) {
        LambdaQueryWrapper<SchoolMessageParentsPushs> lqw = new LambdaQueryWrapper<>();
        lqw.in(SchoolMessageParentsPushs::getId,ids).orderByDesc(SchoolMessageParentsPushs::getCreateTime);
        List<SchoolMessageParentsPushs> list = parentsPushsService.list(lqw);
        ExcelUtil<SchoolMessageParentsPushs> util = new ExcelUtil<>(SchoolMessageParentsPushs.class);
        util.exportExcel(response, list, "家长消息推送");
    }

    //导出全部
    @PostMapping("/exportAll")
    public void exportAll(HttpServletResponse response, SchoolMessageParentsPushs messageParentsPushs) {
        List<SchoolMessageParentsPushs> list = parentsPushsService.queryList(messageParentsPushs);
        ExcelUtil<SchoolMessageParentsPushs> util = new ExcelUtil<>(SchoolMessageParentsPushs.class);
        util.exportExcel(response, list, "家长消息推送");
    }

}
