<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
这个文件是自动生成的。
不要修改此文件。所有改动将在下次重新自动生成时丢失。
-->
<mapper namespace="com.ym.mec.biz.dal.dao.StudentDao">

    <resultMap type="com.ym.mec.biz.dal.entity.Student" id="Student">
        <result column="user_id_" property="userId"/>
        <result column="school_name_" property="schoolName"/>
        <result column="subject_id_list_" property="subjectIdList"/>
        <result column="subject_name_" property="subjectNames"/>
        <result column="service_tag_" property="serviceTag"/>
        <result column="operating_tag_" property="operatingTag"/>
        <result column="operating_temp_tag_" property="operatingTempTag"/>
        <result column="teacher_id_" property="teacherId"/>
        <result column="teacher_name_" property="teacherName"/>
        <result column="is_new_user_" property="isNewUser"/>
        <result column="create_time_" property="createTime"/>
        <result column="update_time_" property="updateTime"/>
        <result column="care_package_" property="carePackage"/>
        <result column="come_on_package_" property="comeOnPackage"/>
        <result column="current_grade_num_" property="currentGradeNum"/>
        <result column="current_class_" property="currentClass"/>
        <result column="cooperation_organ_id_" property="cooperationOrganId"/>
        <result column="member_rank_setting_id_" property="memberRankSettingId"/>
        <result column="membership_start_time_" property="membershipStartTime"/>
        <result column="membership_end_time_" property="membershipEndTime"/>
        <result column="experience_member_rank_setting_id_" property="experienceMemberRankSettingId"/>
        <result column="experience_membership_start_time_" property="experienceMembershipStartTime"/>
        <result column="experience_membership_end_time_" property="experienceMembershipEndTime"/>
        <result column="activity_course_detail_" property="activityCourseDetail"/>
        <result column="organ_name_" property="organName"/>
        <result column="phone_" property="phone"/>
        <result column="username_" property="username"/>
        <result column="count_flag_" property="countFlag"/>
        <result column="ext_subject_ids_" property="extSubjectIds"/>
        <result column="tenant_id_" property="tenantId"/>
    </resultMap>

    <!-- 根据主键查询一条记录 -->
    <select id="get" resultMap="Student">
        SELECT *
        FROM student
        WHERE user_id_ = #{id}
    </select>
    
    <select id="getLocked" resultMap="Student">
        SELECT *
        FROM student
        WHERE user_id_ = #{id} for update
    </select>

    <!-- 全查询 -->
    <select id="findAll" resultMap="Student">
        SELECT *
        FROM student where tenant_id_ = #{tenantId}
    </select>

    <select id="lockUser" resultType="int" useCache="false" flushCache="true">
        SELECT id_
        FROM sys_user
        WHERE id_ = #{userId} FOR
        UPDATE
    </select>

    <select id="lockUserReturnInfo" resultMap="com.ym.mec.biz.dal.dao.TeacherDao.SysUser">
        SELECT *
        FROM sys_user
        WHERE id_ = #{userId} FOR UPDATE
    </select>

    <select id="getUser" resultMap="com.ym.mec.biz.dal.dao.TeacherDao.SysUser">
        SELECT *
        FROM sys_user
        WHERE id_ = #{userId}
    </select>

    <!-- 向数据库增加一条记录 -->
    <insert id="insert" parameterType="com.ym.mec.biz.dal.entity.Student" useGeneratedKeys="true" keyColumn="id"
            keyProperty="id">
        INSERT INTO student (user_id_,school_name_,subject_id_list_,
        <if test="serviceTag != null">
            service_tag_,
        </if>
        <if test="operatingTag != null">
            operating_tag_,
        </if>
        teacher_id_,create_time_,update_time_,service_tag_update_time_,cooperation_organ_id_,
        care_package_,come_on_package_,member_rank_setting_id_,membership_start_time_,
        membership_end_time_,current_grade_num_,current_class_,ext_subject_ids_,tenant_id_)
        VALUES
        (#{userId},#{schoolName},#{subjectIdList},
        <if test="serviceTag != null">
            #{serviceTag},
        </if>
        <if test="operatingTag != null">
            #{operatingTag},
        </if>
        #{teacherId},NOW(),NOW(),NOW(),#{cooperationOrganId},
         #{carePackage},#{comeOnPackage},#{memberRankSettingId},#{membershipStartTime},
         #{membershipEndTime},#{currentGradeNum},#{currentClass},#{extSubjectIds},#{tenantId})
    </insert>

    <update id="update" parameterType="com.ym.mec.biz.dal.entity.Student">
        UPDATE student
        <set>
            <if test="schoolName != null">
                school_name_ = #{schoolName},
            </if>
            <if test="subjectIdList != null">
                subject_id_list_ = #{subjectIdList},
            </if>
            <if test="serviceTag != null">
                service_tag_update_time_=IF(service_tag_ = #{serviceTag}, service_tag_update_time_, NOW()),
                service_tag_ = #{serviceTag},
            </if>
            <if test="operatingTag != null">
                operating_tag_ = #{operatingTag},
            </if>
            <if test="operatingTempTag != null">
                operating_temp_tag_ = #{operatingTempTag},
            </if>
            <if test="teacherId != null">
                teacher_id_=#{teacherId},
            </if>
            <if test="isNewUser != null">
                is_new_user_=#{isNewUser},
            </if>
            <if test="carePackage != null">
                care_package_=#{carePackage},
            </if>
            <if test="comeOnPackage != null">
                come_on_package_=#{comeOnPackage},
            </if>
            <if test="currentGradeNum != null">
                current_grade_num_=#{currentGradeNum},
            </if>
            <if test="currentClass != null">
                current_class_=#{currentClass},
            </if>
            <if test="memberRankSettingId != null">
                member_rank_setting_id_=#{memberRankSettingId},
            </if>
            <if test="membershipStartTime != null">
                membership_start_time_=#{membershipStartTime},
            </if>
            <if test="membershipEndTime != null">
                membership_end_time_=#{membershipEndTime},
            </if>
            <if test="experienceMemberRankSettingId != null">
                experience_member_rank_setting_id_=#{experienceMemberRankSettingId},
            </if>
            <if test="experienceMembershipStartTime != null">
                experience_membership_start_time_=#{experienceMembershipStartTime},
            </if>
            <if test="experienceMembershipEndTime != null">
                experience_membership_end_time_=#{experienceMembershipEndTime},
            </if>
            <if test="activityCourseDetail != null">
                activity_course_detail_=#{activityCourseDetail},
            </if>
            <if test="extSubjectIds != null">
                ext_subject_ids_=#{extSubjectIds},
            </if>
                cooperation_organ_id_=#{cooperationOrganId},
                update_time_ = NOW()
        </set>
        WHERE user_id_ = #{userId} and tenant_id_ = #{tenantId}
    </update>

    <update id="updateStudentMember" parameterType="com.ym.mec.biz.dal.entity.Student">
        UPDATE student SET
                member_rank_setting_id_ = #{student.memberRankSettingId},
                membership_start_time_ = #{student.membershipStartTime},
                membership_end_time_ = #{student.membershipEndTime},
                experience_member_rank_setting_id_ = #{student.experienceMemberRankSettingId},
                experience_membership_start_time_ = #{student.experienceMembershipStartTime},
                experience_membership_end_time_ = #{student.experienceMembershipEndTime},
                update_time_ = NOW()
        WHERE user_id_ = #{student.userId}
    </update>

    <!-- 分页查询 -->
    <select id="queryPage" resultMap="Student" parameterType="map">
        SELECT s.*,su.username_,su.phone_,o.name_ organ_name_ FROM student s
        LEFT JOIN sys_user su ON  su.id_ = s.user_id_
        LEFT JOIN organization o ON  o.id_ = su.organ_id_
        <include refid="queryPageSql"/>
        ORDER BY s.activity_course_detail_ DESC
        <include refid="global.limit"/>
    </select>

    <!-- 查询当前表的总记录数 -->
    <select id="queryCount" resultType="int">
        SELECT COUNT(s.user_id_) FROM student s
        LEFT JOIN sys_user su ON  su.id_ = s.user_id_
        <include refid="queryPageSql"/>
    </select>
    <sql id="queryPageSql">
        <where>
        	s.tenant_id_ = #{tenantId} and su.del_flag_ = 0
            <if test="organId != null and organId != ''">
                AND FIND_IN_SET(su.organ_id_,#{organId})
            </if>
            <if test="search != null and search != ''">
                AND (s.user_id_ = #{search} OR su.username_ LIKE CONCAT('%', #{search}, '%') OR su.phone_ LIKE CONCAT('%', #{search}, '%'))
            </if>
        </where>
    </sql>
    <select id="findStudents" resultMap="com.ym.mec.biz.dal.dao.TeacherDao.SysUser">
        SELECT id_, username_, phone_,avatar_ FROM sys_user
        <include refid="studentQueryCondition"/>
        ORDER BY id_
        <include refid="global.limit"/>
    </select>
    <select id="countStudents" resultType="int">
        SELECT COUNT(id_) FROM sys_user
        <include refid="studentQueryCondition"/>
    </select>
    <sql id="studentQueryCondition">
        <where>
        	tenant_id_ = #{tenantId}
            <if test="organIdList!=null">
                organ_id_ IN
                <foreach collection="organIdList" item="organId" open="(" close=")" separator=",">
                    #{organId}
                </foreach>
            </if>
            <if test="search!=null">
                AND (username_ LIKE CONCAT('%', #{search}, '%') OR phone_ LIKE CONCAT('%', #{search}, '%'))
            </if>
            AND FIND_IN_SET("STUDENT", user_type_)
        </where>
    </sql>

    <select id="queryByOperatingTempTag" resultMap="Student">
        SELECT *
        FROM student
        WHERE operating_temp_tag_ = #{operatingTempTag}
    </select>

    <update id="batchUpdate" parameterType="java.util.List">
        <foreach collection="studentList" item="item" index="index" open="" close="" separator=";">
            UPDATE student
            <set>
	            <if test="item.schoolName != null">
	                school_name_ = #{item.schoolName},
	            </if>
                <if test="item.subjectIdList != null">
                    subject_id_list_ = #{item.subjectIdList},
                </if>
                <if test="item.currentGradeNum != null">
                    current_grade_num_=#{item.currentGradeNum},
                </if>
                <if test="item.currentClass != null and item.currentClass != ''">
                    current_class_ = #{item.currentClass},
                </if>
                <if test="item.serviceTag != null">
                    service_tag_ = #{item.serviceTag},
                </if>
                <if test="item.operatingTag != null">
                    operating_tag_ = #{item.operatingTag},
                </if>
                <if test="item.operatingTempTag != null">
                    operating_temp_tag_ = #{item.operatingTempTag},
                </if>
                <if test="item.teacherId != null">
                    teacher_id_=#{item.teacherId},
                </if>
                <if test="item.updateTime != null">
                    update_time_ = #{item.updateTime},
                </if>
                <if test="item.carePackage != null">
                    care_package_=#{item.carePackage},
                </if>
                <if test="item.comeOnPackage != null">
                    come_on_package_=#{item.comeOnPackage},
                </if>
                <if test="item.cooperationOrganId != null">
                    cooperation_organ_id_=#{item.cooperationOrganId},
                </if>
                <if test="item.activityCourseDetail != null">
                    activity_course_detail_=#{item.activityCourseDetail},
                </if>
	            <if test="item.memberRankSettingId != null">
	                member_rank_setting_id_=#{item.memberRankSettingId},
	            </if>
	            <if test="item.membershipStartTime != null">
	                membership_start_time_=#{item.membershipStartTime},
	            </if>
	            <if test="item.membershipEndTime != null">
	                membership_end_time_=#{item.membershipEndTime},
	            </if>
	            <if test="item.extSubjectIds != null">
	                ext_subject_ids_=#{item.extSubjectIds},
	            </if>
                update_time_ = NOW()
            </set>
            WHERE user_id_ = #{item.userId} and tenant_id_ = #{item.tenantId}
        </foreach>
    </update>
    <update id="updateStudentServiceOrOperatingTag">
        UPDATE student
        <set>
            <if test="serviceTag != null">
                service_tag_ = #{serviceTag},
            </if>
            <if test="operatingTag != null">
                operating_tag_ = #{operatingTag},
            </if>
                update_time_ = NOW()
        </set>
        WHERE
        <if test="studentId!=null">
            user_id_ = #{studentId}
        </if>
        <if test="studentIds!=null and studentIds.size()>0">
            user_id_ IN
            <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                #{studentId}
            </foreach>
        </if>
    </update>

    <update id="updateStudentServiceTag">
        UPDATE student
        <set>
            <if test="serviceTag != null">
                service_tag_update_time_ = IF(service_tag_=#{serviceTag}, service_tag_update_time_, NOW()),
                service_tag_ = #{serviceTag},
            </if>
            update_time_ = NOW()
        </set>
        WHERE
            service_tag_=0
        <if test="studentId!=null">
            AND user_id_ = #{studentId}
        </if>
        <if test="studentIds!=null and studentIds.size()>0">
            AND user_id_ IN
            <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                #{studentId}
            </foreach>
        </if>
    </update>
    <update id="batchUpdateAdviser">
      UPDATE student s SET s.teacher_id_ = #{teacherId},s.update_time_ = NOW() WHERE FIND_IN_SET(s.user_id_,#{studentIds})
    </update>
    <update id="updateServiceTag">
        UPDATE student SET service_tag_ = #{serviceTag},update_time_ = NOW() WHERE user_id_ IN
        <foreach collection="studentIds" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </update>

    <resultMap id="student4operating" type="com.ym.mec.biz.dal.dto.Student4operating">
        <result column="organ_name_" property="organName"/>
        <result column="organ_id_" property="organId"/>
        <result column="student_name_" property="studentName"/>
        <result column="student_id_" property="studentId"/>
        <result column="teacher_id_" property="teacherId"/>
        <result column="teacher_name_" property="teacherName"/>
        <result column="operating_tag_" property="operatingTag"/>
        <result column="vip_times_" property="vipTimes"/>
        <result column="free_practice_times_" property="freePracticeTimes"/>
        <result column="buy_practice_times_" property="buyPracticeTimes"/>
        <result column="music_netWork_times_" property="musicNetWorkTimes"/>
        <result column="student_num_" property="studentNum"/>
    </resultMap>

    <select id="getOperatingStudents" resultMap="student4operating">
        SELECT su.organ_id_,
        o.name_ organ_name_,
        su.username_ student_name_,
        s.user_id_ student_id_,
        tsu.id_ teacher_id_,
        tsu.real_name_ teacher_name_,
        s.operating_tag_,
        a.vip_times_,
        a.buy_practice_times_,
        a.music_netWork_times_,
        p.free_practice_times_
        FROM student s
        LEFT JOIN sys_user su ON s.user_id_ = su.id_
        LEFT JOIN sys_user tsu ON tsu.id_ = s.teacher_id_
        LEFT JOIN organization o ON o.id_ = su.organ_id_
        LEFT JOIN (
        SELECT cssp.user_id_,
        SUM(case when (cs.group_type_ = 'VIP' AND cs.teach_mode_='ONLINE') then 1 ELSE 0 END) vip_times_,
        SUM(case when (pg.type_='CHARGE') then 1 ELSE 0 END) buy_practice_times_,
        SUM(case when (cs.type_='MUSIC_NETWORK' OR cs.type_='HIGH_ONLINE') then 1 ELSE 0 END) music_netWork_times_
        FROM course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_
        LEFT JOIN practice_group pg ON pg.`id_` = cs.`music_group_id_` AND cs.`group_type_` = 'PRACTICE'
        WHERE cs.status_ IN ('NOT_START','UNDERWAY') AND (cs.is_lock_ IS NULL OR cs.is_lock_=0) AND (cs.del_flag_ IS NULL OR cs.del_flag_=0)
        GROUP BY cssp.user_id_
        ) a on a.user_id_ = s.user_id_
        LEFT JOIN (
        SELECT student_id_, count(id_) free_practice_times_
        FROM practice_group
        WHERE type_='FREE' AND group_status_ IN ('NORMAL', 'FINISH')
        GROUP BY student_id_
        ) p ON p.student_id_ = s.user_id_
        <include refid="student4OperatingQueryCondition"/>
        ORDER BY s.user_id_
        <include refid="global.limit"/>
    </select>

    <select id="countOperatingStudents" resultType="int">
        SELECT COUNT(s.user_id_) FROM student s
        LEFT JOIN sys_user su ON s.user_id_ = su.id_
        LEFT JOIN sys_user tsu ON tsu.id_ = s.teacher_id_
        LEFT JOIN (
        SELECT cssp.user_id_,
        SUM(case when (cs.group_type_ = 'VIP' AND cs.teach_mode_='ONLINE') then 1 ELSE 0 END) vip_times_,
        SUM(case when (pg.type_='CHARGE') then 1 ELSE 0 END) buy_practice_times_,
        SUM(case when (cs.type_='MUSIC_NETWORK' OR cs.type_='HIGH_ONLINE') then 1 ELSE 0 END) music_netWork_times_
        FROM course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_
        LEFT JOIN practice_group pg ON pg.`id_` = cs.`music_group_id_` AND cs.`group_type_` = 'PRACTICE'
        WHERE cs.status_ IN ('NOT_START','UNDERWAY') AND (cs.is_lock_ IS NULL OR cs.is_lock_=0) AND (cs.del_flag_ IS NULL OR cs.del_flag_=0)
        GROUP BY cssp.user_id_
        ) a on a.user_id_ = s.user_id_
        LEFT JOIN (
        SELECT student_id_, count(id_) free_practice_times_
        FROM practice_group
        WHERE type_='FREE' AND group_status_ IN ('NORMAL', 'FINISH')
        GROUP BY student_id_
        ) p ON p.student_id_ = s.user_id_
        <include refid="student4OperatingQueryCondition"/>
    </select>

    <sql id="student4OperatingQueryCondition">
        <where>
            su.user_type_ LIKE '%STUDENT%' and s.tenant_id_ = #{tenantId}
            <if test="search != null and search != ''">
                AND (su.phone_ LIKE CONCAT('%',#{search},'%') OR su.username_ LIKE CONCAT('%',#{search},'%') OR su.id_
                LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="organId != null and organId != ''">
                AND FIND_IN_SET(su.organ_id_,#{organId})
            </if>
            <if test="teacherId!=null">
                AND s.teacher_id_ = #{teacherId}
            </if>
            <if test="operatingTag !=null">
                AND s.operating_tag_ = #{operatingTag}
            </if>
            <if test='hasVip != null and hasVip=="1"'>
                AND a.vip_times_ >=1
            </if>
            <if test='hasVip != null and hasVip=="0"'>
                AND (a.vip_times_ =0 OR a.vip_times_ IS NULL)
            </if>
            <if test='hasFreePractice != null and hasFreePractice=="1"'>
                AND p.free_practice_times_ >=1
            </if>
            <if test='hasFreePractice != null and hasFreePractice=="0"'>
                AND (p.free_practice_times_ =0 OR p.free_practice_times_ IS NULL)
            </if>
            <if test='hasBuyPractice != null and hasBuyPractice=="1"'>
                AND a.buy_practice_times_ >=1
            </if>
            <if test='hasBuyPractice != null and hasBuyPractice=="0"'>
                AND (a.buy_practice_times_ =0 OR a.buy_practice_times_ IS NULL)
            </if>
            <if test='hasMusicNetWork != null and hasMusicNetWork=="1"'>
                AND a.music_netWork_times_ >=1
            </if>
            <if test='hasMusicNetWork != null and hasMusicNetWork=="0"'>
                AND (a.music_netWork_times_ =0 OR a.music_netWork_times_ IS NULL)
            </if>
        </where>
    </sql>

    <select id="getTeacherOperatingStudentsNum" resultType="java.util.Map">
        select teacher_id_ 'key', count(*) 'value'
        FROM student
        WHERE FIND_IN_SET(teacher_id_, #{teacherIds})
          AND operating_tag_ = 1
        GROUP BY teacher_id_
    </select>

    <select id="getBuyNums" resultType="java.util.Map">
        SELECT s.teacher_id_ 'key', COUNT(DISTINCT cssp.user_id_) 'value'
        FROM course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_ AND cs.teach_mode_ = 'ONLINE'
        LEFT JOIN student s ON s.user_id_ = cssp.user_id_
        <if test="groupType != null and groupType==@com.ym.mec.biz.dal.enums.GroupType@PRACTICE">
            LEFT JOIN practice_group pg ON cssp.music_group_id_ = pg.id_ AND cssp.group_type_ = 'PRACTICE'
        </if>
        WHERE s.teacher_id_ = #{teacherId}
        AND cs.status_ IN ('NOT_START', 'UNDERWAY')
        AND (cs.is_lock_ IS NULL OR cs.is_lock_ = 0)
        <if test="groupType != null">
            AND cs.group_type_ = #{groupType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
        </if>
        <if test="groupType != null and groupType==@com.ym.mec.biz.dal.enums.GroupType@PRACTICE">
            AND pg.group_status_ IN ('NORMAL', 'FINISH')
            AND pg.buy_months_ >= 1
        </if>
        GROUP BY s.teacher_id_
    </select>
    <select id="getPracticeAndVipNums" resultType="java.util.Map">
        SELECT s.teacher_id_ 'key', COUNT(DISTINCT pg.student_id_) 'value'
        FROM practice_group pg
                 LEFT JOIN student s on s.user_id_ = pg.student_id_
                 LEFT JOIN course_schedule_student_payment vcssp
                           ON vcssp.user_id_ = pg.student_id_ AND vcssp.group_type_ = 'VIP'
                 LEFT JOIN course_schedule_student_payment pcssp
                           ON pcssp.user_id_ = pg.student_id_ AND pcssp.group_type_ = 'PRACTICE'
                 LEFT JOIN course_schedule vcs ON vcs.id_ = vcssp.course_schedule_id_ AND vcs.teach_mode_ = 'ONLINE'
                 LEFT JOIN course_schedule pcs ON pcs.id_ = pcssp.course_schedule_id_
        WHERE FIND_IN_SET(s.teacher_id_, #{teacherIds})
          AND pg.group_status_ IN ('NORMAL', 'FINISH')
          AND vcs.status_ IN ('NOT_START', 'UNDERWAY')
          AND pcs.status_ IN ('NOT_START', 'UNDERWAY')
          AND (vcs.is_lock_ IS NULL OR vcs.is_lock_ = 0)
          AND (pcs.is_lock_ IS NULL OR pcs.is_lock_ = 0)
          AND pg.buy_months_ >= 1
        GROUP BY s.teacher_id_
    </select>
    <select id="getServiceStudents" resultMap="Student">
        SELECT su.id_ user_id_,s.teacher_id_ FROM sys_user su
        LEFT JOIN student s ON s.user_id_=su.id_
        WHERE s.service_tag_=1 AND FIND_IN_SET('STUDENT', su.user_type_) and s.tenant_id_ = #{tenantId}
    </select>

    <resultMap id="StudentServeDto" type="com.ym.mec.biz.dal.dto.StudentServeDto" extends="Student">
        <result column="group_type_" property="groupType" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="teach_mode_" property="teachMode" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result property="courseStartTime" column="course_start_time_"/>
    </resultMap>
    <select id="getBeServiceStudentsInfoWithStudents" resultMap="StudentServeDto">
        SELECT
            s.user_id_,
            s.teacher_id_,
            cs.group_type_,
            cs.teach_mode_,
            IF(CONCAT( cs.class_date_, ' ', cs.end_class_time_ )&lt;#{courseExpireDate} AND (sa.status_ != 'NORMAL' OR sa.status_ IS NULL), NULL, cs.class_date_) course_start_time_
        FROM
          student s
        LEFT JOIN course_schedule_student_payment cssp ON cssp.user_id_ = s.user_id_
        LEFT JOIN student_attendance sa ON cssp.course_schedule_id_=sa.course_schedule_id_ AND sa.user_id_=cssp.user_id_
        LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_
        AND cs.group_type_ IN ('VIP', 'PRACTICE')
        AND CONCAT( cs.class_date_, ' ', cs.start_class_time_ ) > #{monday}
        WHERE
        s.service_tag_ = 1 AND s.user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
    </select>
    <select id="getBeServiceStudentsInfoWithStudentsForHistory" resultMap="StudentServeDto">
        SELECT
            s.student_id_ user_id_,
            s.teacher_id_,
            cs.group_type_,
            cs.teach_mode_,
            IF(CONCAT( cs.class_date_, ' ', cs.end_class_time_ )&lt;#{courseExpireDate} AND (sa.status_ != 'NORMAL' OR sa.status_ IS NULL), NULL, cs.class_date_) course_start_time_
        FROM
          student_extracurricular_exercises_situation_ s
        LEFT JOIN course_schedule_student_payment cssp ON cssp.user_id_ = s.student_id_
        LEFT JOIN student_attendance sa ON cssp.course_schedule_id_=sa.course_schedule_id_ AND sa.user_id_=cssp.user_id_
        LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_
        AND cs.group_type_ IN ('VIP', 'PRACTICE')
        AND CONCAT( cs.class_date_, ' ', cs.start_class_time_ ) > #{monday}
        WHERE
        s.monday_ = #{monday} AND s.student_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
    </select>
    <select id="getServeStudentIds" resultType="int">
        SELECT user_id_
        FROM student stu
          LEFT JOIN sys_user su ON stu.user_id_=su.id_
        WHERE service_tag_=1 AND su.del_flag_=0
        and stu.tenant_id_ = #{tenantId}
    </select>
    <select id="getServeStudentCourseStartTimes" resultType="com.ym.mec.biz.dal.dto.StudentServeCourseDto">
        SELECT
            cssp.user_id_ studentId,
            stu.service_tag_update_time_ serviceTagUpdateTime,
            CONCAT(cs.class_date_, ' ', cs.start_class_time_) courseStartTime
        FROM course_schedule_student_payment cssp
            LEFT JOIN course_schedule cs ON cs.id_=cssp.course_schedule_id_
            LEFT JOIN student stu ON cssp.user_id_ = stu.user_id_
        WHERE stu.service_tag_=1 AND class_date_&gt;=#{monday} and cssp.tenant_id_ = #{tenantId}
    </select>

    <resultMap id="StudentServeCourseDto" type="com.ym.mec.biz.dal.dto.StudentServeCourseDto">
        <result column="student_id_" property="studentId"/>
        <result column="lead_teacher_id_" property="leadTeacherId"/>
        <result column="course_schedule_id_" property="courseScheduleId"/>
        <result column="group_type_" property="groupType" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="music_group_id_" property="musicGroupId"/>
        <result column="class_group_id_" property="classGroupId"/>
        <result column="status_" property="status" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="type_" property="type" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="actual_teacher_id_" property="actualTeacherId"/>
        <result column="course_start_time_" property="courseStartTime"/>
        <result column="teach_mode_" property="teachMode"/>
    </resultMap>

    <select id="getStudentFutureCourseInfo" resultMap="StudentServeCourseDto">
        SELECT
            cssp.user_id_ student_id_,
            cs.id_ course_schedule_id_,
            cs.group_type_,
            cs.music_group_id_,
            cs.class_group_id_,
            cs.status_,
            CASE cs.type_ WHEN 'TRAINING_SINGLE' THEN 'SINGLE' WHEN 'TRAINING_MIX' THEN 'MIX' ELSE cs.type_ END type_,
            cs.actual_teacher_id_,
            CONCAT(cs.class_date_, ' ', cs.start_class_time_) course_start_time_,
            cs.teach_mode_
        FROM course_schedule_student_payment cssp
            LEFT JOIN course_schedule cs ON cssp.course_schedule_id_=cs.id_
        WHERE cssp.tenant_id_ = #{tenantId}
            AND (cs.del_flag_ IS NULL OR cs.del_flag_=0)
            AND (cs.new_course_id_ IS NULL OR cs.new_course_id_=cs.id_)
            AND cs.class_date_ between #{monday} and #{sunday}
            AND cs.type_ IN ('SINGLE', 'TRAINING_SINGLE', 'MIX', 'TRAINING_MIX')
            <if test="studentIds!=null and studentIds.size()>0">
                AND cssp.user_id_ IN
                <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                    #{studentId}
                </foreach>
            </if>
        ORDER BY cssp.user_id_,course_start_time_
    </select>

    <select id="getNoCourseBeServeStudentInfo" resultMap="StudentServeCourseDto">
        SELECT
            sr.user_id_ student_id_,
            stu.teacher_id_ lead_teacher_id_,
            'MUSIC' group_type_,
            sr.music_group_id_
        FROM
            student_registration sr
            LEFT JOIN student stu ON sr.user_id_ = stu.user_id_
            LEFT JOIN music_group mg ON sr.music_group_id_ = mg.id_
        WHERE
            mg.del_flag_ = 0 and sr.tenant_id_ = #{tenantId}
            AND mg.organ_id_ IS NOT NULL
            AND mg.status_ = 'PROGRESS'
            AND sr.music_group_status_ = 'NORMAL'
            <if test="studentIds!=null and studentIds.size()>0">
                AND sr.user_id_ IN
                <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                    #{studentId}
                </foreach>
            </if>
    </select>

    <select id="getStudentNames" resultType="string">
        SELECT username_ FROM sys_user WHERE id_ IN
        <foreach collection="studentIds" item="studentId" separator="," open="(" close=")">
            #{studentId}
        </foreach>
    </select>
    <select id="getStudentsWithOrgan" resultType="com.ym.mec.biz.dal.dto.SimpleUserDto">
        SELECT
            su.id_ userId,su.username_ userName, su.avatar_ avatar, su.phone_ phone
        FROM
            sys_user su
        WHERE
            su.tenant_id_ = #{tenantId}
            AND su.del_flag_=0 AND su.lock_flag_=0
            AND FIND_IN_SET('STUDENT',su.user_type_)
            <if test="organIds!=null">
                AND su.organ_id_ IN
                <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                    #{organId}
                </foreach>
            </if>
            <if test="search != null">
                AND (su.username_ LIKE CONCAT('%', #{search}, '%') OR su.phone_ LIKE CONCAT('%', #{search}, '%'))
            </if>
        ORDER BY su.id_
        <include refid="global.limit"/>
    </select>

    <select id="countStudentsWithOrgan" resultType="int">
        SELECT
            COUNT(su.id_)
        FROM
            sys_user su
        WHERE
            su.tenant_id_ = #{tenantId}
            AND su.del_flag_=0 AND su.lock_flag_=0
            AND FIND_IN_SET('STUDENT',su.user_type_)
            <if test="organIds!=null">
                AND su.organ_id_ IN
                <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                    #{organId}
                </foreach>
            </if>
            <if test="search != null">
                AND (su.username_ LIKE CONCAT('%', #{search}, '%') OR su.phone_ LIKE CONCAT('%', #{search}, '%'))
            </if>
    </select>

    <select id="getStudentTeacher" resultMap="Student">
        SELECT s.user_id_,t.real_name_ teacher_name_ FROM student s
        LEFT JOIN sys_user t ON t.id_ = s.teacher_id_
        WHERE s.user_id_ IN
        <foreach collection="studentIds" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

    <select id="findByStudentIds" resultMap="Student">
        SELECT * FROM student WHERE user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
    </select>

    <select id="lockStudents" resultMap="Student">
        SELECT * FROM student WHERE user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
        FOR UPDATE
    </select>

    <select id="queryCloseServiceTagIds" resultType="java.lang.Integer">
        SELECT s.user_id_ FROM student s
        LEFT JOIN course_schedule_student_payment cssp ON cssp.user_id_ = s.user_id_
        LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_
        LEFT JOIN student_registration sr ON sr.user_id_ = s.user_id_
        LEFT JOIN music_group mg ON mg.id_ = sr.music_group_id_
        WHERE s.service_tag_ = 1
        GROUP BY s.user_id_ HAVING COUNT(CASE WHEN cs.status_ = 'NOT_START' THEN 1 ELSE NULL END) = 0
        AND COUNT(CASE WHEN sr.music_group_status_ = 'NORMAL' AND mg.status_ = 'PROGRESS' THEN 1 ELSE NULL END) = 0;
    </select>

    <select id="getStudentSubjects" resultMap="com.ym.mec.biz.dal.dao.SubjectDao.Subject">
        SELECT
            DISTINCT sub.*
        FROM
            student stu
            LEFT JOIN `subject` sub ON FIND_IN_SET( sub.id_, stu.subject_id_list_ )
        WHERE
            stu.user_id_ IN
            <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                #{studentId}
            </foreach>
            AND sub.id_ IS NOT NULL
        ORDER BY sub.id_ DESC
    </select>

    <select id="queryByIds" resultMap="Student">
        SELECT * FROM student
        WHERE user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
        ORDER BY user_id_
        <include refid="global.limit"></include>
    </select>
    <select id="countByIds" resultType="int">
        SELECT count(user_id_) FROM student
        WHERE user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
    </select>
    <select id="getNoTeacherOrNoSubjectStudent" resultMap="Student">
        SELECT * FROM student WHERE teacher_id_ IS NULL OR subject_id_list_ IS NULL OR cooperation_organ_id_ IS NULL limit 0,1000;
    </select>

    <select id="getHasVipCourseStudentIdsFromNewStudents" resultType="int">
        SELECT DISTINCT(spo.user_id_) from student_payment_order spo LEFT JOIN student s on spo.user_id_ = s.user_id_ WHERE spo.type_ in ('DOUBLE_ELEVEN2021','DOUBLE_ELEVEN2020','SMALL_CLASS_TO_BUY')
		and spo.status_ = 'SUCCESS' and spo.expect_amount_ > 0 and s.is_new_user_ = 1
    </select>
    
    <select id="getMemberNum" resultType="int">
        SELECT COUNT(0) FROM student WHERE member_rank_setting_id_ IS NOT NULL AND FIND_IN_SET(user_id_,#{studentIdsStr})
    </select>

    <select id="queryPushMemberRenew" resultType="java.lang.Integer">
        SELECT s.user_id_ FROM student s
        LEFT JOIN cloud_teacher_order cto ON cto.student_id_ = s.user_id_ AND cto.status_ IN (1,2) where s.tenant_id_ = #{tenantId}
        GROUP BY s.user_id_ HAVING (MAX(cto.id_) IS NULL OR MIN(cto.status_) > 1)
        AND DATEDIFF(MAX(cto.end_time_),NOW()) = #{pushMemberRenew}
    </select>

    <select id="getOrganStudentNum" resultType="int">
        SELECT COUNT(DISTINCT user_id_)
        FROM ((SELECT sr.user_id_
               FROM student_registration sr
                        LEFT JOIN music_group mg ON sr.music_group_id_=mg.id_
                        LEFT JOIN sys_user su ON sr.user_id_=su.id_
               WHERE su.del_flag_=0
                 AND mg.status_='PROGRESS'
                 AND sr.music_group_status_='NORMAL'
                 AND su.organ_id_ = #{organId})
              UNION ALL
              (SELECT
                   cssp.user_id_
               FROM
                   course_schedule_student_payment cssp
                       LEFT JOIN course_schedule cs ON cssp.course_schedule_id_=cs.id_
                       LEFT JOIN sys_user su ON cssp.user_id_ = su.id_
               WHERE
                   cssp.group_type_ IN ('VIP', 'PRACTICE')
                 AND cs.status_='NOT_START'
                 AND su.del_flag_ = 0
                 AND su.organ_id_ = #{organId})) t
        WHERE t.user_id_ NOT IN (SELECT user_id_ FROM student WHERE subject_id_list_ REGEXP '21|25|26|27|28|29')
    </select>

    <select id="getOrgansCloudTeacherStudent" resultType="com.ym.mec.biz.dal.dto.IndexCloudStudyListDto">
        SELECT count(s.`user_id_`) totalStudentNum,
        sum(case when cto.student_id_ IS NULL then 0 else 1 end) waitActivateVipStudentNum,
        sum(case when s.`membership_end_time_` > now() then 1 else 0 end) effectiveVipStudentNum 
        FROM student s LEFT JOIN (
		SELECT distinct cto.`student_id_`  FROM `cloud_teacher_order` cto WHERE cto.`status_` = 1
		) cto on s.user_id_ = cto.student_id_
		LEFT JOIN `sys_user` u on s.`user_id_` = u.`id_`
		WHERE u.`del_flag_` = 0 
        <if test="organIds!=null and organIds.size()>0">
            AND u.organ_id_ IN
            <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                #{organId}
            </foreach>
        </if>
    </select>
    
    <select id="getOrganCloudTeacherStudentNum" resultType="com.ym.mec.biz.dal.dto.Mapper">
        SELECT u.organ_id_ `key`,sum(case when a.user_id_ IS NULL then 0 else 1 end) `value`  FROM student s 
		LEFT JOIN (
		SELECT s.`user_id_`  FROM `student` s WHERE s.`membership_end_time_` > now()
		union
		SELECT cto.`student_id_`  FROM `cloud_teacher_order` cto WHERE cto.`status_` = 1
		) a on a.user_id_ = s.`user_id_` 
		LEFT JOIN `sys_user` u on s.`user_id_` = u.`id_`
		WHERE u.`del_flag_` = 0 AND u.`organ_id_` IN
        <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
            #{organId}
        </foreach>
		GROUP BY u.`organ_id_` 
    </select>

    <select id="getOrgansStudentNum" resultType="map">
        SELECT su.organ_id_ 'key',COUNT(DISTINCT user_id_) 'value'
        FROM ((SELECT sr.user_id_
        FROM student_registration sr
        LEFT JOIN music_group mg ON sr.music_group_id_=mg.id_
        WHERE mg.status_='PROGRESS'
        AND sr.music_group_status_='NORMAL')
        UNION ALL
        (SELECT
        cssp.user_id_
        FROM
        course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cssp.course_schedule_id_=cs.id_
        WHERE
        cssp.group_type_ IN ('VIP', 'PRACTICE')
        AND cs.status_='NOT_START')) t
        LEFT JOIN sys_user su ON t.user_id_=su.id_
        WHERE su.del_flag_=0 AND t.user_id_ NOT IN (SELECT user_id_ FROM student WHERE subject_id_list_ REGEXP '21|25|26|27|28|29')
           AND su.organ_id_ IN
           <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
               #{organId}
           </foreach>
        GROUP BY su.organ_id_
    </select>

    <select id="getOrganTeacherStudentNum" resultType="map">
        SELECT stu.teacher_id_ 'key',COUNT(DISTINCT t.user_id_) 'value'
        FROM ((SELECT sr.user_id_
        FROM student_registration sr
        LEFT JOIN music_group mg ON sr.music_group_id_=mg.id_
        WHERE mg.status_='PROGRESS' AND sr.music_group_status_='NORMAL')
        UNION ALL
        (SELECT
        cssp.user_id_
        FROM
        course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cssp.course_schedule_id_=cs.id_
        WHERE
            cssp.group_type_ IN ('VIP', 'PRACTICE')
            AND cs.status_='NOT_START')) t
        LEFT JOIN student stu ON t.user_id_=stu.user_id_
        LEFT JOIN sys_user su ON t.user_id_ = su.id_
        LEFT JOIN teacher tea ON stu.teacher_id_=tea.id_
        WHERE su.del_flag_=0
        <if test="organId!=null">
            AND tea.organ_id_=#{organId}
        </if>
            AND stu.teacher_id_ IN
            <foreach collection="teacherIds" item="teacherId" open="(" close=")" separator=",">
                #{teacherId}
            </foreach>
        GROUP BY stu.teacher_id_
    </select>

    <select id="getOrganNoTeacherStudentNum" resultType="int">
        SELECT COUNT(DISTINCT stu.user_id_)
        FROM student stu
        LEFT JOIN sys_user su ON stu.user_id_ = su.id_
        WHERE su.del_flag_=0 AND stu.teacher_id_ IS NULL
            AND su.organ_id_=#{organId}
    </select>

    <select id="getCloudStudyStudentNum" resultType="int">
        SELECT
            COUNT(DISTINCT smcr.user_id_)
        FROM sys_music_compare_record smcr
             LEFT JOIN sys_user su ON smcr.user_id_=su.id_
             LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
        WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL AND su.organ_id_=#{organId};
    </select>

    <select id="getOrgansTotalCloudStudyStudentNum" resultType="int">
        SELECT
            COUNT(DISTINCT smcr.user_id_)
        FROM sys_music_compare_record smcr
                 LEFT JOIN sys_user su ON smcr.user_id_=su.id_
                 LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
        WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL
            AND su.organ_id_ IN
            <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                #{organId}
            </foreach>
    </select>

    <select id="getOrgansTodayTotalCloudStudyStudentNum" resultType="int">
        SELECT
        COUNT(DISTINCT smcr.user_id_)
        FROM sys_music_compare_record smcr
        LEFT JOIN sys_user su ON smcr.user_id_=su.id_
        LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
        WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL
        AND smcr.create_time_ > date_sub(curdate(),INTERVAL 0 day)
            AND su.organ_id_ IN
            <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                #{organId}
            </foreach>
    </select>

    <select id="getOrganCloudStudyStudentNum" resultType="map">
        SELECT
            su.organ_id_ 'key',
            COUNT(DISTINCT smcr.user_id_) 'value'
        FROM sys_music_compare_record smcr
                 LEFT JOIN sys_user su ON smcr.user_id_=su.id_
                 LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
        WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL
            AND su.organ_id_ IN
            <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                #{organId}
            </foreach>
        GROUP BY su.organ_id_
    </select>

    <select id="getOrganTeacherCloudStudyStudentNum" resultType="map">
        SELECT
        stu.teacher_id_ 'key',
        COUNT(DISTINCT smcr.user_id_) 'value'
        FROM sys_music_compare_record smcr
        LEFT JOIN sys_user su ON smcr.user_id_=su.id_
        LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
        LEFT JOIN teacher tea ON stu.teacher_id_=tea.id_
        WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL
        <if test="organId!=null">
            AND tea.organ_id_=#{organId}
        </if>
            AND stu.teacher_id_ IN
            <foreach collection="teacherIds" item="teacherId" open="(" close=")" separator=",">
                #{teacherId}
            </foreach>
        GROUP BY stu.teacher_id_
    </select>

    <select id="getCloudStudyLivelyStudentNum" resultType="int">
        SELECT COUNT(user_id_)
        FROM (SELECT
            smcr.user_id_,
            COUNT(DISTINCT(CASE WHEN DATEDIFF(NOW(), smcr.create_time_)&lt;=15 THEN DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') ELSE NULL END)) days
            FROM sys_music_compare_record smcr
            LEFT JOIN sys_user su ON smcr.user_id_=su.id_
            LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
            WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL AND su.organ_id_=#{organId}
            GROUP BY smcr.user_id_) t WHERE t.days>=5
    </select>

    <select id="getOrganTotalCloudStudyLivelyStudentNum" resultType="int">
        SELECT count(a.user_id_) FROM 
		(
		SELECT wd.`user_id_` FROM `sys_music_compare_week_data` wd  
		WHERE wd.`train_time_` >= 3600 AND wd.`monday_` BETWEEN date(#{startTime}) and date(#{endTime})  GROUP BY `user_id_` HAVING count(*) >= 3
		    ) a 
		LEFT JOIN `student` s on a.`user_id_` = s.`user_id_`
		LEFT JOIN `sys_user` u on u.`id_` = s.`user_id_` 
		WHERE u.`del_flag_` = 0 AND u.`organ_id_` IN
        <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
            #{organId}
        </foreach>
    </select>

    <select id="getOrganActiveCloudStudyStudentNum" resultType="com.ym.mec.biz.dal.dto.Mapper">
        SELECT u.`organ_id_` `key`,count(a.user_id_) `value` FROM 
		(
		SELECT wd.`user_id_` FROM `sys_music_compare_week_data` wd  
		WHERE wd.`train_time_` >= 3600 AND wd.`monday_` BETWEEN date(#{startTime}) and date(#{endTime})  GROUP BY `user_id_` HAVING count(*) >= 3
		    ) a 
		LEFT JOIN `student` s on a.`user_id_` = s.`user_id_`
		LEFT JOIN `sys_user` u on u.`id_` = s.`user_id_` 
		WHERE u.`del_flag_` = 0 AND u.`organ_id_` IN
        <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
            #{organId}
        </foreach>
		GROUP BY u.`organ_id_` 
    </select>

    <select id="getCloudStudyStudentOverViewList" resultType="com.ym.mec.biz.dal.dto.IndexCloudStudyListDto">
        SELECT o.`name_` organName,o.`id_` organId,count(s.`user_id_`) totalStudentNum,
        sum(case when cto.student_id_ IS NULL then 0 else 1 end) waitActivateVipStudentNum,
        sum(case when s.`membership_end_time_` > now() then 1 else 0 end) effectiveVipStudentNum 
        FROM student s LEFT JOIN (
		SELECT distinct cto.`student_id_`  FROM `cloud_teacher_order` cto WHERE cto.`status_` = 1
		) cto on s.user_id_ = cto.student_id_
		LEFT JOIN `sys_user` u on s.`user_id_` = u.`id_`
		LEFT JOIN `organization` o on o.`id_` = u.`organ_id_` 
		WHERE u.`del_flag_` = 0 AND u.`organ_id_` IN
        <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
            #{organId}
        </foreach>
		GROUP BY u.`organ_id_` 
    </select>

    <select id="getOrganCloudStudyLivelyStudentNum" resultType="map">
        SELECT
               t.organ_id_ 'key',
               COUNT(user_id_) 'value'
        FROM (SELECT
                su.organ_id_,
                  smcr.user_id_,
                  COUNT(DISTINCT(CASE WHEN DATEDIFF(NOW(), smcr.create_time_)&lt;=15 THEN DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') ELSE NULL END)) days
              FROM sys_music_compare_record smcr
                       LEFT JOIN sys_user su ON smcr.user_id_=su.id_
                       LEFT JOIN student stu ON smcr.user_id_=stu.user_id_
              WHERE su.del_flag_=0 AND stu.user_id_ IS NOT NULL
                    AND su.organ_id_ IN
                    <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                        #{organId}
                    </foreach>
              GROUP BY smcr.user_id_) t WHERE t.days>=5
        GROUP BY t.organ_id_
    </select>

    <sql id="queryCloudStudyStudentDataCondition">
        <where>
            su.del_flag_=0 AND t.user_id_ NOT IN (SELECT user_id_ FROM student WHERE subject_id_list_ REGEXP '21|25|26|27|28|29') and su.tenant_id_ = #{tenantId}
            <if test="organId!=null">
                AND su.organ_id_=#{organId}
            </if>
            <if test="search!=null and search!=''">
                AND (t.user_id_=#{search} OR su.username_ LIKE CONCAT('%', #{search}, '%'))
            </if>
        </where>
    </sql>

    <select id="queryCloudStudyStudentData" resultType="com.ym.mec.biz.dal.dto.EduOrganStudentListDto">
        SELECT
            stu.user_id_ studentId,
            su.username_ studentName,
            stu.teacher_id_ teacherId,
            tea.real_name_ teacherName,
            sub.name_	subjectName,
            stu.cloud_study_sequence_days_ cloudStudyRunningDays,
            COUNT(DISTINCT smcr.behavior_id_) cloudStudyUseNum,
            SUM(CASE WHEN smcr.play_time_ IS NULL THEN 0 ELSE play_time_ END) cloudStudyUseTime,
            COUNT(DISTINCT DATE(smcr.create_time_)) cloudStudyUseDays,
            stu.membership_end_time_ membershipEndTime,
            stu.current_grade_num_ currentGradeNum,stu.current_class_ currentClass,stu.count_flag_ countFlag
        FROM (SELECT DISTINCT t1.user_id_ FROM ((
                SELECT
                sr.user_id_
                FROM
                student_registration sr
                LEFT JOIN music_group mg ON sr.music_group_id_ = mg.id_
                WHERE
                mg.status_ = 'PROGRESS'
                AND sr.music_group_status_ = 'NORMAL'
                ) UNION ALL
                (
                SELECT
                cssp.user_id_
                FROM
                course_schedule_student_payment cssp
                LEFT JOIN course_schedule cs ON cssp.course_schedule_id_ = cs.id_
                WHERE
                cssp.group_type_ IN ( 'VIP', 'PRACTICE' )
                AND cs.status_ = 'NOT_START'
                )) t1) t
            LEFT JOIN student stu ON t.user_id_=stu.user_id_
            LEFT JOIN sys_user su ON stu.user_id_=su.id_
            LEFT JOIN sys_user tea ON stu.teacher_id_=tea.id_
            LEFT JOIN `subject` sub ON stu.subject_id_list_ = sub.id_
            LEFT JOIN sys_music_compare_record smcr ON stu.user_id_ = smcr.user_id_
        <include refid="queryCloudStudyStudentDataCondition" />
        GROUP BY stu.user_id_
        <trim prefix="ORDER BY " suffixOverrides=",">
            <if test="cloudStudyUseTime==null and cloudStudyRunningDays==null">
                stu.user_id_,
            </if>
            <if test="cloudStudyUseTime!=null">
                cloudStudyUseTime ${cloudStudyUseTime},
            </if>
            <if test="cloudStudyRunningDays!=null">
                cloudStudyRunningDays ${cloudStudyRunningDays}
            </if>
        </trim>
        <include refid="global.limit"></include>
    </select>
    <select id="countCloudStudyStudentData" resultType="int">
        SELECT
        COUNT( DISTINCT user_id_ )
        FROM
        ((
        SELECT
        sr.user_id_
        FROM
        student_registration sr
        LEFT JOIN music_group mg ON sr.music_group_id_ = mg.id_
        WHERE
        mg.status_ = 'PROGRESS'
        AND sr.music_group_status_ = 'NORMAL'
        ) UNION ALL
        (
        SELECT
        cssp.user_id_
        FROM
        course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cssp.course_schedule_id_ = cs.id_
        WHERE
        cssp.group_type_ IN ( 'VIP', 'PRACTICE' )
        AND cs.status_ = 'NOT_START'
        )) t
        LEFT JOIN sys_user su ON t.user_id_ = su.id_
        <include refid="queryCloudStudyStudentDataCondition" />
    </select>

    <select id="getOrganEVipStudentNum" resultType="int">
        SELECT COUNT(DISTINCT stu.user_id_)
        FROM student stu
             LEFT JOIN cloud_teacher_order cto ON stu.user_id_=cto.student_id_
             LEFT JOIN sys_user su ON su.id_=stu.user_id_
        WHERE su.del_flag_=0 AND su.organ_id_=#{organId} AND stu.experience_member_rank_setting_id_ IS NOT NULL
          AND NOT EXISTS (SELECT student_id_ FROM cloud_teacher_order WHERE student_id_=stu.user_id_ AND status_ IN (1,2))
    </select>

    <select id="getOrgansTotalEVipStudentNum" resultType="int">
        SELECT COUNT(DISTINCT stu.user_id_)
        FROM student stu
                 LEFT JOIN cloud_teacher_order cto ON stu.user_id_=cto.student_id_
                 LEFT JOIN sys_user su ON su.id_=stu.user_id_
        WHERE su.del_flag_=0 AND stu.experience_member_rank_setting_id_ IS NOT NULL AND (cto.id_ IS NULL OR cto.status_ NOT IN (1, 2))
            AND su.organ_id_ IN
            <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                #{organId}
            </foreach>
    </select>

    <select id="getTeacherExperienceMemberStudentNum" resultType="map">
        SELECT
        stu.teacher_id_ 'key',
        COUNT(DISTINCT stu.user_id_) 'value'
        FROM student stu
        LEFT JOIN cloud_teacher_order cto ON stu.user_id_=cto.student_id_
        LEFT JOIN sys_user su ON su.id_=stu.user_id_
        WHERE su.del_flag_=0 AND stu.experience_member_rank_setting_id_ IS NOT NULL AND (cto.id_ IS NULL OR cto.status_ NOT IN (1, 2))
        <if test="organId!=null">
            AND su.organ_id_=#{organId}
        </if>
            AND stu.teacher_id_ IN
            <foreach collection="teacherIds" item="teacherId" open="(" close=")" separator=",">
                #{teacherId}
            </foreach>
        GROUP BY stu.teacher_id_
    </select>

    <select id="getStudentSubjectMapList" resultType="java.util.Map">
        SELECT stu.user_id_ 'key',sub.name_ 'value'
        FROM student stu
             LEFT JOIN `subject` sub ON stu.subject_id_list_ = sub.id_
        WHERE stu.user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
    </select>
    <select id="groupOrganId" resultMap="com.ym.mec.biz.dal.dao.IndexBaseMonthDataDao.IndexBaseMonthData">
        SELECT su.organ_id_,CURDATE() month_,su.tenant_id_,
               COUNT(DISTINCT su.id_) total_num_ ,
               COUNT(DISTINCT su.id_) activate_num_ ,
               COUNT(DISTINCT su.id_) percent_
        FROM sys_user su
        WHERE 1 = 1
            AND su.id_ IN
            <foreach collection="userIds" item="userId" open="(" close=")" separator=",">
                #{userId}
            </foreach>
        <if test="organIds!=null and organIds.size() > 0">
            AND su.organ_id_ IN
            <foreach collection="organIds" item="organId" open="(" close=")" separator=",">
                #{organId}
            </foreach>
        </if>
        GROUP BY su.organ_id_
    </select>
    <select id="queryStudentOrganNameMap" resultType="java.util.Map">
        SELECT su.id_ 'key',o.name_ 'value' FROM sys_user su
        LEFT JOIN organization o ON o.id_ = su.organ_id_
        WHERE su.organ_id_ IS NOT NULL AND su.id_ IN
        <foreach collection="userIdList" item="userId" open="(" close=")" separator=",">
            #{userId}
        </foreach>
    </select>

    <select id="getValidVipStudentIds" resultType="java.lang.Integer">
        SELECT user_id_ FROM student WHERE member_rank_setting_id_ IS NOT NULl OR experience_member_rank_setting_id_ IS NOT NULL
    </select>
    <select id="countCourseStudentMemberNum" resultType="java.util.Map">
        SELECT cssp.course_schedule_id_ 'key',COUNT(CASE WHEN s.member_rank_setting_id_ IS NULL THEN NULL ELSE 1 END) 'value'
        FROM course_schedule_student_payment cssp
        LEFT JOIN student s ON s.user_id_ = cssp.user_id_
        WHERE cssp.course_schedule_id_ IN
        <foreach collection="courseIds" item="courseId" open="(" close=")" separator=",">
            #{courseId}
        </foreach>
        GROUP BY cssp.course_schedule_id_
    </select>
    <select id="countCourseStudentSubjectName" resultType="java.util.Map">
        SELECT cssp.course_schedule_id_ 'key',GROUP_CONCAT(DISTINCT st.name_) 'value'
        FROM course_schedule_student_payment cssp
        LEFT JOIN student s ON s.user_id_ = cssp.user_id_
        LEFT JOIN `subject` st ON st.id_ = s.subject_id_list_
        WHERE cssp.course_schedule_id_ IN
        <foreach collection="courseIds" item="courseId" open="(" close=")" separator=",">
            #{courseId}
        </foreach>
        GROUP BY cssp.course_schedule_id_
    </select>
    <select id="getStudentByHasCourse" resultType="java.lang.Integer">
        SELECT s.user_id_ FROM student s WHERE s.teacher_id_ = #{teacherId} AND s.user_id_ IN (SELECT t.user_id_ FROM (
        (SELECT sr.user_id_
        FROM student_registration sr
        LEFT JOIN music_group mg ON sr.music_group_id_=mg.id_
        WHERE mg.status_='PROGRESS'
        AND sr.music_group_status_='NORMAL')
        UNION ALL
        (SELECT
        cssp.user_id_
        FROM course_schedule_student_payment cssp
        LEFT JOIN course_schedule cs ON cssp.course_schedule_id_=cs.id_
        WHERE cssp.group_type_ IN ('VIP', 'PRACTICE')
        AND cs.status_='NOT_START'))t)
    </select>

    <select id="getStudentCooperationNameMap" resultType="java.util.Map">
        SELECT stu.user_id_ 'key',co.name_ 'value'
        FROM student stu
        LEFT JOIN cooperation_organ co ON stu.cooperation_organ_id_=co.id_
        WHERE 1=1
            AND stu.user_id_ IN
            <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                #{studentId}
            </foreach>
    </select>

    <update id="updateGrade"><![CDATA[
        UPDATE student SET current_grade_num_=current_grade_num_+1
        WHERE current_grade_num_>=1
          AND current_grade_num_<= 11
        ]]>
    </update>

    <update id="updateNewStudentsToOld">
        UPDATE student SET is_new_user_=0
        WHERE user_id_ IN
        <foreach collection="userIds" item="userId" open="(" close=")" separator=",">
            #{userId}
        </foreach>
    </update>
    <update id="cleanStudentMember">
        UPDATE student SET member_rank_setting_id_ = NULL WHERE NOW() > membership_end_time_
    </update>
    <update id="cleanExperienceStudentMember">
        UPDATE student SET experience_member_rank_setting_id_ = NULL WHERE NOW() > experience_membership_end_time_
    </update>
    <update id="cleanMember">
        UPDATE student SET member_rank_setting_id_ = NULL,membership_start_time_ = NULL,membership_end_time_ = NULL
        WHERE user_id_ = #{userId}
    </update>
    <update id="updateMemberExperience">
        UPDATE student SET
        member_rank_setting_id_ = #{rankId},membership_start_time_ = NOW(),membership_end_time_ = #{endTime},
        experience_member_rank_setting_id_ = #{rankId},experience_membership_start_time_ = NOW(),experience_membership_end_time_ = #{endTime}
        WHERE member_rank_setting_id_ IS NULL AND experience_member_rank_setting_id_ IS NULL
        AND FIND_IN_SET(user_id_,#{studentIds})
    </update>

    <update id="addStudentCloudStudySequenceDays">
        UPDATE student SET cloud_study_sequence_days_=cloud_study_sequence_days_+1,cloud_study_use_last_day_=curdate() WHERE user_id_=#{userId} AND (cloud_study_use_last_day_ IS NULL OR cloud_study_use_last_day_=date_sub(curdate(), interval 1 day))
    </update>

    <update id="updateStudentsCloudStudySequenceDays">
        UPDATE student SET cloud_study_sequence_days_=#{days} WHERE user_id_=#{userId}
    </update>

    <update id="cleanStudentCloudStudySequenceDays">
        UPDATE student SET cloud_study_sequence_days_=0,cloud_study_use_last_day_=date_sub(curdate(), interval 1 day) WHERE cloud_study_use_last_day_&lt;date_sub(curdate(), interval 1 day)
    </update>
    <update id="cleanCountFlag">
        UPDATE student SET count_flag_ = 0 WHERE count_flag_ = 1
    </update>
    <update id="remarkCountFlag">
        UPDATE student SET count_flag_ = 1 WHERE user_id_ IN (

        SELECT t.user_id_ FROM (SELECT DISTINCT sr.user_id_ FROM student_registration sr
        LEFT JOIN sys_user su  ON sr.user_id_ = su.id_
        LEFT JOIN music_group mg ON mg.id_ = sr.music_group_id_
        -- 新用户
        WHERE su.id_ NOT IN (SELECT DISTINCT(sr.`user_id_`) FROM student_registration sr
        LEFT JOIN music_group mg ON mg.id_ = sr.music_group_id_
        LEFT JOIN course_schedule cs on cs.`music_group_id_` = mg.`id_` AND cs.`group_type_` = 'MUSIC' AND cs.`status_` = 'OVER' AND cs.del_flag_ = 0
        LEFT JOIN `course_schedule_student_payment` cssp on cssp.`course_schedule_id_` = cs.`id_` AND sr.user_id_ = cssp.user_id_
        WHERE mg.`status_` = 'PROGRESS' AND sr.music_group_status_ = 'NORMAL'
        GROUP BY sr.`user_id_` HAVING COUNT(cssp.`id_`) &lt;= 4)
        -- 			非管乐
        AND su.id_ NOT IN (SELECT user_id_ FROM student WHERE subject_id_list_ REGEXP '21|25|26|27|28|29')
        -- 			声部排除
        AND su.organ_id_ NOT IN (36,38,39,41,42,43,44,45,46,47,48,49,50,52,54,55,56,63,2,27,22,24)
        -- 			购买了云教练
        AND su.id_ NOT IN (SELECT DISTINCT student_id_ FROM cloud_teacher_order WHERE active_remark_ IS NULL AND status_ != 0)
        -- 			未退团，不是会员团
        AND su.id_ NOT IN (SELECT DISTINCT sr.user_id_ FROM student_registration sr
        LEFT JOIN music_group mg ON mg.id_ = sr.music_group_id_
        WHERE sr.music_group_status_ != 'QUIT' AND mg.course_view_type_ = 2 AND mg.status_ NOT IN ('CANCELED','CLOSE'))
        -- 去掉部分非目标学员
        AND mg.id_ NOT IN ('21062318002900001','20792','21082414270900001','21060314253100001')
        -- 去掉部分非目标学员
        AND sr.user_id_ NOT IN (2127770,2127771,2127772,2127773,2127774,2127775,2127776,2127777,
                              2127778,2127779,2127780,2127781,2127782,2127783,2127784,2127785,2127786,2127787,2127788,
                              2127789,2127790,2127791,2127792,2127793,2127794,2127795,2127796,2127797,2127798,2127799,
                              2127800,2127801,2127802,2127803,2127804,2127805,2127806,2127807,2127808,2127809,2127810,
                              2127811,2127812,2127813,2127814,2127815,2127816,2127817,
                              2122083,2122084,2122085,2122088,2122090,2122092,2122399,2122567,2122577,2122584,2122847,
                              2122892,2122893,2122894,2122896,2122898,2122899,2122901,2122902,2122903,2122951,2122953,
                              2122958,2122962,2122964,2122965,2123157,2123169,2123176,2123187,2123190,2123192,2123201,
                              2123232,2123304,2125139,2125142,2125145,2125147,2125148,2125151,2125152,2125165,2125168,2125197,2125198,
                              2132340,2132341,2132342,2132343,2132344,2132345,2132347,2132348,2132349,2132350,2132351,2132352,2132353,
                              2132354,2132355,2132356,2132357,2132362,2132365,2132366,2132368,2132374,2132375,2132377,2132386,2132387,
                              2132388,2132390,2132391,2132392,2132394,2132395,2132396,2132400,2132401,2132403,2132405,2132407,2132408,
                              2132411,2132413,2132414,2132415,2132417,2132418,2132419,2132423,2132424,2132425,2132431,2132434,2132435,
                              2132436,2132437,2132438,2132440,2132441,2132443,2132444,2132445,2132446,2132447,2132448,2132449,2132452,
                              2132454,2132457,2132459,2132461,2135865)

        AND sr.music_group_status_ = 'NORMAL' AND mg.course_view_type_ != 2 AND mg.`status_` = 'PROGRESS'
        GROUP BY sr.user_id_)t)
    </update>

    <select id="queryStudent" resultMap="Student">
        SELECT s.*,su.username_,su.phone_,o.name_ organ_name_,sb.name_ subject_name_ FROM student s
        LEFT JOIN sys_user su ON su.id_ = s.user_id_
        LEFT JOIN organization o ON o.id_ = su.organ_id_
        LEFT JOIN subject sb ON sb.id_ = s.subject_id_list_
        <where>
        	su.tenant_id_ = #{tenantId}
            <if test="studentIds != null and studentIds.size > 0">
                AND s.user_id_ IN
                <foreach collection="studentIds" separator="," item="studentId" open="(" close=")">
                    #{studentId}
                </foreach>
            </if>
            <if test="subjectId != null">
                AND s.subject_id_list_ = #{subjectId}
            </if>
            <if test="search != null and search != ''">
                AND (s.user_id_ = #{search} OR su.username_ LIKE CONCAT('%',#{search},'%') OR su.phone_ LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="organId != null and organId != ''">
                AND FIND_IN_SET(su.organ_id_,#{organId})
            </if>
        </where>
        ORDER BY user_id_
        <include refid="global.limit"></include>
    </select>
    <select id="countStudent" resultType="int">
        SELECT count(s.user_id_) FROM student s
        LEFT JOIN sys_user su ON su.id_ = s.user_id_
        <where>
        	su.tenant_id_ = #{tenantId}
            <if test="studentIds != null and studentIds.size > 0">
                AND s.user_id_ IN
                <foreach collection="studentIds" separator="," item="studentId" open="(" close=")">
                    #{studentId}
                </foreach>
            </if>
            <if test="subjectId != null">
                AND s.subject_id_list_ = #{subjectId}
            </if>
            <if test="search != null and search != ''">
                AND (s.user_id_ = #{search} OR su.username_ LIKE CONCAT('%',#{search},'%') OR su.phone_ LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="organId != null and organId != ''">
                AND FIND_IN_SET(su.organ_id_,#{organId})
            </if>
        </where>
    </select>
    <select id="getUserByPhone" resultType="com.ym.mec.auth.api.entity.SysUser">
        SELECT su.id_,su.phone_,su.username_,su.birthdate_,su.gender_,su.user_type_,su.tenant_id_
        FROM sys_user su WHERE su.phone_ = #{mobile} LIMIT 1
    </select>

    <resultMap id="SysUserDto" type="com.ym.mec.biz.dal.dto.SysUserDto">
        <result property="userId" column="user_id_"/>
        <result property="username" column="username_"/>
        <result property="phone" column="phone_"/>
        <result property="organName" column="organ_name_"/>
        <result property="subjectName" column="subject_name_"/>
    </resultMap>
    <select id="countStudentBasicInfo" resultType="java.lang.Integer">
        SELECT COUNT(s.user_id_) FROM student s
        LEFT JOIN sys_user su ON su.id_ = s.user_id_
        <if test="musicGroupId != null and musicGroupId != ''">
            LEFT JOIN student_registration sr ON sr.user_id_ = s.user_id_
        </if>
        <include refid="queryStudentBasicInfoSql"/>
    </select>
    <select id="queryStudentBasicInfo" resultMap="SysUserDto">
        SELECT s.user_id_,su.username_,su.phone_,o.name_ organ_name_,sb.name_ subject_name_ FROM student s
        LEFT JOIN sys_user su ON su.id_ = s.user_id_
        LEFT JOIN organization o ON o.id_ = su.organ_id_
        LEFT JOIN `subject` sb ON sb.id_ = s.subject_id_list_
        <if test="musicGroupId != null and musicGroupId != ''">
            LEFT JOIN student_registration sr ON sr.user_id_ = s.user_id_
        </if>
        <include refid="queryStudentBasicInfoSql"/>
        <include refid="global.limit"/>
    </select>
    <select id="queryStuSubjectId" resultType="com.ym.mec.biz.dal.dto.BaseMapDto">
        select sb.id_ 'key',sb.name_ 'value' from student s
        LEFT JOIN sys_user su ON su.id_ = s.user_id_
        LEFT JOIN subject sb ON sb.id_ = s.subject_id_list_
        <where>
            s.subject_id_list_ IS NOT NULL
            <if test="organIds != null and organIds != ''">
                AND FIND_IN_SET(su.organ_id_,#{organIds})
            </if>
        </where>
        GROUP BY sb.id_
    </select>
    <select id="queryStuSubjectIdByTeacherId" resultType="com.ym.mec.biz.dal.dto.BaseMapDto">
        select sb.id_ 'key',sb.name_ 'value' from student s
        LEFT JOIN subject sb ON sb.id_ = s.subject_id_list_
        WHERE s.teacher_id_ = #{userId} AND s.subject_id_list_ IS NOT NULL AND s.subject_id_list_ != ''
        GROUP BY sb.id_
    </select>
    <sql id="queryStudentBasicInfoSql">
        <where>
            AND su.lock_flag_ = 0 AND su.del_flag_ = 0
            <if test="search != null and search != ''">
                AND (s.user_id_ = #{search} OR su.username_ LIKE CONCAT('%',#{search},'%') OR su.phone_ LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="organId != null and organId != ''">
                AND FIND_IN_SET(su.organ_id_,#{organId})
            </if>
            <if test="subjectId != null">
                AND s.subject_id_list_ = #{subjectId}
            </if>
            <if test="musicGroupId != null and musicGroupId != ''">
                AND sr.music_group_id_ = #{musicGroupId}
            </if>
            <if test="imGroupId != null and imGroupId != ''">
                AND s.user_id_ NOT IN (SELECT user_id_ FROM im_group_member WHERE im_group_id_ = #{imGroupId})
            </if>
        </where>
    </sql>
</mapper>
