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

import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.core.utils.HolidayDateUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.constant.DcwjType;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolDcwj.*;
import yangtz.cs.liu.campus.domain.schoolDuty.SchoolDuty;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.mapper.schoolDcwj.SchoolDcwjPushMapper;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassService;
import yangtz.cs.liu.campus.service.schoolDcwj.*;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.util.ExcelUtils;
import yangtz.cs.liu.campus.vo.schoolDcwj.*;

import static yangtz.cs.liu.campus.constant.DcwjType.*;

/**
 * 调查问卷Controller
 *
 * @author wengxiulin
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/dcwj")
public class SchoolDcwjController extends BaseController {
    @Autowired
    private ISchoolDcwjService schoolDcwjService;

    @Autowired
    private ISchoolDcwjNrService schoolDcwjNrService;

    @Autowired
    private ISchoolClassService schoolClassService;

    @Autowired
    private ISchoolStudentService schoolStudentService;

    @Autowired
    private ISchoolDcwjRyService schoolDcwjRyService;
    @Autowired
    private ISchoolDcwjAnService schoolDcwjAnService;
    @Autowired
    private ISchoolGradeMentorService gradeMentorService;

    @Autowired
    private ISchoolGradeService gradeService;

    @Autowired
    private ISchoolClassService classService;

    @Autowired
    private ISchoolDcwjPushService pushService;


    @Value("${server.port}")
    private String p;

    /**
     * 级部-问卷-查询调查问卷列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolDcwj schoolDcwj) {
        //获取当前登录人当前学年所在级部
        //获取当前学年
//        int schoolYear = HolidayDateUtil.getSchoolYear();
        //获取当前用户所在级部
       /* List<SchoolGrade> gradeIds = gradeMentorService.selectGrades(getUserId(), schoolYear);
        if (StringUtils.isNull(gradeIds) || gradeIds.size() == 0) {
            throw new ServiceException("当前" + 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());
        startPage();
        List<DawjVo> list = schoolDcwjService.queryList(idList, schoolDcwj);
        return getDataTable(list);
    }

    /**
     * 班主任-问卷查看列表
     */
    @GetMapping("/headerList")
    public TableDataInfo headerList(SchoolDcwj schoolDcwj) {
        //获取当前登录人当前学年所任班主任的班级ids
        //获取当前学年
//        int schoolYear = HolidayDateUtil.getSchoolYear();
        // TODO 修改最新学年
        int schoolYear = gradeService.isNewSchoolYear();
        LambdaQueryWrapper<SchoolClass> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolClass::getSchoolYear, schoolYear)
                .eq(SchoolClass::getTeacherId, getUserId())
        ;
        List<SchoolClass> classes = classService.list(lqw);
        if (StringUtils.isNull(classes) || classes.size() == 0) {
            return new TableDataInfo();
        }

        //获取级部id并排重
        List<Long> idList = classes.stream().map(SchoolClass::getGradeId).distinct().collect(Collectors.toList());
        startPage();
        //只能查看已发布的
        schoolDcwj.setDcwjZt(PUBLISHED);
        List<DawjVo> list = schoolDcwjService.queryList(idList, schoolDcwj);
        return getDataTable(list);
    }

    /**
     * 导出调查问卷列表
     */
    @Log(title = "调查问卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolDcwj schoolDcwj) {
        List<SchoolDcwj> list = schoolDcwjService.selectSchoolDcwjList(schoolDcwj);
        ExcelUtil<SchoolDcwj> util = new ExcelUtil<SchoolDcwj>(SchoolDcwj.class);
        util.exportExcel(response, list, "调查问卷数据");
    }

    /**
     * 获取调查问卷详细信息
     */
    @GetMapping(value = "/queryById/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolDcwjService.getById(id));
    }

    /**
     * 新增调查问卷
     */
    @Log(title = "调查问卷", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolDcwj schoolDcwj) {
        schoolDcwj.insert();
        //默认是保存
        schoolDcwj.setDcwjZt(DcwjType.UNPUBLISHED);
        return toAjax(schoolDcwjService.save(schoolDcwj));
    }

    /**
     * 修改调查问卷
     */
    @Log(title = "调查问卷", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolDcwj schoolDcwj) {
        if (StringUtils.isNull(schoolDcwj.getId())) {
            throw new ServiceException("id为空");
        }
        return toAjax(schoolDcwjService.updateSchoolDcwj(schoolDcwj));
    }

    /**
     * 删除调查问卷
     */
    @Log(title = "调查问卷", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        //删除子表数据
        LambdaQueryWrapper<SchoolDcwjNr> lqw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SchoolDcwjAn> lqwan = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SchoolDcwjRy> lqwry = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SchoolDcwjPush> lqwpu = new LambdaQueryWrapper<>();
        for (Long id : ids) {
            //问卷内容
            lqw.eq(SchoolDcwjNr::getDcwjId, id);
            schoolDcwjNrService.remove(lqw);
            //问卷结果

            lqwan.eq(SchoolDcwjAn::getDcwjId, id);
            schoolDcwjAnService.remove(lqwan);

            //问卷回答人
            lqwry.eq(SchoolDcwjRy::getDcwjId, id);
            schoolDcwjRyService.remove(lqwry);

            //问卷推送类型
            lqwpu.eq(SchoolDcwjPush::getDcwjId,id);
            pushService.remove(lqwpu);
        }
        return toAjax(schoolDcwjService.removeByIds(ids));
    }


    /**
     * 发布
     */
    @PutMapping("/published/{id}")
    public AjaxResult published(@PathVariable("id") Long id) {
        //查看是否有子数据，没有子数据不能发布
        LambdaQueryWrapper<SchoolDcwjNr> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolDcwjNr::getDcwjId, id);
        List<SchoolDcwjNr> list = schoolDcwjNrService.list(lqw);
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("该调查问卷暂无问卷，无法发布");
        }

        LambdaQueryWrapper<SchoolClass> luwClass = new LambdaQueryWrapper<>();
        //查出级部
        SchoolDcwj schoolDcwj = schoolDcwjService.getById(id);
        //查出学生所在的班级
        luwClass.eq(SchoolClass::getGradeId, schoolDcwj.getGradeId());
        List<SchoolClass> schoolClassList = schoolClassService.list(luwClass);

        //查出所有学生
        LambdaQueryWrapper<SchoolStudent> luwStudent = new LambdaQueryWrapper<>();
        List<SchoolStudent> schoolStudents = schoolStudentService.list(luwStudent);

        //接收人集合
        List<SchoolDcwjRy> ryList = new ArrayList<>();

        for (SchoolClass schoolClass : schoolClassList) {
            //查出班级所有下所有学生
//            LambdaQueryWrapper<SchoolStudent> luwStudent = new LambdaQueryWrapper<>();
//            luwStudent.eq(SchoolStudent::getClassId, schoolClass.getId());
//            List<SchoolStudent> schoolStudents = schoolStudentService.list(luwStudent);
            for (SchoolStudent schoolStudent : schoolStudents) {
                if (schoolStudent.getClassId().equals(schoolClass.getId())){
                    SchoolDcwjRy schoolDcwjRy = new SchoolDcwjRy();
                    schoolDcwjRy.insert();
                    schoolDcwjRy.setDcwjId(schoolDcwj.getId());
                    schoolDcwjRy.setStudentId(schoolStudent.getId());
                    schoolDcwjRy.setRyZdzt(DcwjType.FILLINON);
                    ryList.add(schoolDcwjRy);
                }
            }
//            //把学生存到调查问卷的接收人
//            for (SchoolStudent schoolStudent : schoolStudents) {
//                SchoolDcwjRy schoolDcwjRy = new SchoolDcwjRy();
//                schoolDcwjRy.insert();
//                schoolDcwjRy.setDcwjId(schoolDcwj.getId());
//                schoolDcwjRy.setStudentId(schoolStudent.getId());
//                schoolDcwjRy.setRyZdzt(DcwjType.FILLINON);
//                schoolDcwjRyService.save(schoolDcwjRy);
//            }
        }
        //批量新增接收人
        if (ryList.size() > 0){
            schoolDcwjRyService.batchInsertDcwjRyStudent(ryList);
        }
        //修改状态
        LambdaUpdateWrapper<SchoolDcwj> luw = new LambdaUpdateWrapper<>();
        luw.eq(SchoolDcwj::getId, id).set(SchoolDcwj::getDcwjZt, DcwjType.PUBLISHED);
        return toAjax(schoolDcwjService.update(luw));
    }

    /**
     * 撤回
     *
     * @param id
     * @return
     */
    @PutMapping("/withdraw/{id}")
    public AjaxResult withdraw(@PathVariable Long id) {
        //撤回的话，首先删除根据主键删an表，再删除ry表，最后修改主表状态
        LambdaQueryWrapper<SchoolDcwjAn> anLqw = new LambdaQueryWrapper<>();
        anLqw.eq(SchoolDcwjAn::getDcwjId,id);
        schoolDcwjAnService.remove(anLqw);

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


        LambdaUpdateWrapper<SchoolDcwj> luw = new LambdaUpdateWrapper<>();
        luw.eq(SchoolDcwj::getId, id).set(SchoolDcwj::getDcwjZt, DcwjType.UNPUBLISHED);
        return toAjax(schoolDcwjService.update(luw));
    }

    //班主任-问卷结果-明细数据
    @GetMapping("/list/{dcwjId}")
    public AjaxResult list(@PathVariable("dcwjId") Long dcwjId, SchoolDcwjAnVo vo) {
        AjaxResult ajax = AjaxResult.success();
        //获取标题(班级、学生姓名、填写状态、填写时间等是固定的，所以只获取后面的题目1。。。。等)
        List<SchoolDcwjNr> titles = schoolDcwjNrService.getNrBtByDcwjId(dcwjId);
        ViewTitlesVo titlesVo = schoolDcwjNrService.turnTitles(titles);
        ajax.put("titles", titlesVo);
        //获取班主任所在班级的学生
        //获取当前学年
        //获取学生id
        //List<Long> stuIds = students.stream().map(SchoolStudent::getId).distinct().collect(Collectors.toList());
        List<Long> stuIds = getStudentIds();
        if (StringUtils.isNull(stuIds) || stuIds.size() == 0) {
            ajax.put("data", null);
            return ajax;
        }
        //获取内容
        List<SchoolDcwjAnVo> list = schoolDcwjRyService.getAnStudentData(dcwjId, vo, stuIds);
        List<ViewDataVo> voList = schoolDcwjNrService.turnData(list);
        ajax.put("data", voList);
        return ajax;
    }

    /**
     * 班主任-问卷结果-统计
     * id为主表id
     * 只统计所带班级的
     */
    @GetMapping("/getCount/{dcwjId}")
    public AjaxResult getCount(@PathVariable("dcwjId") Long dcwjId) {
        //获取班主任所在班级的学生
        List<Long> stuIds = getStudentIds();
        if (StringUtils.isNull(stuIds) || stuIds.size() == 0) {
            return AjaxResult.success();
        }
        return AjaxResult.success(schoolDcwjRyService.getHeaderCount(dcwjId, stuIds));
    }

    /**
     * 班主任-问卷结果-明细数据-导出
     */
    @PostMapping("/export/{dcwjId}")
    public void exportHeader(HttpServletResponse response, @PathVariable("dcwjId") Long dcwjId, SchoolDcwjAnVo vo) throws UnknownHostException {
        //获取主表内容
        SchoolDcwj dcwj = schoolDcwjService.getById(dcwjId);
        //获取表头
        //获取标题(只获取后面的题目1。。。。等)
        List<SchoolDcwjNr> titleList = schoolDcwjNrService.getNrBtByDcwjId(dcwjId);
        //表头为空时的操作
        if (StringUtils.isNull(titleList) || titleList.size() == 0) {
            throw new ServiceException("该调查问卷内容为空，请检查");
        }
        //获取类型为图片的标题id
        List<Long> picIds = new ArrayList<>();
        //处理表头 前几列是固定
        List<Object> titles = new ArrayList<>();
        titles.add(XUHAO);
        titles.add(SNAME);
        titles.add(IDCARD);
        titles.add(GRADENAME);
        titles.add(CLASSNAME);
        for (SchoolDcwjNr nr : titleList) {
            titles.add(nr.getNrBt());
            //获取类型为图片上传的标题
            if ("3".equals(nr.getNrLx())) {
                picIds.add(nr.getId());
            }
        }
        List<Long> stuIds = getStudentIds();
        if (StringUtils.isNull(stuIds) || stuIds.size() == 0) {
            throw new ServiceException("所在班级查不到学生信息，不允许导出");
        }
        //获取内容
        List<DcwjRyExportVo> dataVoList = schoolDcwjRyService.getHeaderExportData(dcwjId, vo, stuIds);

        //内容为空时的操作
        if (StringUtils.isNull(dataVoList) || dataVoList.size() == 0) {
            throw new ServiceException("内容为空！！！");
        }

        //数据汇总
        List<List<Object>> sheetDataList = new ArrayList<>();
        sheetDataList.add(titles);

        for (DcwjRyExportVo exportVo : dataVoList) {
            List<Object> o = new ArrayList<>();
            //固定导出的
            o.add(exportVo.getXh());
            o.add(exportVo.getStudentName());
            o.add(exportVo.getIdCard());
            o.add(exportVo.getGradeName());
            o.add(exportVo.getClassName());

            //不固定的
            for (SchoolDcwjAn an : exportVo.getList()) {
                if(StringUtils.isNull(an.getNrId())){
                    o.add(" ");
                    continue;
                }
                if (picIds.contains(an.getNrId())) {
                    try {
                        o.add(new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + p + an.getUserAnswer()));
                    } catch (Exception e) {
                        throw new UnknownHostException("转换URL出错");
                    }

                } else {
                    o.add(an.getUserAnswer());
                }
            }

            //当用户没有填写记录时,上面for循环不执行，所以不固定的那些列就没有数据
            for(int i = 0 ;i < titleList.size();i++){
                o.add(" ");
            }

            List<Object> objects = new ArrayList<>();
            for (int a = 0; a < titles.size(); a++) {
                objects.add(o.get(a));
            }
            sheetDataList.add(objects);
        }
        ExcelUtils.export(response, dcwj.getDcwjName(), sheetDataList);
    }

    public List<Long> getStudentIds() {
        //获取班主任所在班级的学生
        //获取当前学年
//        int schoolYear = HolidayDateUtil.getSchoolYear();
        // TODO 修改最新学年
        int schoolYear = gradeService.isNewSchoolYear();
        LambdaQueryWrapper<SchoolClass> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolClass::getSchoolYear, schoolYear)
                .eq(SchoolClass::getTeacherId, getUserId())
        ;
        List<SchoolClass> classes = classService.list(lqw);
        if (StringUtils.isNull(classes) || classes.size() == 0) {
            return new ArrayList<>();
        }
        List<Long> idList = classes.stream().map(SchoolClass::getId).distinct().collect(Collectors.toList());
        //获取班级学生
        LambdaQueryWrapper<SchoolStudent> stuLqw = new LambdaQueryWrapper<>();
        stuLqw.in(SchoolStudent::getClassId, idList);
        List<SchoolStudent> students = schoolStudentService.list(stuLqw);
        if (StringUtils.isNull(students) || students.size() == 0) {
            return new ArrayList<>();
        }
        //获取学生id
        List<Long> stuIds = students.stream().map(SchoolStudent::getId).distinct().collect(Collectors.toList());
        return stuIds;
    }

    /**
     * 教务管理-问卷调查-列表查看
     * */
    @GetMapping("/senateList")
    public TableDataInfo senateList(SchoolDcwj schoolDcwj) {
        startPage();
        return getDataTable(schoolDcwjService.senateList(schoolDcwj));
    }

    /**
     * 教务管理-问卷调查-新增
     * */
    @PostMapping("/senateAdd")
    public AjaxResult senateAdd(@RequestBody DcwjSenateVo senateVo) {
        return toAjax(schoolDcwjService.senateAdd(senateVo));
    }

    /**
     * 教务管理-问卷调查-详细信息
     */
    @GetMapping(value = "/senateQueryInfo/{id}")
    public AjaxResult senateQueryInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolDcwjService.senateQueryInfo(id));
    }

    /**
     * 教务管理-问卷调查-修改
     */
    @PutMapping("/senateEdit")
    public AjaxResult senateEdit(@RequestBody DcwjSenateVo senateVo) {
        if (StringUtils.isNull(senateVo.getId())) {
            throw new ServiceException("id为空");
        }
        return toAjax(schoolDcwjService.senateEdit(senateVo));
    }

    /**
     * 教务管理-问卷调查-发布
     */
    @PutMapping("/senatePub/{id}")
    public AjaxResult senatePub(@PathVariable("id") Long id) {
        return toAjax(schoolDcwjService.senatePub(id));
    }

    /**
     * 教务管理-问卷调查-撤回
     */
    @PutMapping("/senateWithdraw/{id}")
    public AjaxResult senateWithdraw(@PathVariable("id") Long id) {
        return toAjax(schoolDcwjService.senateWithdraw(id));
    }

    /**
     * 教务管理-问卷结果-明细数据-列表
     */
    @GetMapping("/senateList/{dcwjId}")
    public AjaxResult senateListDetail(@PathVariable("dcwjId") Long dcwjId, SchoolDcwjAnVo vo) {
        AjaxResult ajax = AjaxResult.success();
        //获取标题(班级、姓名、填写状态、填写时间等是固定的，所以只获取后面的题目1。。。。等)
        List<SchoolDcwjNr> titles = schoolDcwjNrService.getNrBtByDcwjId(dcwjId);
        ViewTitlesVo titlesVo = schoolDcwjNrService.turnTitles(titles);
        ajax.put("titles", titlesVo);

        //获取内容
//        List<SchoolDcwjAnVo> list = schoolDcwjRyService.getSenateAnData(dcwjId, vo);

        //判断是推送给教师还是家长
        LambdaQueryWrapper<SchoolDcwjPush> pushLqw = new LambdaQueryWrapper<>();
        pushLqw.eq(SchoolDcwjPush::getDcwjId,dcwjId);
        List<SchoolDcwjPush> pushes = pushService.list(pushLqw);
        if(DcwjType.PUSHT.equals(pushes.get(0).getPubType())){
            //教师
            //获取固定列的值,,获取到的list的id为ry表的id
            startPage();
            List<SchoolDcwjAnVo> list = schoolDcwjRyService.getTeaAnData(dcwjId, vo);
            //获取问卷调查题目
            LambdaQueryWrapper<SchoolDcwjNr> nrlqw = new LambdaQueryWrapper<>();
            nrlqw.eq(SchoolDcwjNr::getDcwjId, dcwjId).orderByAsc(SchoolDcwjNr::getNrPx).orderByDesc(SchoolDcwjNr::getCreateTime);
            List<SchoolDcwjNr> nrs = schoolDcwjNrService.list(nrlqw);

            LambdaQueryWrapper<SchoolDcwjAn> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolDcwjAn::getDcwjId, dcwjId)
            ;
            //a里要么有1个值，要么没有值
            List<SchoolDcwjAn> a = schoolDcwjAnService.list(lqw);

            //教师调查问卷回答的内容
            for (SchoolDcwjAnVo anVo : list) {
                List<SchoolDcwjAn> ans = new ArrayList<>();
                //设置空对象，是为了，通俗的说就是站位，如果不占位的话，就目前来说，如果用户第一题没写，第二题写了，那么第2题的答案会显示在第1题的位置
                SchoolDcwjAn entity = new SchoolDcwjAn();

                //获取该学生从第一题到最后一题的答案，如果当前题没有答案，，附空值
                for(SchoolDcwjNr nr : nrs){
//                    LambdaQueryWrapper<SchoolDcwjAn> lqw = new LambdaQueryWrapper<>();
//                    lqw
//                            .eq(SchoolDcwjAn::getDcwjId, dcwjId)
//                            .eq(SchoolDcwjAn::getRyId, anVo.getId())
//                            .eq(SchoolDcwjAn::getNrId, nr.getId())
//                    ;
//                    //a里要么有1个值，要么没有值
//                    List<SchoolDcwjAn> a = anMapper.selectList(lqw);

                    for (SchoolDcwjAn schoolDcwjAn : a) {
                        if (schoolDcwjAn.getRyId().equals(anVo.getId()) && schoolDcwjAn.getNrId().equals(nr.getId())){
                            ans.add(schoolDcwjAn);
                        }else {
                            ans.add(entity);
                        }
                    }

//                    if(StringUtils.isNotNull(a) && a.size() > 0){
//                        ans.add(a.get(0));
//                    }else {
//                        ans.add(entity);
//                    }
                }
                anVo.setList(ans);
            }
            List<ViewDataVo> voList = schoolDcwjNrService.turnData(list);
            ajax.put("data", voList);
            ajax.put("total",getDataTable(list).getTotal());
            return ajax;
        }

        //推送类型为学生家长
        //获取固定列的值,,获取到的list的id为ry表的id
        startPage();
        List<SchoolDcwjAnVo> list = schoolDcwjRyService.getAnData1(dcwjId, vo);

        //获取问卷调查题目
        LambdaQueryWrapper<SchoolDcwjNr> nrlqw = new LambdaQueryWrapper<>();
        nrlqw.eq(SchoolDcwjNr::getDcwjId, dcwjId).orderByAsc(SchoolDcwjNr::getNrPx).orderByDesc(SchoolDcwjNr::getCreateTime);
        List<SchoolDcwjNr> nrs = schoolDcwjNrService.list(nrlqw);

        LambdaQueryWrapper<SchoolDcwjAn> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolDcwjAn::getDcwjId, dcwjId)
        ;
        //a里要么有1个值，要么没有值
        List<SchoolDcwjAn> a = schoolDcwjAnService.list(lqw);

        //学生家长调查问卷回答的内容
        for (SchoolDcwjAnVo anVo : list) {
            List<SchoolDcwjAn> ans = new ArrayList<>();
            //设置空对象，是为了，通俗的说就是站位，如果不占位的话，就目前来说，如果用户第一题没写，第二题写了，那么第2题的答案会显示在第1题的位置
            SchoolDcwjAn entity = new SchoolDcwjAn();

            //获取该学生从第一题到最后一题的答案，如果当前题没有答案，，附空值
            for(SchoolDcwjNr nr : nrs){

                for (SchoolDcwjAn schoolDcwjAn : a) {
                    if (schoolDcwjAn.getRyId().equals(anVo.getId()) && schoolDcwjAn.getNrId().equals(nr.getId())){
                        ans.add(schoolDcwjAn);
                    }else {
                        ans.add(entity);
                    }
                }
            }
            anVo.setList(ans);
        }

        List<ViewDataVo> voList = schoolDcwjNrService.turnData(list);
        ajax.put("data", voList);
        ajax.put("total",getDataTable(list).getTotal());
        return ajax;
    }

    /**
     * 教务-问卷结果-明细数据-导出
     */
    @PostMapping("/senateExport/{dcwjId}")
    public void senateExport(HttpServletResponse response, @PathVariable("dcwjId") Long dcwjId, SchoolDcwjAnVo vo) throws UnknownHostException {
        SchoolDcwj dcwj = schoolDcwjService.getById(dcwjId);
        //判断是推送给教师还是家长
        LambdaQueryWrapper<SchoolDcwjPush> pushLqw = new LambdaQueryWrapper<>();
        pushLqw.eq(SchoolDcwjPush::getDcwjId,dcwjId);
        List<SchoolDcwjPush> pushes = pushService.list(pushLqw);
        //flase表示推送类型为家长，true为教师
        boolean flag = false;
        if(PUSHT.equals(pushes.get(0).getPubType())){
            flag = true;
        }
        //获取表头
        //获取标题(只获取后面的题目1。。。。等)
        List<SchoolDcwjNr> titleList = schoolDcwjNrService.getNrBtByDcwjId(dcwjId);
        //表头为空时的操作
        if (StringUtils.isNull(titleList) || titleList.size() == 0) {
            throw new ServiceException("该调查问卷内容为空，请检查");
        }
        //获取类型为图片的标题id
        List<Long> picIds = new ArrayList<>();
        //推送类型为教师
        if(flag){
            //处理表头 前几列是固定
            List<Object> titles = new ArrayList<>();
            titles.add(XUHAO);
            titles.add(SNAME);
            for (SchoolDcwjNr nr : titleList) {
                titles.add(nr.getNrBt());
                //获取类型为图片上传的标题
                if ("3".equals(nr.getNrLx())) {
                    picIds.add(nr.getId());
                }
            }
            //获取内容,根据主表id，模糊查询，当答题为空时，为了防止导出出错，需要整理下数据
            List<DcwjRyExportVo> dataVoList = schoolDcwjRyService.getAnExportTeacherData(dcwjId, vo,titleList.size());

            //内容为空时的操作
            if (StringUtils.isNull(dataVoList) || dataVoList.size() == 0) {
                throw new ServiceException("内容为空！！！");
            }

            //数据汇总
            List<List<Object>> sheetDataList = new ArrayList<>();
            sheetDataList.add(titles);

            for (DcwjRyExportVo exportVo : dataVoList) {
                List<Object> o = new ArrayList<>();
                //固定导出的
                o.add(exportVo.getXh());
                o.add(exportVo.getStudentName());

                //不固定的
                for (SchoolDcwjAn an : exportVo.getList()) {
                    if(StringUtils.isNull(an.getNrId())){
                        o.add(" ");
                        continue;
                    }
                    if (picIds.contains(an.getNrId())) {
                        try {
                            o.add(new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + p + an.getUserAnswer()));
                        } catch (Exception e) {
                            throw new UnknownHostException("转换URL出错");
                        }
                    } else {
                        o.add(an.getUserAnswer());
                    }
                }

                //当用户没有填写记录时,上面for循环不执行，所以不固定的那些列就没有数据
                for(int i = 0 ;i < titleList.size();i++){
                    o.add(" ");
                }

                List<Object> objects = new ArrayList<>();
                for (int a = 0; a < titles.size(); a++) {
                    objects.add(o.get(a));
                }
                sheetDataList.add(objects);
            }
            ExcelUtils.export(response, dcwj.getDcwjName(), sheetDataList);

        }

        //处理表头 前几列是固定
        List<Object> titles = new ArrayList<>();
        titles.add(XUHAO);
        titles.add(SNAME);
        titles.add(IDCARD);
        titles.add(GRADENAME);
        titles.add(CLASSNAME);
        for (SchoolDcwjNr nr : titleList) {
            titles.add(nr.getNrBt());
            //获取类型为图片上传的标题
            if ("3".equals(nr.getNrLx())) {
                picIds.add(nr.getId());
            }
        }

        //获取内容,根据主表id，模糊查询，当答题为空时，为了防止导出出错，需要整理下数据
        List<DcwjRyExportVo> dataVoList = schoolDcwjRyService.getAnExportData(dcwjId, vo,titleList.size());

        //内容为空时的操作
        if (StringUtils.isNull(dataVoList) || dataVoList.size() == 0) {
            throw new ServiceException("内容为空！！！");
        }

        //数据汇总
        List<List<Object>> sheetDataList = new ArrayList<>();
        sheetDataList.add(titles);

        for (DcwjRyExportVo exportVo : dataVoList) {
            List<Object> o = new ArrayList<>();
            //固定导出的
            o.add(exportVo.getXh());
            o.add(exportVo.getStudentName());
            o.add(exportVo.getIdCard());
            o.add(exportVo.getGradeName());
            o.add(exportVo.getClassName());

            //不固定的
            for (SchoolDcwjAn an : exportVo.getList()) {
                if(StringUtils.isNull(an.getNrId())){
                    o.add(" ");
                    continue;
                }
                if (picIds.contains(an.getNrId())) {
                    try {
                        o.add(new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + p + an.getUserAnswer()));
                    } catch (Exception e) {
                        throw new UnknownHostException("转换URL出错");
                    }
                } else {
                    o.add(an.getUserAnswer());
                }
            }

            //当用户没有填写记录时,上面for循环不执行，所以不固定的那些列就没有数据
            for(int i = 0 ;i < titleList.size();i++){
                o.add(" ");
            }

            List<Object> objects = new ArrayList<>();
            for (int a = 0; a < titles.size(); a++) {
                objects.add(o.get(a));
            }
            sheetDataList.add(objects);
        }
        ExcelUtils.export(response, dcwj.getDcwjName(), sheetDataList);
    }


}
