package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.CourseStatusEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
import com.ym.mec.biz.dal.page.*;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping
@Api(tags = "数据导出服务")
@RestController
public class ExportController extends BaseController {

    @Autowired
    private StudentRegistrationService studentRegistrationService;
    @Autowired
    private StudentManageService studentManageService;
    @Autowired
    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
    @Autowired
    private CourseScheduleTeacherSalaryService courseScheduleTeacherSalaryService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;
    @Autowired
    private VipGroupDao vipGroupDao;
    @Autowired
    private MusicGroupDao musicGroupDao;
    @Autowired
    private VipGroupService vipGroupService;
    @Autowired
    private PracticeGroupService practiceGroupService;
    @Autowired
    private CourseScheduleService scheduleService;
    @Autowired
    private SporadicChargeInfoService sporadicChargeInfoService;
    @Autowired
    private PracticeGroupDao practiceGroupDao;
    @Autowired
    private CourseReviewService courseReviewService;
    @Autowired
    private TenantPaymentOrderService tenantPaymentOrderService;
    @Autowired
    private CourseScheduleDao courseScheduleDao;
    @Autowired
    private ExtracurricularExercisesReplyService extracurricularExercisesReplyService;
    @Autowired
    private StudentExtracurricularExercisesSituationService studentExtracurricularExercisesSituationService;

    @ApiOperation(value = "网管课购买列表")
    @PostMapping("export/studentBuyPractice")
    @PreAuthorize("@pcs.hasPermissions('export/studentBuyPractice')")
    public void studentBuyPractice(HttpServletResponse response, StudentBuyPracticeQueryInfo queryInfo) throws IOException {
        queryInfo.setRows(49999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<StudentBuyPracticeDto> rows = practiceGroupService.studentBuys(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"学员编号", "学员名称", "所属分部","课程老师","课程组老师", "购买网管课",
                    "免费课结束日期", "首次购买日期", "时间差"}, new String[]{
                    "studentId", "studentName", "organName","teacherName","courseGroupTeacherName" ,"buyPractice.msg",
                    "lastClassDate", "firstBuyTime", "intervalDay"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出对外订单列表")
    @PostMapping("export/tenantPaymentOrder")
    @PreAuthorize("@pcs.hasPermissions('export/tenantPaymentOrder')")
    public void tenantPaymentOrder(HttpServletResponse response, TenantPaymentOrderQueryInfo queryInfo) throws IOException {
        queryInfo.setRows(49999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        List<TenantPaymentOrder> paymentOrders = tenantPaymentOrderService.queryPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"交易流水号", "订单号", "订单日期", "交易类型", "应付金额", "实付金额", "用户姓名", "手机号码", "交易方式", "收款账户", "交易状态",
                    "备注", "交易方式"}, new String[]{"transNo", "orderNo", "createTime", "type.desc", "expectAmount", "actualAmount", "user.username",
                    "user.phone", "paymentChannel", "merNos", "status.msg", "memo", "paymentChannel.desc"}, paymentOrders);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出老师课酬")
    @PostMapping("export/teacherSalary")
    @PreAuthorize("@pcs.hasPermissions('export/teacherSalary')")
    public void teacherSalary(HttpServletResponse response, ExportTeacherSalaryQueryInfo queryInfo) throws IOException {
        queryInfo.setRows(99999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        queryInfo.setIsExport(true);
        List<ExportTeacherSalaryDto> rows = courseScheduleTeacherSalaryService.exportTeacherSalary(queryInfo);
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"课时编号", "老师编号", "老师姓名", "老师分部", "工作类别",
                    "课程分部", "课程组编号", "课程班名称", "乐团模式", "vip活动名称", "阶梯奖励名称", "线上课/线下课", "线上课单价", "线下课单价",
                    "课程类别", "课时时长", "实际上课时长", "上课日期",
                    "上课时间", "教师签到状态", "教师签退状态", "教师签到时间", "教师签退时间",
                    "主辅", "上课地点", "应到学员", "学员签到时间", "学员签退时间", "课时课酬", "阶梯奖励"}, new String[]{
                    "courseScheduleId", "teacherId", "teacherName", "teacherOrganName", "jobType",
                    "courseScheduleOrganName", "groupId", "groupName", "changeType", "vipActiveName", "activeName", "teachMode", "onlineClassesUnitPrice", "offlineClassesUnitPrice",
                    "courseScheduleType", "signCourseScheduleTime", "currentTime", "classDate", "courseScheduleStartTime", "signInStatus",
                    "signOutStatus", "signInTime", "signOutTime", "teacherRole", "address", "studentNum", "studentSignInTime", "studentSignOutTime", "price", "rewards"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "导出学员列表")
    @PostMapping("export/studentHasCourse")
    @PreAuthorize("@pcs.hasPermissions('export/studentHasCourse')")
    public void studentHasCourse(HttpServletResponse response, StudentManageQueryInfo queryInfo) throws IOException {
        queryInfo.setRows(99999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        queryInfo.setIsExport(true);
        List<StudentManageListDto> rows = studentManageService.findStudentsByOrganId(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "学员编号", "学员姓名", "性别", "家长姓名",
                    "家长联系电话", "是否激活", "是否有课", "是否预约网管课", "是否有网管课", "课程余额(元)",
                    "所在乐团", "乐团所属声部", "所在乐团状态", "所在vip课", "所在VIP状态", "服务标签", "运营标签"}, new String[]{
                    "organName", "userId", "username", "gender.description", "parentsName", "parentsPhone",
                    "isActive.msg", "hasCourse.msg", "isMake.msg", "hasPracticeCourse.msg", "courseBalance", "musicGroupName",
                    "subjectName", "musicGroupStatus", "vipGroupName", "vipGroupStatus", "serviceTag.msg", "operatingTag.msg"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "导出陪练课列表")
    @GetMapping("export/practiceGroupList")
    @PreAuthorize("@pcs.hasPermissions('export/practiceGroupList')")
    public void queryAll(HttpServletResponse response, PracticeGroupQueryInfo queryInfo) throws IOException {
        queryInfo.setIsExport(true);
        queryInfo.setRows(999999999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<PracticeGroupDto> rows = practiceGroupService.findPracticeGroups(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        if (rows != null && rows.size() > 0) {
            rows.forEach(e -> {
                e.setSubClassTimes(e.getTotalClassTimes() == null ? 0 : e.getTotalClassTimes() - (e.getCurrentClassTimes() == null ? 0 : e.getCurrentClassTimes()));
            });
        }
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "网管课编号", "课程名称", "指导老师", "教务老师", "班级人数", "先上课单价", "线下课单价",
                    "当前课次", "总课次", "剩余课次", "开课时间", "结束时间"}, new String[]{
                    "organName", "id", "name", "teacherName", "educationalTeacherName", "studentNum", "onlineClassesUnitPrice",
                    "offlineClassesUnitPrice", "currentClassTimes", "totalClassTimes", "subClassTimes", "coursesStartDate", "coursesExpireDate"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出VIP课管理")
    @GetMapping("export/vipGroupList")
    @PreAuthorize("@pcs.hasPermissions('export/vipGroupList')")
    public void queryAll(HttpServletResponse response, VipGroupQueryInfo queryInfo) throws IOException {
        queryInfo.setRows(999999999);
        queryInfo.setIsExport(true);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<VipGroup> rows = vipGroupService.findVipGroups(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        if (rows != null && rows.size() > 0) {
            rows.forEach(e -> {
                e.setSubClassTimes(e.getTotalClassTimes() == null ? 0 : e.getTotalClassTimes() - (e.getCurrentClassTimes() == null ? 0 : e.getCurrentClassTimes()));
            });
        }
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"VIP编号", "课程名称", "课程状态", "指导老师", "指导老师", "班级人数", "先上课单价", "线下课单价",
                    "活动方案", "当前课次", "总课次", "剩余课次", "月消耗", "开课时间", "结束时间", "申请时间", "学生姓名"}, new String[]{
                    "id", "name", "status.msg", "userName", "educationalTeacherName", "studentNum", "onlineClassesUnitPrice",
                    "offlineClassesUnitPrice", "vipGroupActivityName", "currentClassTimes", "totalClassTimes", "subClassTimes", "monthConsumeRate",
                    "courseStartDate", "coursesExpireDate", "registrationStartTime", "userInfo"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "终课表列表导出")
    @GetMapping("export/superFindCourseSchedules")
    @PreAuthorize("@pcs.hasPermissions('export/superFindCourseSchedules')")
    public void superFindCourseSchedules(EndCourseScheduleQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setRows(999999999);
        queryInfo.setIsExport(true);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (org.apache.commons.lang3.StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            } else if (org.apache.commons.lang3.StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<CourseScheduleEndDto> rows = scheduleService.endFindCourseSchedules(queryInfo).getRows();
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部名称", "课程编号", "开始时间", "结束时间",
                    "班级名称", "班级声部", "课程名称", "课程类型", "教学模式",
                    "教学点", "课程状态", "是否点名", "指导老师", "学员编号", "签到时间", "签退时间", "签到状态", "签退状态", "签到备注"}, new String[]{
                    "organName", "id", "startClassTime", "endClassTime", "classGroupName", "subjectName", "name",
                    "groupType.desc", "teachMode.msg", "schoolName", "status.msg", "isCallNames.msg", "teacherName", "studentId", "signInTime",
                    "signOutTime", "signInStatusEnum.msg", "signOutStatusEnum.msg", "remark"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "导出零星收费列表")
    @GetMapping("export/sporadicChargeInfo")
    @PreAuthorize("@pcs.hasPermissions('export/sporadicChargeInfo')")
    public void queryPage(SporadicChargeInfoQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setRows(999999999);
        queryInfo.setIsExport(true);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<SporadicChargeInfo> rows = sporadicChargeInfoService.queryDetailPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "收费类型", "标题", "金额", "时间", "学生姓名", "创建人"}, new String[]{
                    "organName", "chargeType.msg", "title", "amount", "updateTime", "userName", "operatorName"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "导出乐器采购清单")
    @PostMapping("order/musicalListExport")
    @PreAuthorize("@pcs.hasPermissions('order/musicalListExport')")
    public void musicalListExport(HttpServletResponse response, String musicGroupId) throws IOException {
        List<Goods> musicalList = studentPaymentOrderDetailService.getMusicalList(musicGroupId);
        if (musicalList == null) {
            throw new BizException("数据集为空");
        }
        if (musicalList.size() > 50000) {
            throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "乐团", "商品类型", "商品名称", "型号", "数量"}, new String[]{
                    "brief", "memo", "type.desc", "name", "specification", "sellCount"}, musicalList);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出学员采购清单明细")
    @PostMapping("order/musicalListDetailExport")
    @PreAuthorize("@pcs.hasPermissions('order/musicalListDetailExport')")
    public void musicalListDetailExport(HttpServletResponse response, String musicGroupId) throws IOException {
        List<musicalListDetailDto> musicalList = studentPaymentOrderDetailService.getMusicalListDetail(musicGroupId);
        if (musicalList.size() > 50000) {
            throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "乐团", "学员编号", "学员姓名", "购买商品", "采购方式", "乐器金额", "教辅金额", "课程金额", "订单总价"}, new String[]{
                    "organName", "musicGroupName", "userId", "username", "goodsNames", "kitGroupPurchaseTypeEnum.msg", "musicalAmount", "accessoriesAmount", "courseAmount", "orderAmount"}, musicalList);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "乐团【报名中、缴费中】 学生详情列表导出")
    @PostMapping(value = "studentRegistration/queryStudentApplyDetailExport")
    @PreAuthorize("@pcs.hasPermissions('studentRegistration/queryStudentApplyDetailExport')")
    public void queryStudentApplyDetailExport(StudentRegistrationQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setIsExport(true);
        List<StudentApplyDetailDto> studentApplyDetail = studentRegistrationService.queryStudentDetailPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"学生姓名", "家长姓名", "年级", "班级", "性别", "服从调剂", "报名专业", "实际专业", "联系电话", "学员缴费状态", "乐器购买方式"}, new String[]{
                    "studentName", "parentsName", "currentGrade", "currentClass", "gender.description", "isAllowAdjust.msg", "subjectName", "actualSubjectName", "parentsPhone", "paymentStatus.desc", "kitGroupPurchaseTypeEnum.msg"}, studentApplyDetail);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "分页导出教师薪酬列表")
    @RequestMapping("courseScheduleTeacherSalary/export")
    @PreAuthorize("@pcs.hasPermissions('courseScheduleTeacherSalary/export')")
    public void export(CourseScheduleTeacherSalaryQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setIsExport(true);
        List<TeacherSalaryDto> teacherSalaries = courseScheduleTeacherSalaryService.querySalaries(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"用户编号", "用户名", "手机号", "课程类型", "实际薪水", "补助", "结算时间", "教师角色"}, new String[]{
                    "userId", "username", "phone", "type.msg", "name", "actualSalary", "subsidy", "settlementTime", "teacherRole.msg"}, teacherSalaries);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "订单列表导出")
    @RequestMapping("export/orderList")
    @PreAuthorize("@pcs.hasPermissions('export/orderList')")
    public void orderList(StudentPaymentOrderQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getRoutingOrganId()) && queryInfo.getOrderType().equals("3")) {
                queryInfo.setRoutingOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            }
        }
        queryInfo.setRows(999999999);
        queryInfo.setIsExport(true);
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);
        List<StudentPaymentOrderExportDto> studentPaymentOrderExportDtos = studentPaymentOrderService.ExportQueryPage(params);
        if (studentPaymentOrderExportDtos.size() > 50000) {
            throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
        }
        OutputStream outputStream = response.getOutputStream();
        long i = 1;
        for (StudentPaymentOrderExportDto row : studentPaymentOrderExportDtos) {
            if (queryInfo.getOrderType().equals("1")) {
                BigDecimal comAmount = row.getComAmount() == null ? BigDecimal.ZERO : row.getComAmount();
                row.setActualAmount(comAmount);
            } else if (queryInfo.getOrderType().equals("2")) {
                BigDecimal perAmount = row.getPerAmount() == null ? BigDecimal.ZERO : row.getPerAmount();
                row.setActualAmount(perAmount);
            }
            if (row.getActualAmount() == null) {
                row.setActualAmount(BigDecimal.ZERO);
            }
            BigDecimal transferFee = (row.getActualAmount().multiply(new BigDecimal("0.28")).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP);
            row.setTransferFee(transferFee);
            BigDecimal musicalFee = BigDecimal.ZERO;
            BigDecimal teachingFee = BigDecimal.ZERO;
            BigDecimal courseFee = BigDecimal.ZERO;
            BigDecimal leaseFee = BigDecimal.ZERO;
            String goodsName = "";
            if (row.getOrderDetailList() != null) {
                for (StudentPaymentOrderDetail orderDetail : row.getOrderDetailList()) {
                    if (orderDetail.getType().equals(OrderDetailTypeEnum.MUSICAL)) {
                        if (orderDetail.getKitGroupPurchaseType() != null && orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.LEASE)) {
                            leaseFee = orderDetail.getPrice();
                        } else {
                            musicalFee = orderDetail.getPrice();
                        }
                    } else if (orderDetail.getType().equals(OrderDetailTypeEnum.COURSE)) {
                        courseFee = courseFee.add(orderDetail.getPrice());
                    } else if (orderDetail.getType().equals(OrderDetailTypeEnum.ACCESSORIES) || orderDetail.getType().equals(OrderDetailTypeEnum.TEACHING) || orderDetail.getType().equals(OrderDetailTypeEnum.OTHER)) {
                        teachingFee = teachingFee.add(orderDetail.getPrice());
                    }
                }
            }
            if (row.getGoodsList() != null) {
                goodsName = row.getGoodsList().stream().map(Goods::getName).collect(Collectors.joining("|"));
            }
            row.setCourseFee(courseFee);
            row.setMusicalFee(musicalFee);
            row.setTeachingFee(teachingFee);
            row.setLeaseFee(leaseFee);
            row.setMemo(goodsName);
            //专业
            if (row.getGroupType().equals(GroupType.MUSIC)) {
                StudentRegistration studentRegistration = studentRegistrationDao.findStudentByMusicGroupIdAndUserId(row.getMusicGroupId(), row.getUserId());
                if (studentRegistration != null) {
                    row.setSubjectName(studentRegistration.getSubjectName());
                    row.setSchoolName(studentRegistration.getSchoolName());
                    row.setCooperationOrganName(studentRegistration.getRemark());
                }
            } else if (row.getGroupType().equals(GroupType.VIP)) {
                row.setCourseFee(row.getActualAmount());
                VipGroup vipGroupInfo = vipGroupDao.findVipGroupInfo(Integer.parseInt(row.getMusicGroupId()), row.getClassGroupId());
                if (vipGroupInfo != null) {
                    row.setSchoolName(vipGroupInfo.getSchoolName());
                    row.setSubjectName(vipGroupInfo.getSubjectName());
                }

            } else if (row.getGroupType().equals(GroupType.SPORADIC)) {
                row.setSporadicAmount(row.getActualAmount());
                row.setMusicalFee(BigDecimal.ZERO);
                row.setTeachingFee(BigDecimal.ZERO);
                if (row.getChargeType() != null) {
                    if (row.getChargeType().equals(1)) {
                        row.setSporadicType("考级");
                    } else if (row.getChargeType().equals(2)) {
                        row.setSporadicType("声部更改");
                    } else if (row.getChargeType().equals(3)) {
                        row.setSporadicType("乐器更换");
                    } else if (row.getChargeType().equals(4)) {
                        row.setSporadicType("配件销售");
                    } else if (row.getChargeType().equals(5)) {
                        row.setSporadicType("维修费");
                    } else if (row.getChargeType().equals(6)) {
                        row.setSporadicType("福袋活动");
                    } else if (row.getChargeType().equals(7)) {
                        row.setSporadicType("上门费");
                    } else if (row.getChargeType().equals(9)) {
                        row.setSporadicType("账户充值");
                    }
                }
                School userSchool = musicGroupDao.findUserSchool(row.getUserId());
                if (userSchool != null) {
                    row.setSchoolName(userSchool.getName());
                }
            } else if (row.getGroupType().equals(GroupType.PRACTICE)) {
                row.setCourseFee(row.getActualAmount());
                School userSchool = musicGroupDao.findUserSchool(row.getUserId());
                if (userSchool != null) {
                    row.setSchoolName(userSchool.getName());
                }
                PracticeCourseDto practiceGroup = practiceGroupDao.findByGroupId(Integer.parseInt(row.getMusicGroupId()));
                if (practiceGroup != null) {
                    row.setSubjectName(practiceGroup.getSubjectName());
                }
            }
            String paymentChannel = "";
            if (row.getPaymentChannel() == null) {
            } else if (row.getPaymentChannel().equals("YQPAY")) {
                paymentChannel = "双乾";
            } else if (row.getPaymentChannel().equals("ADAPAY")) {
                paymentChannel = "汇付";
            } else if (row.getPaymentChannel().equals("BALANCE")) {
                paymentChannel = "余额";
            }
            row.setPaymentChannel(paymentChannel);
            row.setId(i);
            i++;
        }

        try {
            String[] header = {"序号", "学生姓名", "交易流水号", "订单编号", "收款渠道", "收款账户", "支付金额", "到账时间",
                    "关联乐团ID/VIP课ID", "课程形态", "课程费用", "减免费用", "押金", "乐器", "教辅费用", "零星收款费用", "零星收款类别", "手续费", "专业", "分部", "单位/学校", "合作机构", "备注"};
            String[] body = {"id", "user.username", "transNo", "orderNo", "paymentChannel", "merNos", "actualAmount", "payTime", "musicGroupId",
                    "groupType.desc", "courseFee", "remitFee", "leaseFee", "musicalFee", "teachingFee", "sporadicAmount", "sporadicType", "transferFee", "subjectName", "organName", "schoolName", "cooperationOrganName", "memo"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, studentPaymentOrderExportDtos);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "乐团管理--乐团详情-导出学员列表")
    @RequestMapping("export/musicGroupStudent")
    @PreAuthorize("@pcs.hasPermissions('export/musicGroupStudent')")
    public void queryMusicGroupStudent(MusicGroupStudentQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setIsExport(true);
        queryInfo.setRows(99999);
        PageInfo<MusicGroupStudentsDto> musicGroupStudentsDtoPageInfo = studentManageService.queryMusicGroupStudent(queryInfo);
        OutputStream outputStream = response.getOutputStream();
        try {
            for (MusicGroupStudentsDto row : musicGroupStudentsDtoPageInfo.getRows()) {
                if (row.getGender() != null) {
                    if (row.getGender().equals("1")) {
                        row.setGender("男");
                    } else {
                        row.setGender("女");
                    }
                }
                if (row.getPaymentStatus() != null) {
                    if (row.getPaymentStatus().equals("PAID_COMPLETED")) {
                        row.setPaymentStatus("完成缴费");
                    } else if (row.getPaymentStatus().equals("NON_PAYMENT")) {
                        row.setPaymentStatus("未缴费");
                    } else if (row.getPaymentStatus().equals("PROCESSING")) {
                        row.setPaymentStatus("缴费中");
                    }
                }
                if (row.getStudentStatus().equals("NORMAL")) {
                    row.setStudentStatus("在读");
                } else {
                    row.setStudentStatus("退团");
                }
                if (row.getIsActive()) {
                    row.setActiveName("是");
                } else {
                    row.setActiveName("否");
                }
                if (row.getIsNewStudent().equals(1)) {
                    row.setIsNewStudentStr("是");
                } else {
                    row.setIsNewStudentStr("否");
                }
                if (row.getNextPaymentDate() != null) {
                    row.setNextPaymentDateStr(DateUtil.format(row.getNextPaymentDate(), DateUtil.DEFAULT_PATTERN));
                }
            }
            String[] header = {"学员编号", "学员姓名", "性别", "联系电话", "年级", "班级", "专业", "学员状态", "新增学员", "缴费金额",
                    "下次缴费日期", "报名缴费", "是否激活"};
            String[] body = {"userId", "realName", "gender", "phone", "currentGrade", "currentClass", "subjectName", "studentStatus", "isNewStudentStr",
                    "courseFee", "nextPaymentDateStr", "paymentStatus", "activeName"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, musicGroupStudentsDtoPageInfo.getRows());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "评论列表导出")
    @RequestMapping("export/courseReviews")
    @PreAuthorize("@pcs.hasPermissions('export/courseReviews')")
    public void courseReviews(CourseReviewQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            queryInfo.setOrganId(employee.getOrganIdList());
        }
        queryInfo.setIsExport(1);
        queryInfo.setRows(99999);
        PageInfo<CourseReviewDto> practiceGroupReviews = courseReviewService.findPracticeGroupReviews(queryInfo);
        if (practiceGroupReviews.getTotal() <= 0) {
            response.setStatus(500);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            for (CourseReviewDto row : practiceGroupReviews.getRows()) {
                row.setClassDateStr(DateUtil.dateToString(row.getClassDate(), "yyyy-MM-dd"));
                if (row.getHandHomework() != null && row.getHandHomework() > 0) {
                    row.setHandHomeworkStr("是");
                } else {
                    row.setHandHomeworkStr("否");
                }
                if (row.getHasLiaison() != null && row.getHasLiaison().equals("1")) {
                    row.setHasLiaison("是");
                } else {
                    row.setHasLiaison("否");
                }
                if (row.getCreateTime() != null) {
                    row.setCreateTimeStr(DateUtil.dateToString(row.getCreateTime(), "yyyy-MM-dd"));
                }
                if (row.getPronunciation() != null) {
                    row.setPronunciationStr(row.getPronunciation() + "星");
                }
                if (row.getTempo() != null) {
                    row.setTempoStr(row.getTempo() + "星");
                }
                if (row.getMusicTheory() != null) {
                    row.setMusicTheoryStr(row.getMusicTheory() + "星");
                }
                if (row.getHomeWorkReplied() != null && row.getHomeWorkReplied().equals("1")) {
                    row.setHomeWorkReplied("已回复");
                } else if (row.getHandHomework() != null && row.getHandHomework() > 0) {
                    row.setHomeWorkReplied("未回复");
                } else {
                    row.setHomeWorkReplied(null);
                }
                if (row.getAttendanceId() != null) {
                    row.setAttendanceStr("是");
                } else {
                    row.setAttendanceStr("否");
                }
            }

            String[] header = {"分部", "上课日期", "学生编号", "课程编号", "学员是否到课", "课程班名称", "老师", "教材内容", "发音", "节奏", "乐理", "曲目", "评价备注", "回访日期（布置作业）", "完成app双向沟通", "学员评分", "是否提交作业", "是否回复作业", "教务老师", "教务评价"};
            String[] body = {"organName", "classDateStr", "studentId", "id", "attendanceStr", "courseName", "teacherName", "teachingMaterial", "pronunciationStr", "tempoStr", "musicTheoryStr", "song", "memo", "createTimeStr", "hasLiaison", "studentReview", "handHomeworkStr", "homeWorkReplied", "eduTeacherName", "courseReview"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, practiceGroupReviews.getRows());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "网管课管理导出")
    @RequestMapping("export/practiceGroup")
    @PreAuthorize("@pcs.hasPermissions('export/practiceGroup')")
    public void practiceGroup(HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        String organIds = null;
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            organIds = employee.getOrganIdList();
        }

        List<CourseGroupExportDto> practiceGroupExports = practiceGroupDao.getPracticeGroupExport(organIds);
        if (practiceGroupExports == null || practiceGroupExports.size() == 0) {
            response.setStatus(500);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream outputStream = response.getOutputStream();
        Set<Integer> studentIds = practiceGroupExports.stream().map(CourseGroupExportDto::getStudentId).collect(Collectors.toSet());
        List<CourseGroupExportDto> studentCourseInfos = courseScheduleDao.getStudentCourseInfo(studentIds, GroupType.PRACTICE);

        List<CourseGroupExportDto> totalClassTimes = courseScheduleDao.getStudentCourseScheduleNum(studentIds, GroupType.PRACTICE, null);
        List<CourseGroupExportDto> noStartClassTimes = courseScheduleDao.getStudentCourseScheduleNum(studentIds, GroupType.PRACTICE, CourseStatusEnum.NOT_START);
        for (CourseGroupExportDto practiceGroupExport : practiceGroupExports) {
            for (CourseGroupExportDto studentCourseInfo : studentCourseInfos) {
                if (studentCourseInfo.getStudentId().equals(practiceGroupExport.getStudentId())) {
                    practiceGroupExport.setTeacherIds(studentCourseInfo.getTeacherIds());
                    practiceGroupExport.setTeacherName(studentCourseInfo.getTeacherName());
                    practiceGroupExport.setClassEndDate(studentCourseInfo.getClassEndDate());
                    break;
                }
            }

            for (CourseGroupExportDto studentTotalClassTimes : totalClassTimes) {
                if (studentTotalClassTimes.getStudentId().equals(practiceGroupExport.getStudentId())) {
                    practiceGroupExport.setTotalClassTimes(studentTotalClassTimes.getTotalClassTimes());
                    break;
                }
            }
            for (CourseGroupExportDto noStartStudentClassTimes : noStartClassTimes) {
                if (noStartStudentClassTimes.getStudentId().equals(practiceGroupExport.getStudentId())) {
                    practiceGroupExport.setNoStartClassTimes(noStartStudentClassTimes.getTotalClassTimes());
                    break;
                }
            }
        }

        try {
            String[] header = {"分部", "学生编号", "学生姓名", "网管课老师id", "网管课老师", "有效期截止时间", "课程截止时间", "总课时", "剩余课时", "是否购买"};
            String[] body = {"organName", "studentId", "studentName", "teacherIds", "teacherName", "expireDate", "classEndDate", "totalClassTimes", "noStartClassTimes","buyPractice.msg"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, practiceGroupExports);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "vip管理导出")
    @RequestMapping("export/vipGroup")
    @PreAuthorize("@pcs.hasPermissions('export/vipGroup')")
    public void vipGroup(HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        String organIds = null;
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            organIds = employee.getOrganIdList();
        }

        List<CourseGroupExportDto> vipGroupExports = courseScheduleDao.getVipGroupExport(organIds);
        if (vipGroupExports == null || vipGroupExports.size() == 0) {
            response.setStatus(500);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream outputStream = response.getOutputStream();
        Set<Integer> studentIds = vipGroupExports.stream().map(CourseGroupExportDto::getStudentId).collect(Collectors.toSet());
        List<CourseGroupExportDto> studentCourseInfos = courseScheduleDao.getStudentCourseInfo(studentIds, GroupType.VIP);
        List<CourseGroupExportDto> totalClassTimes = courseScheduleDao.getStudentCourseScheduleNum(studentIds, GroupType.VIP, null);
        List<CourseGroupExportDto> noStartClassTimes = courseScheduleDao.getStudentCourseScheduleNum(studentIds, GroupType.VIP, CourseStatusEnum.NOT_START);
        for (CourseGroupExportDto vipGroupExport : vipGroupExports) {

            for (CourseGroupExportDto studentCourseInfo : studentCourseInfos) {
                if (studentCourseInfo.getStudentId().equals(vipGroupExport.getStudentId())) {
                    vipGroupExport.setTeacherIds(studentCourseInfo.getTeacherIds());
                    vipGroupExport.setTeacherName(studentCourseInfo.getTeacherName());
                    vipGroupExport.setClassStartDate(studentCourseInfo.getClassStartDate());
                    vipGroupExport.setClassEndDate(studentCourseInfo.getClassEndDate());
                    break;
                }
            }
            for (CourseGroupExportDto studentTotalClassTimes : totalClassTimes) {
                if (studentTotalClassTimes.getStudentId().equals(vipGroupExport.getStudentId())) {
                    vipGroupExport.setTotalClassTimes(studentTotalClassTimes.getTotalClassTimes());
                    break;
                }
            }
            for (CourseGroupExportDto noStartStudentClassTimes : noStartClassTimes) {
                if (noStartStudentClassTimes.getStudentId().equals(vipGroupExport.getStudentId())) {
                    vipGroupExport.setNoStartClassTimes(noStartStudentClassTimes.getTotalClassTimes());
                    break;
                }
            }
        }

        try {
            String[] header = {"分部", "学生编号", "学生姓名", "指导老师id", "指导老师", "课程开始时间", "课程截止时间", "总课时", "剩余课时"};
            String[] body = {"organName", "studentId", "studentName", "teacherIds", "teacherName", "classStartDate", "classEndDate", "totalClassTimes", "noStartClassTimes"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, vipGroupExports);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "学生课外训练记录导出")
    @GetMapping("export/extraExercisesReplys")
    @PreAuthorize("@pcs.hasPermissions('export/extraExercisesReplys')")
    public void extraExercisesReplys(ExtraExercilseReplyQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setRows(999999999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (org.apache.commons.lang3.StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            } else if (org.apache.commons.lang3.StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<ExtraExerciseStudentsDto> rows = extracurricularExercisesReplyService.findExtraExercises(queryInfo).getRows();
        if (CollectionUtils.isEmpty(rows)) {
            response.setStatus(500);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        for (ExtraExerciseStudentsDto row : rows) {
            row.setStatusStr(Objects.isNull(row.getStatus()) || row.getStatus() == 0 ? "否" : "是");
            row.setIsViewStr(Objects.isNull(row.getIsView()) || row.getIsView() == 0 ? "否" : "是");
            row.setIsRepliedStr(Objects.isNull(row.getIsReplied()) || row.getIsReplied() == 0 ? "否" : "是");
        }
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(
                    new String[]{"布置时间", "截至时间", "训练标题", "老师名字", "分部", "学生姓名", "提交作业", "是否回复", "是否查看"},
                    new String[]{"createTime", "expireDate", "title", "teacherName", "organName", "user.username", "statusStr", "isRepliedStr", "isViewStr"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "课外训练-教学导出")
    @GetMapping("export/exercisesSituations")
    @PreAuthorize("@pcs.hasPermissions('export/exercisesSituations')")
    public void exercisesSituations(StudentExercisesSituationQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setRows(999999999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (org.apache.commons.lang3.StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            } else if (org.apache.commons.lang3.StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<StudentExercisesSituationDto> rows = studentExtracurricularExercisesSituationService.findStudentExtracurricularExercisesSituations(queryInfo).getRows();
        if (CollectionUtils.isEmpty(rows)) {
            response.setStatus(500);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(
                    new String[]{"学员编号", "学员姓名", "所属分部", "指导老师", "预期安排", "实际安排", "提交次数", "评价次数", "及时评价次数"},
                    new String[]{"studentId", "studentName", "organName", "teacherName", "expectExercisesNum", "actualExercisesNum", "exercisesReplyNum", "exercisesMessageNum", "exercisesMessageTimelyNum"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "课外训练-教学导出")
    @GetMapping("export/isSettlementCourseSalarys")
    @PreAuthorize("@pcs.hasPermissions('export/isSettlementCourseSalarys')")
    public void isSettlementCourseSalarys(CourseSalaryQueryInfo4Web queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setRows(999999999);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (org.apache.commons.lang3.StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            } else if (org.apache.commons.lang3.StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new BizException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        List<TeacherCourseSalaryDetail4WebDto> rows = courseScheduleTeacherSalaryService.findIsSettlementCourseSalarys(queryInfo).getRows();
        if (CollectionUtils.isEmpty(rows)) {
            response.setStatus(500);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(
                    new String[]{"分部", "课程组类型", "课程编号", "时间", "课程名称", "老师编号", "老师姓名", "签到时间", "签退时间", "应发课酬",
                                 "课酬扣款", "结算课酬", "结算课酬", "状态", "备注"},
                    new String[]{"organName", "groupType", "courseScheduleId", "startClassTime", "courseName", "teacherId", "teacherName",
                                "signInTime", "signOutTime", "actualSalary", "reduceSalary", "finalSalary", "confirmStatus", "memo"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=lender-" + DateUtil.getDate(new Date()) + ".xls");
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
