<?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.PracticeGroupDao">

    <resultMap type="com.ym.mec.biz.dal.entity.PracticeGroup" id="PracticeGroup">
        <result column="id_" property="id"/>
        <result column="name_" property="name"/>
        <result column="type_" property="type"
                typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="subject_id_" property="subjectId"/>
        <result column="user_id_" property="userId"/>
        <result column="student_id_" property="studentId"/>
        <result column="single_class_minutes_" property="singleClassMinutes"/>
        <result column="organ_id_" property="organId"/>
        <result column="courses_start_date_" property="coursesStartDate"/>
        <result column="courses_expire_date_" property="coursesExpireDate"/>
        <result column="create_time_" property="createTime"/>
        <result column="update_time_" property="updateTime"/>
        <result column="tenant_id_" property="tenantId"/>
        <result column="memo_" property="memo"/>
        <result column="buy_months_" property="buyMonths"/>
        <result column="drill_times_on_week_" property="drillTimesOnWeek"/>
        <result column="drill_times_json_" property="drillTimesJson"/>
        <result column="group_status_" property="groupStatus"
                typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="be_renew_group_id_" property="beRenewGroupId"/>
        <result column="educational_teacher_id_" property="educationalTeacherId"/>
        <result column="course_schedule_json_" property="courseScheduleJson"/>
        <result column="payment_expire_date_" property="paymentExpireDate"/>
        <result column="registration_start_time_" property="registrationStartTime"/>
        <result column="course_num_" property="allCourseNum"/>
        <result column="total_price_" property="totalPrice"/>
        <result column="activity_user_mapper_id_" property="activityUserMapperId"/>
        <result column="vip_group_activity_id_" property="vipGroupActivityId"/>
        <result column="tenant_id_" property="tenantId"/>
    </resultMap>

    <resultMap id="PracticeCourseDto" type="com.ym.mec.biz.dal.dto.PracticeCourseDto" extends="PracticeGroup">
        <result property="teacherName" column="real_name_"/>
        <result property="avatar" column="avatar_"/>
        <result property="subjectName" column="subject_name_"/>
        <result property="eduTeacherName" column="edu_teacher_name_"/>
    </resultMap>

    <resultMap type="com.ym.mec.biz.dal.dto.PracticeGroupDto" id="PracticeGroupDto" extends="PracticeGroup">
        <result column="id_" property="id"/>
        <result column="name_" property="name"/>
        <result column="subject_id_" property="subjectId"/>
        <result column="user_id_" property="userId"/>
        <result column="single_class_minutes_" property="singleClassMinutes"/>
        <result column="organ_id_" property="organId"/>
        <result column="courses_start_date_" property="coursesStartDate"/>
        <result column="courses_start_dates_" property="coursesStartDates"/>
        <result column="courses_expire_date_" property="coursesExpireDate"/>
        <result column="create_time_" property="createTime"/>
        <result column="update_time_" property="updateTime"/>
        <result column="memo_" property="memo"/>
        <result column="subject_name_" property="subjectName"/>
        <result column="teacher_name_" property="teacherName"/>
        <result column="evaluate_id_" property="evaluateId"/>
        <result column="evaluate_status_" property="evaluateStatus"/>
        <result column="hasRestClass" property="hasRestClass"/>
    </resultMap>
    <update id="updateUserId">
        UPDATE practice_group
        SET user_id_     = #{teacherId},
            update_time_ = NOW()
        WHERE id_ = #{practiceGroupId}
    </update>

    <update id="update" parameterType="com.ym.mec.biz.dal.entity.PracticeGroup">
        UPDATE practice_group
        <set>
            <if test="vipGroupActivityId != null">
                vip_group_activity_id_ = #{vipGroupActivityId},
            </if>
            <if test="tenantId != null">
                tenant_id_ = #{tenantId},
            </if>
            <if test="activityUserMapperId != null">
                activity_user_mapper_id_ = #{activityUserMapperId},
            </if>
            <if test="totalPrice != null">
                total_price_ = #{totalPrice},
            </if>
            <if test="paymentExpireDate != null">
                payment_expire_date_ = #{paymentExpireDate},
            </if>
            <if test="registrationStartTime != null">
                registration_start_time_ = #{registrationStartTime},
            </if>
            <if test="allCourseNum != null">
                course_num_ = #{allCourseNum},
            </if>
            <if test="courseScheduleJson != null">
                course_schedule_json_ = #{courseScheduleJson},
            </if>
            <if test="subjectId!=null">
                subject_id_=#{subjectId},
            </if>
            <if test="memo!=null">
                memo_=#{memo},
            </if>
            <if test="userId != null">
                user_id_ = #{userId},
            </if>
            <if test="name!=null">
                name_=#{name},
            </if>
            <if test="coursesStartDate != null">
                courses_start_date_=#{coursesStartDate},
            </if>
            <if test="coursesExpireDate != null">
                courses_expire_date_ = #{coursesExpireDate},
            </if>
            <if test="groupStatus!=null">
                group_status_=#{groupStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
            </if>
            <if test="type!=null">
                type_ =#{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
            </if>
            <if test="educationalTeacherId!=null">
                educational_teacher_id_=#{educationalTeacherId},
            </if>
            update_time_ = NOW()
        </set>
        WHERE id_ = #{id} and tenant_id_ = #{tenantId}
    </update>

    <update id="batchUpdate">
        <foreach collection="groups" item="group" separator=";">
            UPDATE practice_group
            <set>
                <if test="group.groupStatus!=null">
                    group_status_=#{group.groupStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
                </if>
                update_time_ = NOW()
            </set>
            WHERE id_ = #{group.id}
        </foreach>
    </update>
    <update id="updateMemo">
        UPDATE practice_group SET memo_ = #{memo},update_time_ = NOW() WHERE id_ = #{groupId}
    </update>
    <update id="batchUpdatePracticeRemindStatus">
        UPDATE practice_group SET reminded=#{remindStatus} WHERE id_ IN
        <foreach collection="practiceIds" item="practiceId" separator="," open="(" close=")">
            #{practiceId}
        </foreach>
    </update>

    <!-- 根据主键查询一条记录 -->
    <select id="get" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE id_ = #{id}
    </select>

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

    <!-- 向数据库增加一条记录 -->
    <insert id="insert" parameterType="com.ym.mec.biz.dal.entity.PracticeGroup" useGeneratedKeys="true" keyColumn="id"
            keyProperty="id">
        INSERT INTO practice_group
        (name_,type_,subject_id_,user_id_,student_id_,single_class_minutes_,
         organ_id_,courses_start_date_,courses_expire_date_,create_time_,update_time_,
         memo_,buy_months_,drill_times_on_week_,drill_times_json_,group_status_,
         be_renew_group_id_,educational_teacher_id_,payment_expire_date_,registration_start_time_,
         course_num_,total_price_,activity_user_mapper_id_,vip_group_activity_id_,tenant_id_)
        VALUES(#{name},#{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
               #{subjectId},#{userId},#{studentId},#{singleClassMinutes},#{organId},#{coursesStartDate},
               #{coursesExpireDate},NOW(),NOW(),#{memo},#{buyMonths},#{drillTimesOnWeek},#{drillTimesJson},
               #{groupStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{beRenewGroupId},
               #{educationalTeacherId},#{paymentExpireDate},#{registrationStartTime},#{allCourseNum},
               #{totalPrice},#{activityUserMapperId},#{vipGroupActivityId},#{tenantId})
    </insert>

    <select id="getUserFreePracticeGroup" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE student_id_ = #{userId}
          AND type_='FREE'
    </select>

    <!-- 分页查询 -->
    <select id="queryPage" resultMap="PracticeGroup" parameterType="map">
        SELECT * FROM practice_group where tenant_id_ = #{tenantId}
        <include refid="global.limit"/>
    </select>

    <!-- 查询当前表的总记录数 -->
    <select id="queryCount" resultType="int">
        SELECT COUNT(*)
        FROM practice_group where tenant_id_ = #{tenantId}
    </select>
    <select id="getUserPracticeCoursesWithDateRange" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE user_id_ = #{userId}
          AND (courses_start_date_ BETWEEN DATE_FORMAT(#{startDate}, '%Y-%m-%d') AND DATE_FORMAT(#{endDate}, '%Y-%m-%d'))
    </select>
    <select id="countUserPracticeApplyRecord" resultType="int">
        SELECT COUNT(*)
        FROM practice_group
        WHERE student_id_ = #{userId}
          AND group_status_ IN ('NORMAL', 'FINISH')
          AND type_='FREE'
    </select>
    <select id="countPracticeGroupByOrgan" resultType="java.lang.Integer">
        SELECT count(*) FROM practice_group pg
        <include refid="practiceGroupQueryCondition"/>
    </select>
    <select id="findAllByOrgan" resultMap="PracticeGroupDto">
        SELECT pg.*,
        su.real_name_ teacher_name_
        FROM
        practice_group pg
        LEFT JOIN sys_user su ON pg.user_id_ = su.id_
        <include refid="practiceGroupQueryCondition"/>
        GROUP BY pg.id_ ORDER BY pg.id_ DESC
        <include refid="global.limit"/>
    </select>

    <select id="findUserLatestPracticeGroup" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE student_id_ = #{userId}
          AND type_='CHARGE'
        ORDER BY create_time_ DESC
        LIMIT 1;
    </select>

    <select id="findUserBuyPracticeGroups" resultMap="PracticeCourseDto">
        SELECT pg.*,
               su.real_name_,
               su.avatar_,
               s.name_ subject_name_
        FROM practice_group pg
                 LEFT JOIN sys_user su ON pg.user_id_ = su.id_
                 LEFT JOIN `subject` s ON pg.subject_id_ = s.id_
        WHERE student_id_ = #{userId}
          AND (pg.group_status_ = 'LOCK')
          <if test="type!=null">
              AND pg.type_=#{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
          </if>
          <if test="type==null">
              AND pg.type_='CHARGE'
          </if>
    </select>

    <select id="findUserBuyPracticeGroupsWithDate" resultMap="PracticeCourseDto">
        SELECT pg.*,
               su.real_name_,
               su.avatar_,
               s.name_ subject_name_
        FROM practice_group pg
                 LEFT JOIN sys_user su ON pg.user_id_ = su.id_
                 LEFT JOIN `subject` s ON pg.subject_id_ = s.id_
        WHERE student_id_ = #{userId}
          AND courses_start_date_ = #{date}
          AND group_status_ = 'LOCK'
          AND pg.type_='CHARGE'
    </select>
    <select id="findUserPracticeGroup" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE student_id_ = #{userId}
          AND id_ = #{groupId};
    </select>
    <select id="findUserPracticeGroup2" resultMap="PracticeGroupDto">
        SELECT pg.*, su.real_name_ teacher_name_
        FROM practice_group pg
                 LEFT JOIN sys_user su ON pg.user_id_ = su.id_
        WHERE pg.student_id_ = #{userId}
          AND pg.id_ = #{groupId};
    </select>
    <select id="findHistoryPracticeGroups" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE courses_expire_date_ &lt; NOW()
          AND group_status_ = 'NORMAL'
    </select>

    <sql id="practiceGroupQueryCondition">
        <where>
        	pg.tenant_id_ = #{tenantId}
            <if test="hasEducationalTeacherId != null and hasEducationalTeacherId == true">
                AND pg.educational_teacher_id_ IS NOT NULL
            </if>
            <if test="hasEducationalTeacherId != null and hasEducationalTeacherId == false">
                AND pg.educational_teacher_id_ IS NULL
            </if>
            <if test="search!=null and search!=''">
                AND (pg.name_ LIKE CONCAT('%',#{search},'%') OR pg.id_= #{search})
            </if>
            <if test="teacherId != null">
                AND pg.user_id_=#{teacherId}
            </if>
            <if test="tenantId != null">
                AND pg.tenant_id_ = #{tenantId}
            </if>
            <if test="studentId != null">
                AND pg.student_id_ = #{studentId}
            </if>
            <if test="groupStatus != null and groupStatus != ''">
                AND pg.group_status_ = #{groupStatus}
            </if>
            <if test="organId != null">
                AND FIND_IN_SET(pg.organ_id_,#{organId})
            </if>
            <if test="educationalTeacherId!=null">
                AND pg.educational_teacher_id_=#{educationalTeacherId}
            </if>
            <if test="type != null and type == 1">
                AND pg.be_renew_group_id_ IS NULL AND pg.type_='CHARGE'
            </if>
            <if test="type != null and type == 0">
                AND pg.be_renew_group_id_ IS NOT NULL AND pg.type_='CHARGE'
            </if>
            <if test="type != null and type == 2">
                AND pg.type_='FREE'
            </if>
            <if test="practiceGroupType != null">
                AND pg.type_=#{practiceGroupType, typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
            </if>
        </where>
    </sql>

    <!-- 根据主键查询一条记录 -->
    <select id="lockPracticeGroup" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE id_ = #{groupId} FOR
        UPDATE
    </select>
    <select id="findUserStatusPracticeGroups" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE student_id_ = #{userId}
          <if test="groupStatus!=null">
              AND group_status_ = #{groupStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
          </if>
          <if test="groupType!=null">
              AND type_ = #{groupType, typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
          </if>
    </select>
    <select id="findUserLockPracticeGroupWithDate" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE student_id_ = #{userId}
          AND courses_start_date_ = #{date}
          AND group_status_ = 'LOCK'
    </select>
    <select id="findUserLockPracticeGroupWithDateBefore" resultMap="PracticeGroup">
        SELECT *
        FROM practice_group
        WHERE student_id_ = #{userId}
          AND courses_start_date_ &lt;= #{date}
          AND group_status_ = 'LOCK'
    </select>

    <sql id="practiceGroupReviewsQueryCondition">
        <where>
            pg.group_status_ != 'LOCK'
            AND pg.tenant_id_ = #{tenantId}
            <if test="month != null">
                AND DATE_FORMAT(cse.create_time_, '%Y-%m') = #{month}
            </if>
            <if test="search!=null and search!=''">
                AND (pg.name_ LIKE CONCAT('%',#{search},'%') OR pg.id_= #{search})
            </if>
            <if test="teacherId!=null">
                AND pg.user_id_=#{teacherId}
            </if>
            <if test="organId != null">
                AND FIND_IN_SET(pg.organ_id_,#{organId})
            </if>
            <if test="month != null">
                AND pg.courses_expire_date_ >= #{month}
            </if>
            <if test='isFree !=null and isFree=="0"'>
                AND pg.type_='CHARGE'
            </if>
            <if test='isFree !=null and isFree=="1"'>
                AND pg.type_='FREE'
            </if>
            <if test='isOver !=null and isOver=="0"'>
                <![CDATA[AND pg.group_status_ = 'NORMAL'
			]]>
            </if>
            <if test='isOver !=null and isOver=="1"'>
                <![CDATA[ AND pg.group_status_ ='FINISH'
			]]></if>
            <if test='hasReport !=null and hasReport=="0"'>
                <![CDATA[AND cse.status_ =0
			]]>
            </if>
            <if test='hasReport !=null and hasReport=="1"'>
                <![CDATA[ AND cse.status_ = 1
			]]></if>
        </where>
    </sql>

    <select id="findPracticeGroupsReviews" resultMap="PracticeGroupDto">
        SELECT pg.*,cse.id_ evaluate_id_,cse.status_ evaluate_status_,
        su.real_name_ teacher_name_
        FROM
        practice_group pg
        LEFT JOIN sys_user su ON pg.user_id_ = su.id_
        LEFT JOIN course_schedule_evaluate cse ON pg.id_=cse.music_group_id_
        <include refid="practiceGroupReviewsQueryCondition"/>
        ORDER BY pg.id_ DESC
        <include refid="global.limit"/>
    </select>


    <select id="countPracticeGroupReviews" resultType="java.lang.Integer">
        SELECT count(*) FROM practice_group pg
        LEFT JOIN course_schedule_evaluate cse ON pg.id_=cse.music_group_id_
        <include refid="practiceGroupReviewsQueryCondition"/>
    </select>

    <select id="getNeedPostReportPracticeGroups"
            resultMap="com.ym.mec.biz.dal.dao.CourseScheduleEvaluateDao.CourseScheduleEvaluate">
        <![CDATA[
        SELECT pg.id_                   music_group_id_,
               pg.user_id_              teacher_id_,
               cg.id_                   class_group_id_,
               pg.single_class_minutes_ total_minutes_,
               pg.subject_id_,pg.tenant_id_
        FROM practice_group pg
                 LEFT JOIN class_group cg on pg.id_ = cg.music_group_id_ AND cg.group_type_ = 'PRACTICE'
         WHERE pg.group_status_ IN ('NORMAL','FINISH') AND cg.group_type_ = 'PRACTICE'
          AND pg.buy_months_ >= 1
          AND pg.courses_start_date_ <= #{nowDate,jdbcType=DATE}
          AND pg.courses_expire_date_ >= #{afterDate,jdbcType=DATE}
        ]]>
        <if test="afterDateIsLastDay == false">
            AND DATE_FORMAT(pg.courses_expire_date_, '%d') = DATE_FORMAT(#{afterDate}, '%d')
        </if>
        <if test="afterDateIsLastDay == true">
            <![CDATA[ AND DATE_FORMAT(pg.courses_expire_date_, '%d') >= DATE_FORMAT(#{afterDate}, '%d') ]]>
        </if>
        AND cg.del_flag_ = 0
    </select>

    <select id="getReportCourseTimes" resultMap="com.ym.mec.biz.dal.dao.ClassGroupDao.ClassGroup">
        SELECT COUNT(*) total_class_times_,class_group_id_ id_ from course_schedule WHERE class_group_id_ IN
        <foreach collection="classGroupIds" item="classGroupId" open="(" separator="," close=")">
            #{classGroupId}
        </foreach>
        <![CDATA[AND class_date_ >= #{startDate,jdbcType=DATE} AND class_date_ <=#{endDate,jdbcType=DATE} ]]>
        AND (del_flag_ =0 OR del_flag_ IS NULL)
        GROUP BY class_group_id_
    </select>

    <select id="findByGroupId" resultMap="PracticeCourseDto">
        SELECT pg.*, s.name_ subject_name_, su.real_name_ edu_teacher_name_
        FROM practice_group pg
                 LEFT JOIN subject s on pg.subject_id_ = s.id_
                 LEFT JOIN sys_user su on pg.educational_teacher_id_ = su.id_
        WHERE pg.id_ = #{id}
    </select>

    <select id="countStudentBuys" resultType="java.lang.Integer">
        SELECT COUNT(a.student_id_) FROM
        (SELECT DISTINCT(pg.`student_id_`),pg.`organ_id_` FROM `practice_group` pg WHERE pg.`group_status_` in
        ('NORMAL','FINISH')) a
        LEFT JOIN (SELECT pg.`student_id_` ,max(concat(cs.`class_date_`,' ',cs.`end_class_time_` )) lastClassDate FROM
        `practice_group` pg
        LEFT JOIN `course_schedule` cs on cs.`music_group_id_` = pg.`id_` and cs.`group_type_` = 'PRACTICE'
        WHERE pg.type_='FREE' AND cs.`group_type_` = 'PRACTICE'
        GROUP BY pg.`student_id_` ) b on a.student_id_ = b.student_id_
        left join (SELECT pg.`student_id_` ,min(pg.`create_time_`) firstBuyTime
        FROM `practice_group` pg WHERE pg.type_='CHARGE' AND pg.`group_status_` in ('NORMAL','FINISH') GROUP
        BY pg.`student_id_` ) c
        on a.student_id_ = c.student_id_
        left join `sys_user` u on u.`id_` = a.student_id_
        left join `organization` o on o.`id_` = a.organ_id_
        <include refid="queryStudentBuysSql"/>
    </select>
    <resultMap id="queryStudentBuysMap" type="com.ym.mec.biz.dal.dto.StudentBuyPracticeDto">
        <result property="organName" column="organ_name_"/>
        <result property="phone" column="phone_"/>
        <result property="studentId" column="student_id_"/>
        <result property="studentName" column="student_name_"/>
        <result property="teacherName" column="teacher_name_"/>
        <result property="courseGroupTeacherName" column="course_group_teacher_"/>
        <result property="firstBuyTime" column="first_buy_time_"/>
        <result property="intervalDay" column="interval_day_"/>
        <result property="lastClassDate" column="last_class_date_"/>
        <result property="buyPractice" column="buy_practice_"
                typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
    </resultMap>
    <select id="queryStudentBuys" resultMap="queryStudentBuysMap">
        SELECT o.`name_` organ_name_,a.student_id_,u.`username_` student_name_,u.phone_,
        b.lastClassDate last_class_date_,c.firstBuyTime first_buy_time_,
        CASE WHEN DATEDIFF(c.firstBuyTime,b.lastClassDate) &lt; 0 THEN 0 ELSE DATEDIFF(c.firstBuyTime,b.lastClassDate)
        END interval_day_,
        CASE WHEN c.firstBuyTime IS NULL THEN 0 ELSE 1 END buy_practice_,d.teacher_name_,d.course_group_teacher_
        FROM
        (SELECT DISTINCT(pg.`student_id_`),pg.`organ_id_` FROM `practice_group` pg WHERE pg.`group_status_` in
        ('NORMAL','FINISH')) a
        LEFT JOIN (SELECT pg.`student_id_` ,max(concat(cs.`class_date_`,' ',cs.`end_class_time_` )) lastClassDate FROM
        `practice_group` pg
        LEFT JOIN `course_schedule` cs on cs.`music_group_id_` = pg.`id_`
        WHERE pg.type_='FREE' AND cs.`group_type_` = 'PRACTICE'
        GROUP BY pg.`student_id_` ) b on a.student_id_ = b.student_id_
        left join (SELECT pg.`student_id_` ,min(pg.`create_time_`) firstBuyTime
        FROM `practice_group` pg
        WHERE pg.type_='CHARGE' AND pg.`group_status_` IN ('NORMAL','FINISH') GROUP
        BY pg.`student_id_` ) c ON a.student_id_ = c.student_id_
        LEFT JOIN (SELECT GROUP_CONCAT(DISTINCT su.real_name_) teacher_name_,pg.student_id_,GROUP_CONCAT(DISTINCT suc.real_name_) course_group_teacher_
        FROM `practice_group` pg
        LEFT JOIN `course_schedule` cs ON cs.`music_group_id_` = pg.`id_`
        LEFT JOIN sys_user su ON su.id_ = cs.actual_teacher_id_
        LEFT JOIN sys_user suc ON suc.id_ = pg.user_id_
        WHERE cs.`group_type_` = 'PRACTICE' AND pg.`group_status_` IN ('NORMAL','FINISH') GROUP BY pg.`student_id_` ) d ON a.student_id_ = d.student_id_
        LEFT JOIN `sys_user` u ON u.`id_` = a.student_id_
        LEFT JOIN `organization` o ON o.`id_` = a.organ_id_
        <include refid="queryStudentBuysSql"/>
        <include refid="global.limit"/>
    </select>
    <sql id="queryStudentBuysSql">
        <where>
        	u.tenant_id_ = #{tenantId}
            <if test="search != null and search != ''">
                AND (u.id_ = #{search} OR u.`username_` LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="buyPractice != null and buyPractice == false">
                AND c.firstBuyTime IS NULL
            </if>
            <if test="buyPractice != null and buyPractice == true">
                AND c.firstBuyTime IS NOT NULL
            </if>
            <if test="organId != null">
                AND FIND_IN_SET(a.organ_id_,#{organId})
            </if>
        </where>
    </sql>

    <resultMap id="courseGroupExport" type="com.ym.mec.biz.dal.dto.CourseGroupExportDto">
        <result column="organ_name_" property="organName"/>
        <result column="student_id_" property="studentId"/>
        <result column="student_name_" property="studentName"/>
        <result column="teacher_id_" property="teacherId"/>
        <result column="teacher_ids_" property="teacherIds"/>
        <result column="teacher_name_" property="teacherName"/>
        <result column="edu_teacher_ids_" property="eduTeacherIds"/>
        <result column="edu_teacher_name_" property="eduTeacherName"/>
        <result column="expire_date_" property="expireDate"/>
        <result column="class_start_date_" property="classStartDate"/>
        <result column="class_end_date_" property="classEndDate"/>
        <result column="total_class_times_" property="totalClassTimes"/>
        <result column="no_start_class_times_" property="noStartClassTimes"/>
        <result column="buy_practice_" property="buyPractice" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
    </resultMap>
    <select id="getPracticeGroupExport" resultMap="courseGroupExport">
        SELECT pg.student_id_,
        su.username_ student_name_,
        o.name_ organ_name_,
        MAX(pg.courses_expire_date_) expire_date_,
        CASE WHEN MAX(pg.buy_months_) IS NULL THEN 0 ELSE 1 END buy_practice_,
        GROUP_CONCAT(DISTINCT edut.`real_name_`) edu_teacher_name_,
        GROUP_CONCAT(DISTINCT edut.`id_`) edu_teacher_ids_
        FROM practice_group pg
        LEFT JOIN organization o on o.id_ = pg.organ_id_
        LEFT JOIN sys_user su ON su.id_ = pg.student_id_
        left join sys_user edut ON edut.id_ = pg.educational_teacher_id_
        WHERE pg.group_status_ IN ('NORMAL','FINISH') and pg.tenant_id_ = #{tenantId}
        <if test="organIds != null and organIds != ''">
            AND FIND_IN_SET(pg.organ_id_, #{organIds})
        </if>
        GROUP BY pg.student_id_,o.id_
    </select>

    <select id="findConvertDefeatStudents" resultType="com.ym.mec.biz.dal.dto.SimpleUserDto">
        SELECT
            DISTINCT 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="organIdList!=null">
                AND su.organ_id_ IN
                <foreach collection="organIdList" 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="countConvertDefeatStudents" resultType="int">
        SELECT
            COUNT(DISTINCT 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="organIdList!=null">
            AND su.organ_id_ IN
                <foreach collection="organIdList" 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="findEnableAssignTeachers" resultType="com.ym.mec.biz.dal.dto.SimpleUserDto">
        SELECT su.id_ userId,su.real_name_ userName,su.avatar_ avatar
        FROM teacher t
          LEFT JOIN sys_user su ON t.id_=su.id_
        WHERE
            FIND_IN_SET(#{subjectId}, t.subject_id_)
            AND su.del_flag_=0 AND su.lock_flag_=0
            AND t.is_support_extra_practice_lesson_=1
            AND (t.organ_id_ = #{studentOrganId} OR FIND_IN_SET(#{studentOrganId},t.flow_organ_range_))
            AND NOT EXISTS (SELECT
                cs.actual_teacher_id_
            FROM
                course_schedule_student_payment cssp
                LEFT JOIN course_schedule cs ON cs.id_ = cssp.course_schedule_id_
		        LEFT JOIN practice_group pg ON cssp.music_group_id_=pg.id_
            WHERE
                cssp.user_id_ = #{studentId}
                AND cs.actual_teacher_id_ = t.id_
		        AND pg.type_='TRIAL'
                AND cssp.group_type_ = 'PRACTICE')
    </select>

    <select id="findLastPracticeSubject" resultType="int">
        SELECT pg.subject_id_ FROM course_schedule_student_payment cssp LEFT JOIN course_schedule cs ON cs.id_=cssp.course_schedule_id_
        LEFT JOIN practice_group pg ON cssp.music_group_id_=pg.id_
        WHERE cssp.group_type_='PRACTICE' AND cssp.user_id_=#{studentId} ORDER BY CONCAT(cs.class_date_, ' ', cs.start_class_time_) DESC LIMIT 1
    </select>

    <select id="findStudentTrialPractices" resultMap="PracticeGroupDto">
        SELECT
            pg.id_,
            pg.name_,
            pg.user_id_,
            su.real_name_ teacher_name_,
            GROUP_CONCAT(CONCAT(cs.class_date_, ' ', cs.start_class_time_) ORDER BY CONCAT( cs.class_date_, ' ', cs.start_class_time_ )) courses_start_dates_,
            pg.memo_
        FROM
            practice_group pg
            LEFT JOIN course_schedule cs ON cs.music_group_id_ = pg.id_
            LEFT JOIN sys_user su ON su.id_=pg.user_id_
        WHERE
            pg.student_id_ = #{studentId}
            AND cs.group_type_ = 'PRACTICE'
            AND pg.type_ = 'TRIAL'
        GROUP BY pg.id_
        ORDER BY pg.id_
    </select>
    <select id="countStudentTrialPractices" resultType="int">
        SELECT
            COUNT( DISTINCT pg.id_ )
        FROM
            course_schedule cs
            LEFT JOIN practice_group pg ON pg.id_ = cs.music_group_id_
        WHERE
            pg.student_id_ = #{studentId}
            AND cs.group_type_ = 'PRACTICE'
            AND pg.type_ = 'TRIAL'
    </select>
    <select id="findStudentAndTeacherTrialPractices" resultMap="com.ym.mec.biz.dal.dao.CourseScheduleDao.CourseSchedule">
        SELECT
            cs.id_,
            cs.music_group_id_,
            cs.group_type_,
            cs.class_group_id_,
            cs.status_,
            cs.subsidy_,
            cs.class_date_,
            CONCAT(cs.class_date_, ' ', cs.start_class_time_) start_class_time_,
            CONCAT(cs.class_date_, ' ', cs.end_class_time_)   end_class_time_,
            cs.teacher_id_,
            cs.actual_teacher_id_,
            cs.create_time_,
            cs.update_time_,
            cs.teach_mode_,
            cs.type_,
            cs.name_,
            cs.student_num_,
            cs.leave_student_num_,
            cs.teaching_content_,
            cs.note_,
            cs.schoole_id_
        FROM
            practice_group pg
            LEFT JOIN course_schedule cs ON cs.music_group_id_ = pg.id_
        WHERE
            pg.type_ = 'TRIAL'
            AND pg.user_id_ = #{teacherId}
            AND pg.student_id_ = #{studentId}
            AND cs.group_type_ = 'PRACTICE'
    </select>

    <select id="countStudentAndTeacherTrialPractices" resultType="int">
        SELECT COUNT(pg.id_)
        FROM course_schedule cs
            LEFT JOIN practice_group pg ON cs.music_group_id_=pg.id_
        WHERE
            pg.type_ = 'TRIAL'
            AND cs.actual_teacher_id_ = #{teacherId}
            AND pg.student_id_ = #{studentId}
    </select>

    <select id="checkStudentExitChargePractice" resultType="int">
        SELECT COUNT(id_) FROM practice_group WHERE type_='CHARGE' AND student_id_=#{studentId} AND group_status_ IN ('NORMAL', 'FINISH')
        <if test="startTime!=null and startTime!=''">
            AND create_time_>#{startTime}
        </if>
    </select>

    <select id="countStudentIngTrialPractices" resultType="int">
      SELECT COUNT(pg.id_) FROM practice_group pg LEFT JOIN course_schedule cs ON cs.music_group_id_=pg.id_
      WHERE pg.student_id_=#{studentId} AND pg.type_='TRIAL' AND cs.group_type_='PRACTICE' AND CONCAT(cs.class_date_, ' ', cs.end_class_time_)>NOW()
    </select>

    <select id="getNeedRemindPracticeUsers" resultType="int">
        SELECT pg.student_id_ FROM practice_group pg
        LEFT JOIN course_schedule cs ON cs.music_group_id_=pg.id_
        WHERE pg.group_status_='NORMAL' AND cs.group_type_='PRACTICE' AND CONCAT(class_date_, ' ', end_class_time_)>NOW()
        GROUP BY pg.student_id_ HAVING COUNT(cs.id_)=1;
    </select>

    <select id="getUserNeedRemindPracticeIdMap" resultType="map">
        SELECT cssp.user_id_ AS 'key', CONCAT(pg.type_, '-', cssp.music_group_id_) AS 'value'
        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_=cssp.music_group_id_
        WHERE pg.reminded=0 AND cs.group_type_='PRACTICE' AND CONCAT(class_date_, ' ', end_class_time_)>NOW()
            AND cssp.user_id_ IN
            <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
                #{studentId}
            </foreach>
    </select>

    <select id="getPracticeGroupByIds" resultMap="PracticeCourseDto">
        SELECT pg.id_,pg.type_,t.real_name_,et.real_name_ edu_teacher_name_ FROM practice_group pg
        LEFT JOIN sys_user t ON pg.user_id_ = t.id_
        LEFT JOIN sys_user et ON et.id_ = pg.educational_teacher_id_
        WHERE pg.id_ IN
        <foreach collection="practiceIds" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

    <select id="getWithIds" resultMap="PracticeGroup">
        SELECT * FROM practice_group
        WHERE id_ IN
        <foreach collection="practiceIds" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

    <select id="getPracticeGroupType" resultType="map">
        SELECT id_ AS 'key', type_ AS 'value' FROM practice_group
        WHERE id_ IN
        <foreach collection="practiceIds" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

    <select id="queryEduNameMapByCourseId" resultType="java.util.Map">
        SELECT cs.id_ 'key',su.real_name_ 'value' FROM course_schedule cs
        LEFT JOIN practice_group pg ON pg.id_ = cs.music_group_id_
        LEFT JOIN sys_user su ON su.id_ = pg.educational_teacher_id_
        WHERE cs.id_ IN
        <foreach collection="courseIds" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        AND pg.educational_teacher_id_ IS NOT NULL
    </select>

    <select id="getStudentEduTeacher" resultType="string">
        SELECT edut.real_name_
        FROM practice_group pg
        LEFT JOIN sys_user edut ON edut.id_ = pg.educational_teacher_id_
        WHERE pg.student_id_ = #{studentId}
            AND pg.group_status_ IN ('NORMAL','FINISH')
        ORDER BY pg.courses_start_date_ DESC LIMIT 1
    </select>
    <select id="countStudentUserActivityNum" resultType="java.lang.Integer">
        SELECT COUNT(DISTINCT pg.id_)
        FROM practice_group pg
        LEFT JOIN class_group_student_mapper cgsm ON pg.id_ = cgsm.music_group_id_ AND cgsm.group_type_='PRACTICE'
        WHERE pg.vip_group_activity_id_ = #{vipGroupActivityId}
        AND ((pg.group_status_ NOT IN ('CANCEL') AND #{studentId} = pg.student_id_) OR cgsm.user_id_=#{studentId})
    </select>
    <select id="countUserRepeatPracticeGroupInCourseStartEndTime" resultType="java.lang.Integer">
        SELECT COUNT(id_)
        FROM practice_group
        WHERE student_id_ = #{userId} AND courses_start_date_ = #{courseStartDate} AND courses_expire_date_ = #{courseEndDate}
    </select>
    <select id="findPracticeGroups" resultMap="com.ym.mec.biz.dal.dao.VipGroupDao.studentVipGroup">
        SELECT pg.id_,pg.name_,pg.single_class_minutes_,pg.payment_expire_date_,pg.courses_expire_date_,
        pg.courses_start_date_ courses_start_date,pg.course_num_ online_classes_num_,pg.total_price_,cg.expect_student_num_,
        cg.student_num_,su.real_name_ teacher_name_,su.avatar_,pg.create_time_,'PRACTICE' group_type_
        FROM practice_group pg
        LEFT JOIN class_group cg ON pg.id_ = cg.music_group_id_ AND cg.group_type_ = 'PRACTICE'
        LEFT JOIN teacher t ON pg.user_id_ = t.id_
        LEFT JOIN sys_user su ON pg.user_id_ = su.id_
        WHERE pg.audit_status_ = 'PASS' AND pg.group_status_ = 'APPLYING' AND pg.courses_expire_date_ >= DATE_FORMAT(NOW(),'%Y%m%d')
        AND pg.registration_start_time_ &lt;= NOW()
        AND pg.courses_start_date_ > NOW()
        AND (select count(1) as num from student_payment_order where pg.id_ = music_group_id_ AND user_id_ = #{userId}
        AND status_='SUCCESS') = 0 AND pg.student_id_ = #{userId}
        <if test="subjectId != null">
            AND pg.subject_id_ = #{subjectId}
        </if>
        <if test="search != null">
            AND pg.name_ LIKE concat('%',#{search},'%')
        </if>
        <if test="expireFlag != null and expireFlag == true">
            AND pg.payment_expire_date_ >= NOW()
        </if>
    </select>
    <select id="getPracticeGroupDetail" resultMap="com.ym.mec.biz.dal.dao.VipGroupDao.studentVipGroupDetailDto">
        SELECT pg.name_,pg.total_price_,pg.user_id_,pg.single_class_minutes_,pg.course_num_ online_classes_num_,0 offline_classes_num_,pg.id_,
               pg.payment_expire_date_,pg.courses_start_date_ courses_start_date,
               cg.total_class_times_,
               cg.expect_student_num_,
               cg.student_num_,
               su.real_name_                                      teacher_name_,
               su.avatar_,
               t.introduction_,
               cs.id_                                            course_id_,
               cs.class_group_id_,
               cs.status_,
               cs.subsidy_,
               cs.class_date_,
               CONCAT(cs.class_date_, ' ', cs.start_class_time_) start_class_time_,
               CONCAT(cs.class_date_, ' ', cs.end_class_time_)   end_class_time_,
               cs.teacher_id_,
               cs.actual_teacher_id_,
               cs.type_
        FROM practice_group pg
                 LEFT JOIN class_group cg ON pg.id_ = cg.music_group_id_ AND cg.group_type_ = 'PRACTICE'
                 LEFT JOIN course_schedule cs ON cg.id_ = cs.class_group_id_
                 LEFT JOIN teacher t ON pg.user_id_ = t.id_
                 LEFT JOIN sys_user su ON pg.user_id_ = su.id_
        WHERE pg.id_ = #{groupId}
        ORDER BY cs.start_class_time_
    </select>
    <select id="countTeacherPracticeGroups" resultType="java.lang.Integer">
        SELECT COUNT(id_)
        FROM practice_group
        WHERE user_id_ = #{teacherId}
    </select>
</mapper>
