<?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.yonge.cooleshow.biz.dal.dao.StudentDao">
    <resultMap id="BaseResultMap" type="com.yonge.cooleshow.biz.dal.entity.Student">
        <result column="user_id_" property="userId"/>
        <result column="subject_id_" property="subjectId"/>
        <result column="member_rank_setting_id_" property="memberRankSettingId"/>
        <result column="membership_start_time_" property="membershipStartTime"/>
        <result column="membership_end_time_" property="membershipEndTime"/>
        <result column="cloud_study_sequence_days_" property="cloudStudySequenceDays"/>
        <result column="cloud_study_use_last_day_" property="cloudStudyUseLastDay"/>
        <result column="lock_flag_" property="lockFlag" />
        <result column="tenant_id_" property="tenantId" />
        <result column="create_time_" property="createTime"/>
        <result column="update_time_" property="updateTime"/>
        <result column="avatar_" property="avatar"/>
        <result column="tenant_group_id_" property="tenantGroupId"/>
        <result column="im_device_id_" property="imDeviceId"/>
    </resultMap>

    <!-- 表字段 -->
    <sql id="baseColumns">
         t.user_id_ as `userId`
        , t.subject_id_ as `subjectId`
        , t.current_grade_num_ as `currentGradeNum`
        , t.member_rank_setting_id_ as `memberRankSettingId`
        , t.membership_start_time_ as `membershipStartTime`
        , t.membership_end_time_ as `membershipEndTime`
        , t.cloud_study_sequence_days_ as `cloudStudySequenceDays`
        , t.cloud_study_use_last_day_ as `cloudStudyUseLastDay`
        , t.train_time_ as trainTime
        , t.evaluate_time_ as evaluateTime
        , t.tenant_id_ as tenantId
        , t.create_time_ as `createTime`
        , t.update_time_ as `updateTime`
        , t.tenant_group_id_ as `tenantGroupId`
        , t.im_device_id_ as imDeviceId
        </sql>
    <update id="setSubject">
        update student set subject_id_ = #{subjectIds},update_time_ = now() where user_id_ = #{id}
    </update>

    <select id="detail" resultType="com.yonge.cooleshow.biz.dal.vo.StudentVo">
        SELECT
            <include refid="baseColumns"/>,
            if(u.lock_flag_ = 0 and t.lock_flag_ = 0,0,1) as lockFlag,
            u.avatar_ as userAvatar,
            u.avatar_ as avatar,
            u.real_name_ as realName,
            u.id_card_no_ as idCardNo,
            u.username_ as username,
            u.gender_ as gender,
            u.birthdate_ as birthdate,
            u.im_token_ as imToken,
            TIMESTAMPDIFF(YEAR, u.birthdate_, CURDATE()) as age,
            u.phone_ as phone,
            (case when isnull(u.id_card_no_) then 0 else 1 end) as isReal,
            (!isnull(membership_end_time_) and membership_end_time_ > now()) as isVip,
            (
            SELECT GROUP_CONCAT(name_ ORDER by locate(id_,t.subject_id_)) FROM subject WHERE FIND_IN_SET(id_,t.subject_id_)
            ) as subjectName,
            u.user_type_ as userType,
            (case when t.tenant_id_ = -1 then '平台学生' else ti.name_ end) as tenantName
        FROM student t
        left join sys_user u on t.user_id_ = u.id_
        left join tenant_info ti on ti.id_ = t.tenant_id_
        where u.del_flag_ = 0 and t.user_id_ = #{userId}
    </select>
    <select id="detailByPhone" resultType="com.yonge.cooleshow.biz.dal.vo.StudentVo">
        SELECT
            <include refid="baseColumns"/>,
            if(u.lock_flag_ = 0 and t.lock_flag_ = 0,0,1) as lockFlag,
            u.avatar_ as avatar,
            u.real_name_ as realName,
            u.id_card_no_ as idCardNo,
            u.username_ as username,
            u.gender_ as gender,
            u.birthdate_ as birthdate,
            TIMESTAMPDIFF(YEAR, u.birthdate_, CURDATE()) as age,
            u.phone_ as phone,
            (case when isnull(u.id_card_no_) then 0 else 1 end) as isReal,
            (!isnull(membership_end_time_) and membership_end_time_ > now()) as isVip,
            (
                SELECT GROUP_CONCAT(name_ ORDER by locate(id_,t.subject_id_)) FROM subject WHERE FIND_IN_SET(id_,t.subject_id_)
            ) as subjectName,
            u.user_type_ as userType
        FROM student t
        left join sys_user u on t.user_id_ = u.id_
        where u.del_flag_ = 0 and u.phone_ = #{phone}
    </select>
    <!-- 分页查询 -->
    <select id="selectPage" resultType="com.yonge.cooleshow.biz.dal.vo.StudentVo">
        SELECT
            <include refid="baseColumns"/>,
            if(u.lock_flag_ = 0 and t.lock_flag_ = 0,0,1) as lockFlag,
            u.avatar_ as userAvatar,
            u.avatar_ as avatar,
            u.username_ as username,
            u.gender_ as gender,
            u.birthdate_ as birthdate,
            u.del_flag_ as delFlag,
            TIMESTAMPDIFF(YEAR, u.birthdate_, CURDATE()) as age,
            u.phone_ as phone,
            !isnull(birthdate_) as isReal,
            u.real_name_ as realName,
            (!isnull(membership_end_time_) and membership_end_time_ > now()) as isVip,
            (
            SELECT GROUP_CONCAT(name_ ORDER by locate(id_,t.subject_id_)) FROM subject WHERE FIND_IN_SET(id_,t.subject_id_)
            ) as subjectName,
            (case when t.tenant_id_ = -1 then '平台学生' else ti.name_ end) as tenantName
        FROM student t
        left join sys_user u on t.user_id_ = u.id_
        left join tenant_info ti on t.tenant_id_ = ti.id_
        <where>
            <if test="null != param.search and '' != param.search">
                AND (
                    t.user_id_ LIKE CONCAT('%', #{param.search}, '%') or
                    u.username_ LIKE CONCAT('%', #{param.search}, '%') or
                    u.real_name_ LIKE CONCAT('%', #{param.search}, '%') or
                    u.phone_ LIKE CONCAT('%', #{param.search}, '%')
                )
            </if>
            <if test="null != param.gender">
                and u.gender_ = #{param.gender}
            </if>
            <if test="null != param.subjectId and '' != param.subjectId">
                AND FIND_IN_SET(t.subject_id_, #{param.subjectId})
            </if>
            <if test="null != param.isVip">
                <if test="1 == param.isVip.code">
                    and t.membership_end_time_ &gt; now()
                </if>
                <if test="0 == param.isVip.code">
                    and (t.membership_end_time_ is null or t.membership_end_time_ &lt;= now())
                </if>
            </if>
            <if test="param.startTime !=null">
                <![CDATA[AND t.create_time_ >= #{param.startTime} ]]>
            </if>
            <if test="param.endTime !=null">
                <![CDATA[AND t.create_time_ < #{param.endTime} ]]>
            </if>
            <if test="null != param.lockFlag">
                and t.lock_flag_ = #{param.lockFlag}
            </if>
            <if test="null != param.delFlag">
                and u.del_flag_ = #{param.delFlag}
            </if>
            <if test="null != param.vipEndTime">
                and t.membership_end_time_ &lt;= #{param.vipEndTime}
            </if>
            <if test="null != param.vipStartTime">
                and t.membership_end_time_ &gt;= #{param.vipStartTime}
            </if>
            <if test="param.trainFlag != null">
                AND t.train_time_ > 0
            </if>
            <if test="param.evaluateFlag != null">
                AND t.evaluate_time_ > 0
            </if>
            <if test="param.hideFlag != null">
                and t.hide_flag_ = #{param.hideFlag}
            </if>
            <if test="param.tenantId != null">
                and t.tenant_id_ = #{param.tenantId}
            </if>
            <if test="param.bindTenant != null and param.bindTenant == 0">
                and t.tenant_id_ = -1
            </if>
            <if test="param.bindTenant != null and param.bindTenant == 1">
                and t.tenant_id_ != -1
            </if>
            <if test="param.tenantName != null and param.tenantName.trim() != ''">
                and ti.name_ like concat('%',#{param.tenantName},'%')
            </if>
            <if test="param.phoneList != null and param.phoneList.size() > 0">
                and u.phone_ in
                <foreach collection="param.phoneList" separator="," item="item"  open="(" close=")" >
                    #{item}
                </foreach>
            </if>
            <if test="param.tenantGroupId != null and param.tenantGroupId.trim() != ''">
                AND FIND_IN_SET(t.tenant_group_id_, #{param.tenantGroupId})
            </if>
        </where>
        <choose>
            <when test="param.orderBy != null and param.orderBy.trim() != ''">
                order by ${param.orderBy}
            </when>
            <otherwise>
                order by t.create_time_ desc
            </otherwise>
        </choose>
    </select>

    <select id="querySubject" resultMap="com.yonge.cooleshow.biz.dal.dao.SubjectDao.Subject">
        SELECT s.* FROM `subject` s
        LEFT JOIN student t ON FIND_IN_SET(s.id_,t.subject_id_)
        WHERE t.user_id_ = #{userId}
    </select>

    <select id="querySubjectItem" resultType="com.yonge.cooleshow.biz.dal.entity.Subject">
        select t.* from subject t
        join (
            select a.subject_id_ from (
                <trim prefixOverrides="union all">
                    <if test="type == null or type =='MUSIC'">
                        union all
                        (
                            select
                                a.music_subject_ as subject_id_
                            from music_sheet a
                            join music_sheet_purchase_record a1 on a.id_ = a1.music_sheet_id_
                            where a1.student_id_ = #{userId} and a1.order_status_ = 'PAID'
                            GROUP BY a.music_subject_
                        )
                    </if>
                    <if test="type == null or type =='VIDEO'">
                        union all
                        (
                            select
                                a.lesson_subject_ as subject_id_
                            from video_lesson_group a
                            join video_lesson_purchase_record a1 on a.id_ = a1.video_lesson_group_id_
                            where a1.student_id_ = #{userId}
                            GROUP BY a.lesson_subject_
                        )
                    </if>
                    <if test="type == null or type =='PIANO_ROOM'">
                        union all
                        (
                            select
                                a.subject_id_ as subject_id_
                            from course_group a
                            join course_schedule_student_payment a1 on a.id_ = a1.course_group_id_
                            where a.type_ = 'PIANO_ROOM_CLASS' and a1.user_id_ = #{userId}
                            GROUP BY a.subject_id_
                        )
                    </if>
                    <if test="type == null or type =='PRACTICE'">
                        union all
                        (
                            select
                                a.subject_id_ as subject_id_
                            from course_group a
                            join course_schedule_student_payment a1 on a.id_ = a1.course_group_id_
                            where a.type_ = 'PRACTICE' and a1.user_id_ = #{userId}
                            GROUP BY a.subject_id_
                        )
                    </if>
                    <if test="type == null or type =='LIVE'">
                        union all
                        (
                            select
                                a.subject_id_ as subject_id_
                            from course_group a
                            join course_schedule_student_payment a1 on a.id_ = a1.course_group_id_
                            where a.type_ = 'LIVE' and a1.user_id_ = #{userId}
                            GROUP BY a.subject_id_
                        )
                    </if>
                </trim>
            ) a group by a.subject_id_
        ) a on t.id_ = a.subject_id_
        where t.parent_subject_id_ != 0
        and not exists(
            select 1 from student s where s.user_id_ = #{userId} and find_in_set(t.id_,s.subject_id_)
        )
    </select>

    <resultMap id="queryMyFollowResult" type="com.yonge.cooleshow.biz.dal.vo.MyFollow">
        <id column="userId" property="userId" />
        <result column="avatar" property="avatar" />
        <result column="userName" property="userName" />
        <result column="realName" property="realName" />
        <result column="gender" property="gender" />
        <result column="starGrade" property="starGrade" />
        <result column="fansNum" property="fansNum" />
        <result column="liveFlag" property="liveFlag" />
        <result column="subjectName" property="subjectName" />
        <result column="roomUid" property="roomUid" />
        <association property="teacher"  javaType="com.yonge.cooleshow.biz.dal.entity.Teacher" resultMap="com.yonge.cooleshow.biz.dal.dao.TeacherDao.BaseResultMap"/>
    </resultMap>

    <select id="queryMyFollow" resultMap="queryMyFollowResult">
        SELECT
            s.teacher_id_ as userId,
            u.avatar_ as avatar,
            u.username_ as userName,
            u.real_name_ as realName,
            u.gender_ as gender,
            t.star_grade_ as starGrade,
            t.fans_num_ as fansNum,
            t.live_flag_ as liveFlag,
            t.exp_time_ as expTime,
            (SELECT group_concat( name_ ) FROM `subject` WHERE find_in_set( id_, tr.subject_id_ )) AS subjectName,
            r.room_uid_ as roomUid,
            tr.entry_flag_ as entryFlag,
            tr.musician_flag_ as musicianFlag,
            tr.*
        FROM student_star s
        LEFT JOIN sys_user u ON s.teacher_id_ = u.id_
        LEFT JOIN teacher_total t ON s.teacher_id_ = t.user_id_
        LEFT JOIN teacher tr ON s.teacher_id_ = tr.user_id_
        LEFT JOIN (SELECT room_uid_,speaker_id_ FROM live_room WHERE live_state_=1 and room_state_  = 0 and type_ = 'TEMP') r ON t.user_id_= r.speaker_id_
        WHERE s.student_id_ = #{param.userId}
        <if test="param.username != null and param.username != ''">
            and u.username_ LIKE CONCAT('%', #{param.username}, '%')
        </if>
    </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_ = sub.id_
        WHERE stu.user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
    </select>

    <select id="countStudentsWithTenant" resultType="int">
        SELECT COUNT(su.id_) FROM sys_user su
        left join student s ON s.user_id_ = su.id_
        WHERE
        s.tenant_id_ = #{tenantId}
        AND su.del_flag_=0 AND su.lock_flag_=0
        AND FIND_IN_SET('STUDENT',su.user_type_)
        <if test="search != null">
            AND (su.username_ LIKE CONCAT('%', #{search}, '%') OR su.phone_ LIKE CONCAT('%', #{search}, '%'))
        </if>
    </select>

    <select id="countTeacherByTenantIds" resultType="com.yonge.cooleshow.biz.dal.wrapper.TenantInfoWrapper$UserCount">
        select tenant_id_ tenantId, count(tenant_id_) count
        from student
        <where>
            lock_flag_ = 0
            <if test="tenantIdList != null">
                AND tenant_id_ in
                <foreach collection="tenantIdList" item="item" separator="," open="(" close=")">
                    #{item}
                </foreach>
            </if>
        </where>
        group by tenant_id_
    </select>
    <select id="queryStudentCounts" resultType="java.lang.Integer">
        select count(tenant_id_)
        from student
        <where>
            lock_flag_ = 0
            <if test="id != null">
                and  tenant_id_ = #{id}
            </if>
        </where>
    </select>

    <select id="countStudentByTenantGroupIds" resultType="com.yonge.cooleshow.biz.dal.wrapper.StudentWrapper$UserCount">
        select ifnull(tenant_group_id_,-1) tenantGroupId, count(user_id_) count
        from student
        <where>
            hide_flag_ = 0
            <if test="tenantId != null">
                AND tenant_id_ =#{tenantId}
            </if>
            <if test="groupIdList != null and groupIdList.size() > 0">
                AND tenant_group_id_ in
                <foreach collection="groupIdList" item="item" separator="," open="(" close=")">
                    #{item}
                </foreach>
            </if>
        </where>
        group by tenant_group_id_
    </select>
</mapper>