package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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 com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.enums.AccountType;
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.MusicGroupStatusEnum;
import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
import com.ym.mec.biz.dal.enums.OrderTypeEnum;
import com.ym.mec.biz.dal.enums.PaymentChannelEnum;
import com.ym.mec.biz.dal.enums.SporadicChargeTypeEnum;
import com.ym.mec.biz.dal.enums.StudentMusicGroupStatusEnum;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.page.CooperationOrganQueryInfo;
import com.ym.mec.biz.dal.page.CourseReviewQueryInfo;
import com.ym.mec.biz.dal.page.CourseSalaryQueryInfo4Web;
import com.ym.mec.biz.dal.page.CourseScheduleTeacherSalaryQueryInfo;
import com.ym.mec.biz.dal.page.DegreeQueryInfo;
import com.ym.mec.biz.dal.page.EndCourseScheduleQueryInfo;
import com.ym.mec.biz.dal.page.ExportStudentAttendanceQueryInfo;
import com.ym.mec.biz.dal.page.ExportTeacherSalaryQueryInfo;
import com.ym.mec.biz.dal.page.ExtraExercilseReplyQueryInfo;
import com.ym.mec.biz.dal.page.MusicCalenderDetailQueryInfo;
import com.ym.mec.biz.dal.page.MusicGroupPaymentCalenderQueryInfo;
import com.ym.mec.biz.dal.page.MusicGroupStudentQueryInfo;
import com.ym.mec.biz.dal.page.PracticeGroupQueryInfo;
import com.ym.mec.biz.dal.page.SellOrderQueryInfo;
import com.ym.mec.biz.dal.page.SporadicChargeInfoQueryInfo;
import com.ym.mec.biz.dal.page.StudentBuyPracticeQueryInfo;
import com.ym.mec.biz.dal.page.StudentExercisesSituationQueryInfo;
import com.ym.mec.biz.dal.page.StudentManageQueryInfo;
import com.ym.mec.biz.dal.page.StudentOperatingQueryInfo;
import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
import com.ym.mec.biz.dal.page.StudentRegistrationQueryInfo;
import com.ym.mec.biz.dal.page.TeacherCloseQueryInfo;
import com.ym.mec.biz.dal.page.TeacherCourseRewardQueryInfo;
import com.ym.mec.biz.dal.page.TeacherSalaryModifyQueryInfo;
import com.ym.mec.biz.dal.page.TenantPaymentOrderQueryInfo;
import com.ym.mec.biz.dal.page.VipGroupQueryInfo;
import com.ym.mec.biz.service.CooperationOrganService;
import com.ym.mec.biz.service.CourseReviewService;
import com.ym.mec.biz.service.CourseScheduleService;
import com.ym.mec.biz.service.CourseScheduleTeacherSalaryService;
import com.ym.mec.biz.service.DegreeRegistrationService;
import com.ym.mec.biz.service.ExtracurricularExercisesReplyService;
import com.ym.mec.biz.service.MusicGroupPaymentCalenderDetailService;
import com.ym.mec.biz.service.MusicGroupPaymentCalenderService;
import com.ym.mec.biz.service.PracticeGroupService;
import com.ym.mec.biz.service.SellOrderService;
import com.ym.mec.biz.service.SporadicChargeInfoService;
import com.ym.mec.biz.service.StudentAttendanceService;
import com.ym.mec.biz.service.StudentExtracurricularExercisesSituationService;
import com.ym.mec.biz.service.StudentManageService;
import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
import com.ym.mec.biz.service.StudentPaymentOrderService;
import com.ym.mec.biz.service.StudentRegistrationService;
import com.ym.mec.biz.service.TeacherAttendanceService;
import com.ym.mec.biz.service.TeacherCourseRewardService;
import com.ym.mec.biz.service.TeacherSalaryComplaintsService;
import com.ym.mec.biz.service.TeacherService;
import com.ym.mec.biz.service.TenantPaymentOrderService;
import com.ym.mec.biz.service.VipGroupService;
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;

@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;
    @Autowired
    private TeacherSalaryComplaintsService teacherSalaryComplaintsService;
    @Autowired
    private TeacherAttendanceService teacherAttendanceService;
    @Autowired
    private StudentAttendanceService studentAttendanceService;
    @Autowired
    private TeacherCourseRewardService teacherCourseRewardService;
    @Autowired
    private DegreeRegistrationService degreeRegistrationService;
    @Autowired
    private CooperationOrganService cooperationOrganService;
    @Autowired
    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private MusicGroupPaymentCalenderDetailService musicGroupPaymentCalenderDetailService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private MusicGroupBuildLogDao musicGroupBuildLogDao;
    @Autowired
    private MusicGroupPaymentCalenderService musicGroupPaymentCalenderService;
    @Autowired
    private SellOrderService sellOrderService;
    @Autowired
    private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
    @Autowired
    private SellOrderDao sellOrderDao;
    @Autowired
    private SysConfigDao sysConfigDao;

    @ApiOperation(value = "学员考勤记录导出")
    @PostMapping("export/exportStudentAttendances")
    @PreAuthorize("@pcs.hasPermissions('export/exportStudentAttendances')")
    public void exportStudentAttendances(HttpServletResponse response, ExportStudentAttendanceQueryInfo queryInfo) throws IOException {
        queryInfo.setPage(1);
        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<ExportStudentAttendanceDto> rows = studentAttendanceService.exportStudentAttendancesQueryPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部编号", "分部名称", "课程组类型", "课程组编号", "课程组名称", "学员姓名",
                    "学员编号", "课程编号", "课程名称", "上课日期", "上课开始时间", "上课结束时间",
                    "指导老师名称", "指导老师编号", "教务老师名称", "教务老师编号", "授课老师名称", "授课老师编号", "学员考勤状态"}, new String[]{
                    "organId", "organName", "groupType.desc", "groupId", "groupName", "username",
                    "userId", "courseScheduleId", "courseScheduleName", "classDate", "startClassTime", "endClassTime", "guideTeacherName", "guideTeacherId"
                    , "educationalTeacherName", "educationalTeacherId", "actualTeacherName", "actualTeacherId", "studentAttendanceStatus.msg"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=studentAttendance-" + 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/musicGroupPaymentCalenderDetail")
    @PreAuthorize("@pcs.hasPermissions('export/musicGroupPaymentCalenderDetail')")
    public void exportMusicGroupPaymentCalenderDetail(HttpServletResponse response, MusicCalenderDetailQueryInfo queryInfo) throws IOException {
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
        List<MusicGroupPaymentCalenderDetail> rows = musicGroupPaymentCalenderDetailService.queryPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"学员编号", "学员姓名", "学员声部", "学员状态", "手机号", "预计缴费金额",
                    "缴费开始日期", "缴费截止日期", "是否开启缴费", "缴费状态", "支付时间"}, new String[]{
                    "userId", "sysUser.username", "studentRegistration.subjectName", "studentRegistration.musicGroupStatus.msg", "sysUser.phone", "expectAmount",
                    "startPaymentDateMgpc", "deadlinePaymentDateMgpc", "openFlag.msg", "paymentStatus.desc", "payTime"}, 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/exportPaymentCalenderAuditList")
    @PreAuthorize("@pcs.hasPermissions('export/exportPaymentCalenderAuditList')")
    public void exportPaymentCalenderAuditList(HttpServletResponse response, MusicGroupPaymentCalenderQueryInfo queryInfo) throws IOException {
        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.setPage(1);
        queryInfo.setRows(49999);
        List<MusicGroupPaymentCalenderAuditDto> rows = musicGroupPaymentCalenderService.auditList(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部名称", "分部编号", "乐团编号", "乐团名称", "申请类型", "订单类型", "加课总时长（分钟）", "原现价（元）",
                    "申请价格（元）", "备注", "申请人", "状态", "申请时间"}, new String[]{
                    "organName", "organId", "musicGroupId", "musicGroupName", "paymentType.desc", "payUserType.desc",
                    "addCourseTotalTime", "courseCurrentPrice", "courseOriginalPrice", "memo", "operatorName", "auditStatus.desc", "createTime"}, 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/queryTeacherAttendances")
    @PreAuthorize("@pcs.hasPermissions('export/queryTeacherAttendances')")
    public void exportTeacherAttendances(HttpServletResponse response, TeacherCloseQueryInfo queryInfo) throws IOException {
        queryInfo.setPage(1);
        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 rows = teacherAttendanceService.queryTeacherAttendances(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "老师编号", "老师姓名", "课程编号", "课程名称", "上课日期",
                    "课程开始时间", "课程结束时间", "课程类型", "签到时间", "签到状态", "签退时间", "签退状态", "备注"}, new String[]{
                    "organName", "teacherId", "teacherName", "courseScheduleId", "courseScheduleName", "classDate",
                    "startClassTime", "endClassTime", "courseScheduleType.msg", "signInTime", "signInStatus.msg", "signOutTime", "signOutStatus.msg",
                    "remark"}, 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/teacherSalaryComplaints")
    @PreAuthorize("@pcs.hasPermissions('export/teacherSalaryComplaints')")
    public void exportTeacherSalaryComplaints(HttpServletResponse response, TeacherSalaryModifyQueryInfo queryInfo) throws IOException {
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
        List<TeacherSalaryComplaints> rows = teacherSalaryComplaintsService.queryPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "老师ID", "老师姓名", "课酬归属时间", "申述提交时间", "状态",
                    "申述处理者"}, new String[]{
                    "organName", "teacherId", "realName", "salarySettlementMonth", "createTime", "statusEnum.msg",
                    "operatorRealName"}, 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/studentBuyPractice")
    @PreAuthorize("@pcs.hasPermissions('export/studentBuyPractice')")
    public void studentBuyPractice(HttpServletResponse response, StudentBuyPracticeQueryInfo queryInfo) throws IOException {
        queryInfo.setPage(1);
        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.setPage(1);
        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.setPage(1);
        queryInfo.setRows(49999);
        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活动名称", "Vip课程类型", "阶梯奖励名称", "线上课/线下课", "线上课单价", "线下课单价",
                    "课程类别", "课时时长", "实际上课时长", "上课日期",
                    "上课时间", "教师签到状态", "教师签退状态", "教师签到时间", "教师签退时间", "考勤申诉处理状态", "处理意见",
                    "主辅", "上课地点", "应到学员", "学员签到时间", "学员签退时间", "课时课酬", "阶梯奖励", "扣款原因"}, new String[]{
                    "courseScheduleId", "teacherId", "teacherName", "teacherOrganName", "jobType",
                    "courseScheduleOrganName", "groupId", "groupName", "changeType", "vipActiveName", "vipCategoryName", "activeName", "teachMode", "onlineClassesUnitPrice", "offlineClassesUnitPrice",
                    "courseScheduleType", "signCourseScheduleTime", "currentTime", "classDate", "courseScheduleStartTime", "signInStatus",
                    "signOutStatus", "signInTime", "signOutTime", "complaintsStatus", "disposeContent", "teacherRole", "address", "studentNum",
                    "studentSignInTime", "studentSignOutTime", "price", "rewards", "deductionReason"}, 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/teacherCourseReward")
    @PreAuthorize("@pcs.hasPermissions('export/teacherCourseReward')")
    public void teacherCourseReward(HttpServletResponse response, TeacherCourseRewardQueryInfo queryInfo) throws IOException {
        queryInfo.setPage(1);
        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("非法请求");
                }
            }
        }
        Date endTime = queryInfo.getEndTime();
        if (endTime != null) {
            queryInfo.setEndTime(DateUtil.addDays(endTime, 1));
        }
        List<TeacherCourseReward> rows = teacherCourseRewardService.queryPage(queryInfo).getRows();
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"课程组编号", "课程组名称", "分部", "指导老师", "是否结转", "结转金额", "结转日期", "备注"}, new String[]{
                    "musicGroupId", "courseGroupName", "organName", "teacherName", "settlementStatus.msg",
                    "expectRewardAmount", "settlementDate", "memo"}, 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.setPage(1);
        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("非法请求");
                }
            }
        }
        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", "hasPracticeCourse.msg", "courseBalance", "balance", "musicGroupName",
                    "subjectName", "musicGroupStatus", "vipGroupName", "vipGroupStatus", "serviceTag.msg", "operatingTag.msg", "teacherName", "isSignedContract"}, 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.setPage(1);
        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<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()));
                if (e.getBuyMonths() == null || e.getBuyMonths() == 0) {
                    e.setPayStatus("免费");
                } else {
                    if (e.getBeRenewGroupId() == null || e.getBeRenewGroupId() == 0l) {
                        e.setPayStatus("首充");
                    } else {
                        e.setPayStatus("续费");
                    }
                }
            });
        }
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"课程组编号", "课程组名称", "课程组类型", "分部", "教务老师", "指导老师", "班级人数",
                    "当前课次", "总课次", "剩余课次", "开课时间", "结束时间", "课程组状态", "是否续费", "备注"}, new String[]{
                    "id", "name", "type.msg", "organName", "educationalTeacherName", "teacherName", "studentNum", "currentClassTimes",
                    "totalClassTimes", "subClassTimes", "coursesStartDate", "coursesExpireDate",
                    "groupStatus.desc", "payStatus", "memo"}, 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.setPage(1);
        queryInfo.setRows(49999);
        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) {
            for (VipGroup e : rows) {
                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", "courseUnitPrice",
                    "vipGroupActivityName", "currentClassTimes", "totalClassTimes", "subClassTimes", "monthConsumeRate", "lastOverTime",
                    "courseStartDate", "coursesExpireDate", "registrationStartTime", "userInfo", "vipGroupCategoryName", "stopReason"}, 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.setPage(1);
        queryInfo.setRows(49999);
        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();
        for (CourseScheduleEndDto row : rows) {
            row.setIsComplaints(StringUtils.equals(row.getIsComplaints(), "1") ? "有" : "无");
        }
        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", "teacherName", "studentId", "isCallNames.msg", "isComplaints"}, 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.setPage(1);
        queryInfo.setRows(49999);
        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();
        for (SporadicChargeInfo row : rows) {
            row.setOpenFlagStr(row.getOpenFlag().equals(0) ? "开启" : "关闭");
            row.setOrderType(row.getUserId() == null ? "公用" : "个人");
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"分部", "收费类型", "标题", "收费状态", "金额", "时间", "学生姓名", "订单类型", "创建人"}, new String[]{
                    "organName", "chargeType.msg", "title", "openFlagStr", "amount", "createTime", "userName", "orderType", "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", "subjectName", "musicalName", "kitGroupPurchaseTypeEnum.msg", "musicalAmount", "accessoriesName", "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.setPage(1);
        queryInfo.setRows(49999);
        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.setPage(1);
        queryInfo.setRows(49999);
        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()) && "3".equals(queryInfo.getOrderType())) {
                queryInfo.setRoutingOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            }
        }
        if (StringUtils.isNotBlank(queryInfo.getSearch())) {
            List<BasicUserDto> users = studentPaymentOrderDao.getUsers(queryInfo.getSearch());
            List<Integer> userIds = users.stream().map(BasicUserDto::getUserId).collect(Collectors.toList());
            if (userIds.size() <= 0) {
                userIds.add(0);
            }
            queryInfo.setUserIds(userIds);
        }
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
        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 (row.getActualAmount() == null) {
                row.setActualAmount(BigDecimal.ZERO);
            }
            if (row.getBalancePaymentAmount() == null) {
                row.setBalancePaymentAmount(BigDecimal.ZERO);
            }
            if (row.getMemo() == null) {
                row.setMemo("");
            }
            BigDecimal transferFee = BigDecimal.ZERO;
            if (row.getPaymentChannel() != null && row.getPaymentChannel().equals("ADAPAY")) {
                FeeFlagNumDto countFeeFlagNum = studentPaymentRouteOrderDao.getCountFeeFlagNum(row.getOrderNo());
                if (countFeeFlagNum.getTotalNum() > countFeeFlagNum.getYesNum()) {
                    transferFee = row.getActualAmount().multiply(new BigDecimal("0.28")).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                }
                if (countFeeFlagNum.getTotalNum().equals(countFeeFlagNum.getYesNum())) {
                    List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderDao.getRouteOrders(row.getOrderNo());
                    for (StudentPaymentRouteOrder routeOrder : routeOrders) {
                        transferFee = transferFee.add(routeOrder.getRouteAmount().multiply(new BigDecimal("0.28")).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
                    }
                }
            }
            row.setTransferFee(transferFee);

            String goodsName = "";
            if (row.getOrderDetailList() != null) {
                for (StudentPaymentOrderDetail orderDetail : row.getOrderDetailList()) {
                    switch (orderDetail.getType()) {
                        case COURSE:
                        case CLASSROOM:
                        case SINGLE:
                        case MIX:
                        case COMPREHENSIVE:
                        case ENLIGHTENMENT:
                        case TRAINING_SINGLE:
                        case TRAINING_MIX:
                        case MUSIC_NETWORK:
                        case HIGH:
                        case HIGH_ONLINE:
                        case HIGH_ONLINE_COURSE:
                            row.setMusicGroupCourseFee(row.getMusicGroupCourseFee().add(orderDetail.getPrice()));
                            break;
                        case MUSICAL:
                            if (orderDetail.getKitGroupPurchaseType() != null && orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.LEASE)) {
                                BigDecimal leaseFee = orderDetail.getPrice();
                                if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
                                    leaseFee = orderDetail.getPrice().multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
                                }
                                row.setLeaseFee(leaseFee);
                            } else {
                                row.setMusicalFee(orderDetail.getPrice());
                            }
                            break;
                        case ACCESSORIES:
                        case TEACHING:
                            row.setTeachingFee(row.getTeachingFee().add(orderDetail.getPrice()));
                            break;
                        case OTHER:
                            row.setOtherFee(row.getOtherFee().add(orderDetail.getPrice()));
                        default:
                            break;
                    }
                }
            }
            if (row.getGoodsList() != null) {
                goodsName = row.getGoodsList().stream().map(Goods::getName).collect(Collectors.joining("|"));
            }
            if (StringUtils.isNotBlank(goodsName)) {
                row.setMemo(goodsName);
            }
            //专业
            if (row.getGroupType().equals(GroupType.VIP)) {
                row.setVipCourseFee(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)) {
                //考级报名
                if (row.getType().equals(OrderTypeEnum.DEGREE_REGISTRATION)) {
                    String[] feeTypes = row.getMemo().split("；");
                    List<String> feeTypeList = Arrays.asList(feeTypes);
                    for (String feeTypeStr : feeTypeList) {
                        int index = feeTypeStr.lastIndexOf("：");
                        if (index < 0) {
                            continue;
                        }
                        BigDecimal typeFee = new BigDecimal(feeTypeStr.substring(index + 1));
                        if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
                            typeFee = typeFee.multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
                        }
                        if (feeTypeStr.contains("VIP")) {
                            row.setVipCourseFee(typeFee);
                        } else if (feeTypeStr.contains("网管课")) {
                            row.setPracticeCourseFee(typeFee);
                        } else if (feeTypeStr.contains("乐理课")) {
                            row.setTheoryCourseFee(typeFee);
                        }
                    }
                    row.setDegreeFee(row.getActualAmount().subtract(row.getVipCourseFee()).subtract(row.getPracticeCourseFee()).subtract(row.getTheoryCourseFee()));
                } else {
                    row.setOtherFee(row.getActualAmount());
                }
                if (row.getChargeType() != null) {
                    for (SporadicChargeTypeEnum chargeType : SporadicChargeTypeEnum.values()) {
                        if (!chargeType.getCode().equals(row.getChargeType())) continue;
                        row.setSporadicType(chargeType.getMsg());
                    }
                }
                School userSchool = musicGroupDao.findUserSchool(row.getUserId());
                if (userSchool != null) {
                    row.setSchoolName(userSchool.getName());
                }
            } else if (row.getGroupType().equals(GroupType.PRACTICE)) {
                row.setPracticeCourseFee(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());
                }
            } else {
                StudentPaymentOrderExportDto feeByType = sellOrderDao.getFeeByType(row.getId());
                row.setMusicalFee(feeByType.getMusicalFee());
                row.setTeachingFee(feeByType.getTeachingFee());
                row.setRepairFee(feeByType.getRepairFee());
                row.setOtherFee(feeByType.getOtherFee());
                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());
                    }
                    row.setMusicGroupCourseFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getRepairFee()).subtract(feeByType.getOtherFee()).subtract(row.getLeaseFee()));
                } else if (row.getType().equals(OrderTypeEnum.REPAIR)) {
                    row.setRepairFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getOtherFee()));
                } else if (row.getType().equals(OrderTypeEnum.OUTORDER)) {
                    row.setMusicGroupCourseFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getRepairFee()).subtract(feeByType.getOtherFee()));
                    row.setTransferFee(BigDecimal.ZERO);
                }
            }
            if (row.getMusicGroupId()!= null && row.getMusicGroupId().equals("null")) {
                row.setMusicGroupId("");
            }
            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 = {"序号", "学生姓名", "交易流水号", "订单编号", "收款渠道", "收款账户", "应付金额", "现金支付", "余额支付", "乐团课", "VIP课", "网管课", "乐理课", "考级", "维修费用", "押金", "乐器", "教辅费用", "其它", "手续费", "到账时间",
                    "关联乐团ID/VIP课ID", "课程形态", "零星收款类别", "专业", "分部", "教学点", "合作单位", "备注"};
            String[] body = {"id", "user.username", "transNo", "orderNo", "paymentChannel", "merNos", "expectAmount", "actualAmount", "balancePaymentAmount", "musicGroupCourseFee", "vipCourseFee", "practiceCourseFee", "theoryCourseFee", "degreeFee", "repairFee", "leaseFee", "musicalFee", "teachingFee", "otherFee", "transferFee", "payTime", "musicGroupId",
                    "groupType.desc", "sporadicType", "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.setPage(1);
        queryInfo.setRows(49999);
        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.desc", "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.setPage(1);
        queryInfo.setRows(49999);
        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("否");
                }
                if (new Integer(1).equals(row.getAssignHomework())) {
                    row.setAssignHomeworkStr("是");
                } else {
                    row.setAssignHomeworkStr("否");
                }
            }

            String[] header = {"分部", "上课日期", "学生编号", "课程编号", "学员是否到课", "课程班名称", "老师", "教材内容", "发音", "节奏", "乐理", "曲目", "评价备注", "回访日期（布置作业）", "完成app双向沟通", "学员评分", "是否布置作业", "是否提交作业", "是否回复作业", "教务老师", "教务评价"};
            String[] body = {"organName", "classDateStr", "studentId", "id", "attendanceStr", "courseName", "teacherName", "teachingMaterial", "pronunciationStr", "tempoStr", "musicTheoryStr", "song", "memo", "createTimeStr", "hasLiaison", "studentReview", "assignHomeworkStr", "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", "网管课老师", "教务老师id", "教务老师", "有效期截止时间", "课程截止时间", "总课时", "剩余课时", "是否购买"};
            String[] body = {"organName", "studentId", "studentName", "teacherIds", "teacherName", "eduTeacherIds", "eduTeacherName", "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<Map<Integer, Date>> studentLastCourseSchedule = courseScheduleStudentPaymentDao.findStudentLastCourseSchedule(new ArrayList<>(studentIds));
        Map<Integer, String> studentLastCourseMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(studentLastCourseSchedule)) {
            studentLastCourseMap = MapUtil.convertMybatisMap(studentLastCourseSchedule);
        }
        List<CourseGroupExportDto> studentCourseInfos = courseScheduleDao.getStudentVipCourseInfo(studentIds);
        List<CourseGroupExportDto> totalClassTimes = courseScheduleDao.getStudentCourseScheduleNum(studentIds, GroupType.VIP, null);
        List<CourseGroupExportDto> noStartClassTimes = courseScheduleDao.getStudentCourseScheduleNum(studentIds, GroupType.VIP, CourseStatusEnum.NOT_START);
        for (CourseGroupExportDto vipGroupExport : vipGroupExports) {

            String lastClassDateStr = studentLastCourseMap.get(vipGroupExport.getStudentId());
            if (StringUtils.isNotBlank(lastClassDateStr)) {
                vipGroupExport.setLastClassDate(DateUtil.stringToDate(lastClassDateStr));
            }

            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", "指导老师", "教务老师id", "教务老师", "课程开始时间", "课程截止时间", "上次课时间", "总课时", "剩余课时"};
            String[] body = {"organName", "studentId", "studentName", "teacherIds", "teacherName", "eduTeacherIds", "eduTeacherName", "classStartDate", "classEndDate", "lastClassDate", "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.setPage(1);
        queryInfo.setRows(49999);
        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 ? "否" : "是");
            row.setIsRepliedTimelyStr(Objects.isNull(row.getIsRepliedTimely()) || row.getIsRepliedTimely() == 0 ? "否" : "是");
            row.setExistVipCourseStr(Objects.isNull(row.getExistVipCourse()) || row.getExistVipCourse() == 0 ? "否" : "是");
        }
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(
                    new String[]{"布置时间", "截至时间", "训练标题", "老师名字", "分部", "学生姓名", "学生编号", "提交作业", "提交作业时间", "是否评价", "是否有vip", "及时评价"},
                    new String[]{"createTime", "expireDate", "title", "teacherName", "organName", "user.username", "userId", "statusStr", "submitTime", "isRepliedStr", "existVipCourseStr", "isRepliedTimelyStr"}, 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.setPage(1);
        queryInfo.setRows(49999);
        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[]{"学员编号", "学员姓名", "所属分部", "乐团名称", "指导老师", "教务老师", "预期安排", "实际安排", "提交次数", "评价次数", "及时评价次数", "付费网管课", "VIP课", "作业提交时间"},
                    new String[]{"studentId", "studentName", "organName", "groupNames", "teacherName", "educationalTeacherName", "expectExercisesNum", "actualExercisesNum", "exercisesReplyNum",
                            "exercisesMessageNum", "exercisesMessageTimelyNum", "existPracticeCourse", "existVipCourse", "lastSubmitTime"}, 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.setPage(1);
        queryInfo.setRows(49999);
        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;
        }
        for (TeacherCourseSalaryDetail4WebDto row : rows) {
            if (Objects.isNull(row.getSignInTime())) {
                row.setSignInStatusStr("未签到");
            } else {
                String signInTimeStr = DateUtil.dateToString(row.getSignInTime(), "yyyy-MM-dd HH:mm");
                if (YesOrNoEnum.YES.equals(row.getSignInStatus())) {
                    row.setSignInStatusStr(signInTimeStr + "(正常签到)");
                } else {
                    row.setSignInStatusStr(signInTimeStr + "(异常签到)");
                }
            }
            if (Objects.isNull(row.getSignOutTime())) {
                row.setSignOutStatusStr("未签退");
            } else {
                String signOutTimeStr = DateUtil.dateToString(row.getSignOutTime(), "yyyy-MM-dd HH:mm");
                if (YesOrNoEnum.YES.equals(row.getSignOutStatus())) {
                    row.setSignOutStatusStr(signOutTimeStr + "(正常签退)");
                } else {
                    row.setSignOutStatusStr(signOutTimeStr + "(异常签退)");
                }
            }
            if (row.getBelongDaya() == 1) {
                row.setSalaryType("基本课酬");
            } else {
                row.setSalaryType("其它课酬");
            }
        }
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(
                    new String[]{"分部", "课程组类型", "课程编号", "时间", "课程名称", "老师编号", "老师姓名", "签到时间", "签退时间",
                            "学员缴费", "课酬类型", "应发课酬", "课酬扣款", "结算课酬", "状态", "备注", "扣款原因"},
                    new String[]{"organName", "groupType.desc", "courseScheduleId", "startClassTime", "courseName", "teacherId", "teacherName",
                            "signInStatusStr", "signOutStatusStr", "actualReceipts", "salaryType", "actualSalary", "reduceSalary", "finalSalary",
                            "confirmStatus.desc", "memo", "deductionReason"}, 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/operatingStudents")
    @PreAuthorize("@pcs.hasPermissions('export/operatingStudents')")
    public void operatingStudents(StudentOperatingQueryInfo queryInfo, HttpServletResponse response) {
        queryInfo.setPage(1);
        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("非法请求");
                }
            }
        }
        PageInfo<Student4operating> PageOperatingStudents = studentManageService.getOperatingStudents(queryInfo);

        if (PageOperatingStudents.getTotal() <= 0) {
            throw new BizException("导出记录不存在");
        }
        List<Student4operating> rows = PageOperatingStudents.getRows();
        for (Student4operating row : rows) {
            if (row.getOperatingTag() != null && row.getOperatingTag() == 1) {
                row.setOperatingTagStr("是");
            } else {
                row.setOperatingTagStr("否");
            }
            if (row.getVipTimes() != null && row.getVipTimes() > 0) {
                row.setVipTimesStr("是");
            } else {
                row.setVipTimesStr("否");
            }
            if (row.getMusicNetWorkTimes() != null && row.getMusicNetWorkTimes() > 0) {
                row.setMusicNetWorkTimesStr("是");
            } else {
                row.setMusicNetWorkTimesStr("否");
            }
            if (row.getFreePracticeTimes() != null && row.getFreePracticeTimes() > 0) {
                row.setFreePracticeTimesStr("是");
            } else {
                row.setFreePracticeTimesStr("否");
            }
            if (row.getBuyPracticeTimes() != null && row.getBuyPracticeTimes() > 0) {
                row.setBuyPracticeTimesStr("是");
            } else {
                row.setBuyPracticeTimesStr("否");
            }
        }
        OutputStream ouputStream = null;
        try {

            HSSFWorkbook workbook = POIUtil.exportExcel(
                    new String[]{"分部", "乐团名称", "学生", "学生编号", "指导老师", "指导老师id", "参与运营指标", "有线上VIP课", "参与免费网管课", "有付费网管课", "有乐团网管课"},
                    new String[]{"organName", "groupNames", "studentName", "studentId", "teacherName", "teacherId", "operatingTagStr", "vipTimesStr", "freePracticeTimesStr", "buyPracticeTimesStr", "musicNetWorkTimes"}, 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 = "vip评论列表导出")
    @RequestMapping("export/vipCourseReviews")
    @PreAuthorize("@pcs.hasPermissions('export/vipCourseReviews')")
    public void vipCourseReviews(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.setPage(1);
        queryInfo.setRows(49999);
        PageInfo<CourseReviewDto> practiceGroupReviews = courseReviewService.getVipCourseReviews(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("否");
                }
                if (new Integer(1).equals(row.getAssignHomework())) {
                    row.setAssignHomeworkStr("是");
                } else {
                    row.setAssignHomeworkStr("否");
                }
            }

            String[] header = {"分部", "上课日期", "课程编号", "课程班名称", "老师", "教材内容", "发音", "节奏", "乐理", "曲目", "评价备注", "回访日期（布置作业）", "是否布置作业", "是否提交作业", "教务老师", "教务评价"};
            String[] body = {"organName", "classDateStr", "id", "courseName", "teacherName", "teachingMaterial", "pronunciationStr", "tempoStr", "musicTheoryStr", "song", "memo", "createTimeStr", "assignHomeworkStr", "handHomeworkStr", "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/degreeRegistration")
    @PreAuthorize("@pcs.hasPermissions('export/degreeRegistration')")
    public void degreeRegistration(DegreeQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        queryInfo.setSort("create_time_");
        queryInfo.setOrder("ASC");
        queryInfo.setRows(65000);
        PageInfoDegree<DegreeRegistration> pageList = degreeRegistrationService.getPageList(queryInfo);
        if (pageList.getTotal() <= 0) {
            response.setStatus(200);
            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 (DegreeRegistration row : pageList.getRows()) {
                if (row.getGender().equals("1")) {
                    row.setGender("男");
                } else {
                    row.setGender("女");
                }
                if (row.getStatus().equals(2)) {
                    row.setStatusStr("已缴费");
                } else {
                    row.setStatusStr("未缴费");
                }
            }

            String[] header = {"姓名", "性别", "身份证号", "城市", "学校", "报考乐器", "报考级别", "乐理级别", "乐理级别证书", "家长联系电话", "考级费用", "乐理费用", "备注", "缴费状态", "订单编号", "商户订单号", "报名时间"};
            String[] body = {"name", "gender", "idcard", "city", "school", "subject", "level", "theoryLevel", "theoryCert", "mobile", "money", "theoryMoney", "memo", "statusStr", "orderNo", "transNo", "createTime"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, pageList.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/cooperationOrgan")
    @PreAuthorize("@pcs.hasPermissions('export/cooperationOrgan')")
    public void cooperationOrgan(CooperationOrganQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new IOException("用户信息获取失败");
        }
        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 IOException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    throw new IOException("非法请求");
                }
            }
        }
        queryInfo.setRows(65000);
        PageInfo<CooperationOrgan> pageList = cooperationOrganService.queryPage(queryInfo);
        if (pageList.getTotal() <= 0) {
            response.setStatus(200);
            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 {

            String[] header = {"分部", "单位编号", "单位名称", "联系人", "职位", "手机号", "是否启用"};
            String[] body = {"organization.name", "id", "name", "linkman", "job", "mobileNo", "isEnable"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, pageList.getRows());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=cooperationOrgan-" + 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/musicGroupRegister")
    @PreAuthorize("@pcs.hasPermissions('export/musicGroupRegister')")
    public void musicGroupRegister(String organIds, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isBlank(organIds)) {
                organIds = employee.getOrganIdList();
            }
        }
        List<MusicGroupStatusEnum> musicGroupStatusList = new ArrayList<>();
        musicGroupStatusList.add(MusicGroupStatusEnum.APPLY);
        musicGroupStatusList.add(MusicGroupStatusEnum.PAY);

        List<MusicGroupRegisterDto> musicGroupRegisters = musicGroupDao.getMusicGroupRegister(musicGroupStatusList, organIds);

        if (musicGroupRegisters.size() <= 0) {
            response.setStatus(200);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        List<String> musicGroupIds = musicGroupRegisters.stream().map(MusicGroupRegisterDto::getMusicGroupId).collect(Collectors.toList());

        List<RegisterSubjectDto> registerSubjects = musicGroupDao.getRegisterSubjectNum(musicGroupIds, null, 2);
        List<MusicGroupRegisterDto> musicGroupRegisterOrders = musicGroupDao.getMusicGroupRegisterOrder(musicGroupIds);
        List<MusicGroupRegisterDto> musicGroupRegisterTotalMoneys = musicGroupDao.getMusicGroupRegisterTotalMoney(musicGroupIds);

        List<MusicGroupBuildLog> musicGroupAuditSuccess = musicGroupBuildLogDao.getMusicGroupAuditSuccess(musicGroupIds);

        HashSet<Integer> added = new HashSet<>();
        List<String> header = new ArrayList<>();
        header.add("分部");
        header.add("乐团名称");
        header.add("乐团状态");
        header.add("审核通过时间");
        header.add("报名总数");
        List<String> body = new ArrayList<>();
        body.add("organName");
        body.add("musicGroupName");
        body.add("musicGroupStatus");
        body.add("auditSuccessTime");
        body.add("registerNum");
        for (RegisterSubjectDto registerSubject : registerSubjects) {
            if (!added.contains(registerSubject.getSubjectId())) {
                added.add(registerSubject.getSubjectId());
                header.add(registerSubject.getSubjectName());
                body.add("subject" + registerSubject.getSubjectId());
            }
        }
        header.add("团购数");
        header.add("缴费总数");
        header.add("回款总金额");

        body.add("groupBuyMusicalNum");
        body.add("registerPayNum");
        body.add("totalMoney");


        List<Map<String, Object>> data = new ArrayList<>();
        for (MusicGroupRegisterDto musicGroupRegister : musicGroupRegisters) {
            added.clear();
            HashMap<String, Object> musicGroupRegisterMap = new HashMap<>();
            int registerPayNum = 0;
            musicGroupRegisterMap.put("organName", musicGroupRegister.getOrganName());
            musicGroupRegisterMap.put("musicGroupName", musicGroupRegister.getMusicGroupName());
            musicGroupRegisterMap.put("musicGroupStatus", musicGroupRegister.getMusicGroupStatus().getMsg());
            musicGroupRegisterMap.put("registerNum", musicGroupRegister.getRegisterNum());
            for (MusicGroupRegisterDto musicGroupRegisterOrder : musicGroupRegisterOrders) {
                if (musicGroupRegisterOrder.getMusicGroupId().equals(musicGroupRegister.getMusicGroupId())) {
                    musicGroupRegister.setGroupBuyMusicalNum(musicGroupRegisterOrder.getGroupBuyMusicalNum());
                }
            }
            for (MusicGroupRegisterDto musicGroupRegisterTotalMoney : musicGroupRegisterTotalMoneys) {
                if (musicGroupRegisterTotalMoney.getMusicGroupId().equals(musicGroupRegister.getMusicGroupId())) {
                    musicGroupRegister.setTotalMoney(musicGroupRegisterTotalMoney.getTotalMoney());
                }
            }

            for (RegisterSubjectDto registerSubject : registerSubjects) {
                if (registerSubject.getMusicGroupId().equals(musicGroupRegister.getMusicGroupId())) {
                    added.add(registerSubject.getSubjectId());
                    musicGroupRegisterMap.put("subject" + registerSubject.getSubjectId(), registerSubject.getNum());
                    registerPayNum += registerSubject.getNum();
                }
                if (!added.contains(registerSubject.getSubjectId())) {
                    musicGroupRegisterMap.put("subject" + registerSubject.getSubjectId(), 0);
                }
            }
            for (MusicGroupBuildLog groupAuditSuccess : musicGroupAuditSuccess) {
                if (!groupAuditSuccess.getMusicGroupId().equals(musicGroupRegister.getMusicGroupId())) continue;
                musicGroupRegisterMap.put("auditSuccessTime", groupAuditSuccess.getCreateTime());
            }
            musicGroupRegisterMap.put("groupBuyMusicalNum", musicGroupRegister.getGroupBuyMusicalNum());
            musicGroupRegisterMap.put("registerPayNum", registerPayNum);
            musicGroupRegisterMap.put("totalMoney", musicGroupRegister.getTotalMoney());
            data.add(musicGroupRegisterMap);
        }

        OutputStream outputStream = response.getOutputStream();
        try {
            String[] headerStr = header.toArray(new String[header.size()]);
            String[] bodyStr = body.toArray(new String[body.size()]);

            HSSFWorkbook workbook = POIUtil.exportExcel(headerStr, bodyStr, data);
            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/routeOrderList")
    @PreAuthorize("@pcs.hasPermissions('export/routeOrderList')")
    public void routeOrderList(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());
            }
        }
        if (StringUtils.isNotBlank(queryInfo.getSearch())) {
            List<BasicUserDto> users = studentPaymentOrderDao.getUsers(queryInfo.getSearch());
            List<Integer> userIds = users.stream().map(BasicUserDto::getUserId).collect(Collectors.toList());
            if (userIds.size() <= 0) {
                userIds.add(0);
            }
            queryInfo.setUserIds(userIds);
        }
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
        queryInfo.setIsExport(true);
        queryInfo.setOrderType("3");
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);
        List<StudentPaymentOrderExportDto> studentPaymentOrderExportDtos = studentPaymentRouteOrderDao.ExportQueryPage(params);
        if (studentPaymentOrderExportDtos.size() > 50000) {
            throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
        }
        OutputStream outputStream = response.getOutputStream();
        long i = 1;
        for (StudentPaymentOrderExportDto row : studentPaymentOrderExportDtos) {
            if (row.getActualAmount() == null) {
                row.setActualAmount(BigDecimal.ZERO);
            }
            if (row.getBalancePaymentAmount() == null) {
                row.setBalancePaymentAmount(BigDecimal.ZERO);
            }
            if (row.getRouteAmount() == null) {
                row.setRouteAmount(BigDecimal.ZERO);
            }
            if (row.getMemo() == null) {
                row.setMemo("");
            }
            BigDecimal transferFee = BigDecimal.ZERO;
            if (row.getPaymentChannel() != null && row.getPaymentChannel().equals("ADAPAY")) {
                FeeFlagNumDto countFeeFlagNum = studentPaymentRouteOrderDao.getCountFeeFlagNum(row.getOrderNo());
                if (countFeeFlagNum.getTotalNum() > countFeeFlagNum.getYesNum() && row.getFeeFlag().equals("Y")) {
                    transferFee = row.getActualAmount().multiply(new BigDecimal("0.28")).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                }
                if (countFeeFlagNum.getTotalNum().equals(countFeeFlagNum.getYesNum())) {
                    transferFee = row.getRouteAmount().multiply(new BigDecimal("0.28")).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                }
            }
            row.setTransferFee(transferFee);

            String goodsName = "";
            if (row.getOrderDetailList() != null) {
                for (StudentPaymentOrderDetail orderDetail : row.getOrderDetailList()) {
                    switch (orderDetail.getType()) {
                        case COURSE:
                        case CLASSROOM:
                        case SINGLE:
                        case MIX:
                        case COMPREHENSIVE:
                        case ENLIGHTENMENT:
                        case TRAINING_SINGLE:
                        case TRAINING_MIX:
                        case MUSIC_NETWORK:
                        case HIGH:
                        case HIGH_ONLINE:
                        case HIGH_ONLINE_COURSE:
                            row.setMusicGroupCourseFee(row.getMusicGroupCourseFee().add(orderDetail.getPrice()));
                            break;
                        case MUSICAL:
                            if (orderDetail.getKitGroupPurchaseType() != null && orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.LEASE)) {
                                BigDecimal leaseFee = orderDetail.getPrice();
                                if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
                                    leaseFee = orderDetail.getPrice().multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
                                }
                                row.setLeaseFee(leaseFee);
                            } else {
                                row.setMusicalFee(orderDetail.getPrice());
                            }
                            break;
                        case ACCESSORIES:
                        case TEACHING:
                            row.setTeachingFee(row.getTeachingFee().add(orderDetail.getPrice()));
                            break;
                        case OTHER:
                            row.setOtherFee(row.getOtherFee().add(orderDetail.getPrice()));
                        default:
                            break;
                    }
                }
            }
            if (row.getGoodsList() != null) {
                goodsName = row.getGoodsList().stream().map(Goods::getName).collect(Collectors.joining("|"));
            }
            if (StringUtils.isNotBlank(goodsName)) {
                row.setMemo(goodsName);
            }
            //专业
            if (row.getGroupType().equals(GroupType.VIP)) {
                row.setVipCourseFee(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)) {
                //考级报名
                if (row.getType().equals(OrderTypeEnum.DEGREE_REGISTRATION)) {
                    String[] feeTypes = row.getMemo().split("；");
                    List<String> feeTypeList = Arrays.asList(feeTypes);
                    for (String feeTypeStr : feeTypeList) {
                        int index = feeTypeStr.lastIndexOf("：");
                        if (index < 0) {
                            continue;
                        }
                        BigDecimal typeFee = new BigDecimal(feeTypeStr.substring(index + 1));
                        if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
                            typeFee = typeFee.multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
                        }
                        if (feeTypeStr.contains("VIP")) {
                            row.setVipCourseFee(typeFee);
                        } else if (feeTypeStr.contains("网管课")) {
                            row.setPracticeCourseFee(typeFee);
                        } else if (feeTypeStr.contains("乐理课")) {
                            row.setTheoryCourseFee(typeFee);
                        }
                    }
                    row.setDegreeFee(row.getActualAmount().subtract(row.getVipCourseFee()).subtract(row.getPracticeCourseFee()).subtract(row.getTheoryCourseFee()));
                } else {
                    row.setOtherFee(row.getActualAmount());
                }
                if (row.getChargeType() != null) {
                    for (SporadicChargeTypeEnum chargeType : SporadicChargeTypeEnum.values()) {
                        if (!chargeType.getCode().equals(row.getChargeType())) continue;
                        row.setSporadicType(chargeType.getMsg());
                    }
                }
                School userSchool = musicGroupDao.findUserSchool(row.getUserId());
                if (userSchool != null) {
                    row.setSchoolName(userSchool.getName());
                }
            } else if (row.getGroupType().equals(GroupType.PRACTICE)) {
                row.setPracticeCourseFee(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());
                }
            } else {
                StudentPaymentOrderExportDto feeByType = sellOrderDao.getFeeByType(row.getId());
                row.setMusicalFee(feeByType.getMusicalFee());
                row.setTeachingFee(feeByType.getTeachingFee());
                row.setRepairFee(feeByType.getRepairFee());
                row.setOtherFee(feeByType.getOtherFee());
                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());
                    }
                    row.setMusicGroupCourseFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getRepairFee()).subtract(feeByType.getOtherFee()).subtract(row.getLeaseFee()));
                } else if (row.getType().equals(OrderTypeEnum.REPAIR)) {
                    row.setRepairFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getOtherFee()));
                } else if (row.getType().equals(OrderTypeEnum.OUTORDER)) {
                    row.setMusicGroupCourseFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getRepairFee()).subtract(feeByType.getOtherFee()));
                    row.setTransferFee(BigDecimal.ZERO);
                }
            }
            if (row.getMusicGroupId()!= null && row.getMusicGroupId().equals("null")) {
                row.setMusicGroupId("");
            }
            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 = {"序号", "学生姓名", "交易流水号", "订单编号", "收款渠道", "收款账户", "应付金额", "现金支付", "余额支付", "分润账户", "分润金额", "分润余额", "乐团课", "VIP课", "网管课", "乐理课", "考级", "维修费用", "押金", "乐器", "教辅费用", "其它", "手续费", "到账时间",
                    "关联乐团ID/VIP课ID", "课程形态", "零星收款类别", "专业", "分部", "教学点", "合作单位", "备注"};
            String[] body = {"id", "user.username", "transNo", "orderNo", "paymentChannel", "merNos", "expectAmount", "actualAmount", "balancePaymentAmount", "routeMerNo", "routeAmount", "routeBalance", "musicGroupCourseFee", "vipCourseFee", "practiceCourseFee", "theoryCourseFee", "degreeFee", "repairFee", "leaseFee", "musicalFee", "teachingFee", "otherFee", "transferFee", "payTime", "musicGroupId",
                    "groupType.desc", "sporadicType", "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/teacherDefaultSalary")
    @PreAuthorize("@pcs.hasPermissions('export/teacherDefaultSalary')")
    public void exportTeacherDefaultSalary(String organIdList, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new IOException("用户信息获取失败");
        }
        List<TeacherDefaultSalaryDto> pageList = teacherService.queryTeacherDefaultSalary(organIdList);
        if (pageList.size() <= 0) {
            response.setStatus(200);
            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 {
            String[] header = {"老师编号", "姓名", "分部", "工作类型", "在职状态", "老师状态", "1v1", "1v2", "1v3", "1v4", "1v5", "1v6", "1v7",
                    "网管课", "单技课2.0(主教)", "合奏课2.0(主教)", "综合课2.0(主教)", "集训单技课2.0(主教)", "集训合奏课2.0(主教)",
                    "基础技能课2.0(主教)", "课堂课(主教)", "单技课3.0(主教)", "合奏课3.0(主教)", "综合课3.0(主教)", "集训单技课3.0(主教)", "集训合奏课3.0(主教)",
                    "基础技能课3.0(主教)"
                    , "单技课2.0(助教)", "合奏课2.0(助教)", "综合课2.0(助教)", "集训单技课2.0(助教)", "集训合奏课2.0(助教)",
                    "基础技能课2.0(助教)", "课堂课(助教)", "单技课3.0(助教)", "合奏课3.0(助教)", "综合课3.0(助教)", "集训单技课3.0(助教)", "集训合奏课3.0(助教)",
                    "基础技能课3.0(助教)", "网络基础训练课1v3", "网络基础训练课1v4", "网络基础训练课1v5", "乐团网管课1v1"};
            String[] body = {"userId", "realName", "organName", "jobNature", "demissionStatus", "status", "vip1", "vip2", "vip3", "vip4", "vip5", "vip6", "vip7",
                    "practiceSalary", "mainSingleSalary2", "mainMixSalary2", "mainComprehensiveSalary2", "mainTraningSigleSalary2", "mainTraningMixSalary2",
                    "mainHighSalary2", "mainClassroomSalary2", "mainSingleSalary", "mainMixSalary", "mainComprehensiveSalary", "mainTraningSigleSalary", "mainTraningMixSalary",
                    "mainHighSalary",
                    "assistantSingleSalary2", "assistantMixSalary2", "assistantComprehensiveSalary2", "assistantTraningSigleSalary2", "assistantTraningMixSalary2",
                    "assistantHighSalary2", "assistantClassroomSalary2", "assistantSingleSalary", "assistantMixSalary", "assistantComprehensiveSalary", "assistantTraningSigleSalary", "assistantTraningMixSalary",
                    "assistantHighSalary", "highOnline3Salary", "highOnline4Salary", "highOnline5Salary", "musicNetwork1Salary"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, pageList);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=teacherDefaultSalary-" + 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/musicGroupNormalStudentNum")
    @PreAuthorize("@pcs.hasPermissions('export/musicGroupNormalStudentNum')")
    public void musicGroupNormalStudentNum(String organIds, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isBlank(organIds)) {
                organIds = employee.getOrganIdList();
            }
        }

        List<MusicGroupStatusEnum> musicGroupStatusList = new ArrayList<>();
        musicGroupStatusList.add(MusicGroupStatusEnum.PAY);
        musicGroupStatusList.add(MusicGroupStatusEnum.PREPARE);
        musicGroupStatusList.add(MusicGroupStatusEnum.PROGRESS);
        musicGroupStatusList.add(MusicGroupStatusEnum.PAUSE);
        List<MusicGroupRegisterDto> musicGroupRegisters = musicGroupDao.getMusicGroupRegister(musicGroupStatusList, organIds);

        if (musicGroupRegisters.size() <= 0) {
            response.setStatus(200);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        List<String> musicGroupIds = musicGroupRegisters.stream().map(MusicGroupRegisterDto::getMusicGroupId).collect(Collectors.toList());

        List<RegisterSubjectDto> registerSubjects = musicGroupDao.getRegisterSubjectNum(musicGroupIds, StudentMusicGroupStatusEnum.NORMAL, null);

        HashSet<Integer> added = new HashSet<>();
        List<String> header = new ArrayList<>();
        header.add("分部");
        header.add("乐团名称");
        header.add("乐团状态");
        header.add("在读总人数");
        List<String> body = new ArrayList<>();
        body.add("organName");
        body.add("musicGroupName");
        body.add("musicGroupStatus");
        body.add("normalNum");
        for (RegisterSubjectDto registerSubject : registerSubjects) {
            if (!added.contains(registerSubject.getSubjectId())) {
                added.add(registerSubject.getSubjectId());
                header.add(registerSubject.getSubjectName());
                body.add("subject" + registerSubject.getSubjectId());
            }
        }

        List<Map<String, Object>> data = new ArrayList<>();
        for (MusicGroupRegisterDto musicGroupRegister : musicGroupRegisters) {
            added.clear();
            HashMap<String, Object> musicGroupRegisterMap = new HashMap<>();

            musicGroupRegisterMap.put("organName", musicGroupRegister.getOrganName());
            musicGroupRegisterMap.put("musicGroupName", musicGroupRegister.getMusicGroupName());
            musicGroupRegisterMap.put("musicGroupStatus", musicGroupRegister.getMusicGroupStatus().getMsg());
            musicGroupRegisterMap.put("normalNum", musicGroupRegister.getNormalNum());

            for (RegisterSubjectDto registerSubject : registerSubjects) {
                if (registerSubject.getMusicGroupId().equals(musicGroupRegister.getMusicGroupId())) {
                    added.add(registerSubject.getSubjectId());
                    musicGroupRegisterMap.put("subject" + registerSubject.getSubjectId(), registerSubject.getNum());
                }
                if (!added.contains(registerSubject.getSubjectId())) {
                    musicGroupRegisterMap.put("subject" + registerSubject.getSubjectId(), 0);
                }
            }
            data.add(musicGroupRegisterMap);
        }

        OutputStream outputStream = response.getOutputStream();
        try {
            String[] headerStr = header.toArray(new String[header.size()]);
            String[] bodyStr = body.toArray(new String[body.size()]);

            HSSFWorkbook workbook = POIUtil.exportExcel(headerStr, bodyStr, data);
            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/studentOrder")
    @PreAuthorize("@pcs.hasPermissions('export/studentOrder')")
    public void studentOrder(String organIds, Date date, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isBlank(organIds)) {
                organIds = employee.getOrganIdList();
            }
        }
        Date startTime = DateUtil.getFirstDayOfMonth(date);
        Date EndTime = DateUtil.getLastSecondWithDay(DateUtil.getLastDayOfMonth(date));

        List<OrderTypeEnum> orderTypeList = new ArrayList<>();
        orderTypeList.add(OrderTypeEnum.SPORADIC);
        orderTypeList.add(OrderTypeEnum.PRACTICE_GROUP_BUY);
        orderTypeList.add(OrderTypeEnum.PRACTICE_GROUP_RENEW);
        orderTypeList.add(OrderTypeEnum.SMALL_CLASS_TO_BUY);
        List<OrderByTypeExportDto> orders = studentPaymentOrderDao.getOrderByMonthAndType(organIds, orderTypeList, startTime, EndTime);

        if (orders.size() <= 0) {
            response.setStatus(200);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        List<Long> vipGroupIds = orders.stream().filter(e -> e.getGroupType().equals(GroupType.VIP)).map(OrderByTypeExportDto::getMusicGroupId).collect(Collectors.toList());
        List<Long> practiceGroupIds = orders.stream().filter(e -> e.getGroupType().equals(GroupType.PRACTICE)).map(OrderByTypeExportDto::getMusicGroupId).collect(Collectors.toList());
        List<Integer> studentIds = orders.stream().filter(e -> e.getGroupType().equals(GroupType.SPORADIC)).map(OrderByTypeExportDto::getStudentId).collect(Collectors.toList());

        List<VipBuyResultDto> vipGroupTeachers = new ArrayList<>();
        List<PracticeCourseDto> practiceGroupsTeacher = new ArrayList<>();
        List<Student> studentTeachers = new ArrayList<>();
        if (vipGroupIds.size() > 0) {
            vipGroupTeachers = vipGroupDao.getGroupTeachers(vipGroupIds);
        }

        if (practiceGroupIds.size() > 0) {
            practiceGroupsTeacher = practiceGroupDao.getPracticeGroupByIds(practiceGroupIds);
        }
        if (studentIds.size() > 0) {
            studentTeachers = studentDao.getStudentTeacher(studentIds);
        }

        for (OrderByTypeExportDto order : orders) {
            for (VipBuyResultDto vipGroupTeacher : vipGroupTeachers) {
                if (order.getGroupType().equals(GroupType.VIP) && order.getMusicGroupId().equals(vipGroupTeacher.getVipGroupId().longValue())) {
                    order.setTeacherName(vipGroupTeacher.getTeacherName());
                    order.setEduTeacherName(vipGroupTeacher.getEduTeacherName());
                    break;
                }
            }
            for (PracticeCourseDto practiceCourseDto : practiceGroupsTeacher) {
                if (order.getGroupType().equals(GroupType.PRACTICE) && order.getMusicGroupId().equals(practiceCourseDto.getId())) {
                    order.setTeacherName(practiceCourseDto.getTeacherName());
                    order.setEduTeacherName(practiceCourseDto.getEduTeacherName());
                    break;
                }
            }
            for (Student studentTeacher : studentTeachers) {
                if (order.getGroupType().equals(GroupType.SPORADIC) && studentTeacher.getUserId().equals(order.getStudentId())) {
                    order.setTeacherName(studentTeacher.getTeacherName());
                    break;
                }
            }

        }

        OutputStream outputStream = response.getOutputStream();
        try {
            String[] header = {"学员编号", "学员姓名", "指导老师", "教务老师", "订单日期", "交易类型", "实际金额"};
            String[] body = {"studentId", "studentName", "teacherName", "eduTeacherName", "createTime", "orderType.msg", "actualAmount"};

            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, orders);
            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/exportSellOrders")
    @PreAuthorize("@pcs.hasPermissions('export/exportSellOrders')")
    public void exportSellOrders(HttpServletResponse response, SellOrderQueryInfo queryInfo) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(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.getOrganIdList().split(",")))) {
                    throw new BizException("非法请求");
                }
            }
        }
        if (queryInfo.getEndTime() != null) {
            queryInfo.setEndTime(DateUtil.getLastTimeWithDay(queryInfo.getEndTime()));
        }
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
        List<SellOrder> rows = sellOrderService.queryPage(queryInfo).getRows();
        for (SellOrder row : rows) {
            if (StringUtils.isNoneBlank(row.getPaymentChannel())) {
                row.setPaymentChannelStr(PaymentChannelEnum.valueOf(row.getPaymentChannel()).getDesc());
            }
            row.setAccountTypeStr(AccountType.INTERNAL.equals(row.getAccountType()) ? "对内" : "对外");
            switch (row.getReceiveStatus()) {
                case "NO_RECEIVE":
                    row.setReceiveStatusStr("未确认");
                    break;
                case "MANUAL_RECEIVE":
                    row.setReceiveStatusStr("手动确认");
                    break;
                case "AUTO_RECEIVE":
                    row.setReceiveStatusStr("自动确认");
                    break;
            }
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{
                    "交易流水号", "订单号", "销售日期", "销售类型", "商品名称", "数量", "应付金额(元)", "余额支付(元)",
                    "现金支付(元)", "销售成本(元)", "学员姓名", "交易方式", "收款账户", "账户类型", "扣减库存", "所属分部",
                    "所属学校", "教务老师", "确认收货", "状态"}, new String[]{
                    "transNo", "orderNo", "sellTime", "type.desc", "goodsName", "num", "expectAmount", "balanceAmount",
                    "actualAmount", "sellCost", "userName", "paymentChannelStr", "merNo", "accountTypeStr", "stockType.msg", "organName",
                    "schoolName", "eduTeacher", "receiveStatusStr", "status.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();
                }
            }
        }
    }
}
