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

	<resultMap type="com.ym.mec.biz.dal.entity.SysMusicCompareRecord" id="SysMusicCompareRecord">
		<result column="id_" property="id" />
		<result column="user_id_" property="userId" />
		<result column="sys_music_score_id_" property="sysMusicScoreId" />
		<result column="heard_level_" property="heardLevel" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler" />
		<result column="sys_music_score_name_" property="sysMusicScoreName" />
		<result column="behavior_id_" property="behaviorId"/>
		<result column="score_data_" property="scoreData" />
		<result column="notes_data_index_" property="notesDataIndex"/>
		<result column="score_" property="score" />
		<result column="intonation_" property="intonation" />
		<result column="cadence_" property="cadence" />
		<result column="integrity_" property="integrity" />
		<result column="record_file_path_" property="recordFilePath" />
		<result column="video_file_path_" property="videoFilePath" />
		<result column="device_type_" property="deviceType" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler" />
		<result column="client_id_" property="clientId" />
		<result column="source_time_" property="sourceTime"/>
		<result column="play_time_" property="playTime"/>
		<result column="speed_" property="speed"/>
		<result column="feature_" property="feature" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler" />
		<result column="monday_" property="monday"/>
		<result column="create_time_" property="createTime" />
		<result column="part_index_" property="partIndex" />
        <result column="tenant_id_" property="tenantId"/>
	</resultMap>

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

	<!-- 全查询 -->
	<select id="findAll" resultMap="SysMusicCompareRecord">
		SELECT * FROM sys_music_compare_record where tenant_id_ = #{tenantId} ORDER BY id_
	</select>

	<!-- 向数据库增加一条记录 -->
	<insert id="insert" parameterType="com.ym.mec.biz.dal.entity.SysMusicCompareRecord" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
		INSERT INTO sys_music_compare_record (id_,user_id_,sys_music_score_id_,heard_level_,behavior_id_,score_data_,score_,intonation_,cadence_,integrity_,
		                                      record_file_path_,video_file_path_,device_type_,client_id_,play_time_,speed_,monday_,
												source_time_,feature_,create_time_,update_time_,part_index_,tenant_id_)
		VALUES(#{id},#{userId},#{sysMusicScoreId},#{heardLevel,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{behaviorId},#{scoreData},
		       #{score},#{intonation},#{cadence},#{integrity},
		       #{recordFilePath},#{videoFilePath},#{deviceType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{clientId},#{playTime},#{speed},#{monday},
		       #{sourceTime},#{feature,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}, NOW(), NOW(),#{partIndex},#{tenantId})
	</insert>

	<!-- 根据主键查询一条记录 -->
	<update id="update" parameterType="com.ym.mec.biz.dal.entity.SysMusicCompareRecord">
		UPDATE sys_music_compare_record <set>
		<if test="userId != null">
			user_id_ = #{userId},
		</if>
		<if test="sysMusicScoreId != null">
			sys_music_score_id_ = #{sysMusicScoreId},
		</if>
		<if test="behaviorId!=null">
			behavior_id_ = #{behaviorId},
		</if>
		<if test="scoreData != null">
			score_data_ = #{scoreData},
		</if>
		<if test="score != null">
			score_ = #{score},
		</if>
		<if test="intonation!=null">
			intonation_ = #{intonation},
		</if>
		<if test="integrity != null">
			integrity_ = #{integrity},
		</if>
		<if test="cadence != null">
			cadence_ = #{cadence},
		</if>
		<if test="recordFilePath != null">
			record_file_path_ = #{recordFilePath},
		</if>
		<if test="videoFilePath != null">
			video_file_path_ = #{videoFilePath},
		</if>
		<if test="clientId != null">
			client_id_ = #{clientId},
		</if>
		<if test="deviceType!=null">
			device_type_ = #{deviceType, typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
		</if>
		<if test="sourceTime != null">
			source_time_ = #{sourceTime},
		</if>
		<if test="playTime != null">
			play_time_ = #{playTime},
		</if>
		<if test="speed != null">
			speed_ = #{speed},
		</if>
		<if test="monday != null">
			monday_ = #{monday},
		</if>
		<if test="partIndex != null">
			part_index_ = #{partIndex},
		</if>
		<if test="feature!=null">
			feature_ = #{feature,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
		</if>
		<if test="heardLevel!=null">
			heard_level_ = #{heardLevel,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
		</if>
		update_time_ = NOW()
	</set> WHERE id_ = #{id} and tenant_id_ = #{tenantId}
	</update>

	<!-- 根据主键删除一条记录 -->
	<delete id="delete" >
		DELETE FROM sys_music_compare_record WHERE id_ = #{id}
	</delete>

	<sql id="queryCondition">
		<where>
			smcr.tenant_id_ = #{tenantId}
			<if test="userId!=null">
				AND smcr.user_id_=#{userId}
			</if>
			<if test="featureType != null">
				AND smcr.feature_ = #{featureType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
			</if>
			<if test="startTime != null and startTime != ''">
				AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') >= CONCAT(#{startTime},' 00:00:00')
			</if>
			<if test="endTime != null and endTime != ''">
				AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') &lt;= CONCAT(#{endTime},' 23:59:59')
			</if>
		</where>
	</sql>

	<!-- 分页查询 -->
	<select id="queryPage" resultMap="SysMusicCompareRecord" parameterType="map">
		SELECT
			smcr.id_, smcr.user_id_, smcr.sys_music_score_id_, smcr.heard_level_,
			LOCATE('musicalNotesPlayStats', smcr.score_data_) notes_data_index_,
		       smcr.score_, smcr.intonation_, smcr.cadence_,
		       smcr.integrity_, smcr.record_file_path_, smcr.video_file_path_, smcr.client_id_, smcr.device_type_, smcr.play_time_,
		       smcr.monday_, smcr.create_time_,
			sms.name_ sys_music_score_name_
		FROM sys_music_compare_record smcr
		LEFT JOIN sys_music_score sms on smcr.sys_music_score_id_ = sms.id_
		<include refid="queryCondition"/>
		ORDER BY id_ DESC
		<include refid="global.limit"/>
	</select>

	<!-- 查询当前表的总记录数 -->
	<select id="queryCount" resultType="int">
		SELECT COUNT(*) FROM sys_music_compare_record smcr
		<include refid="queryCondition"/>
	</select>

    <select id="getUserTrainStat" resultType="com.ym.mec.biz.dal.dto.MusicCompareRankingDto">
		SELECT
			smcr.user_id_ userId,
			su.avatar_ avatar,
		    su.username_ studentName,
		    sms.name_ musicScoreName,
			COUNT(smcr.id_) trainNum,
		    MAX(smcr.score_) score,
			COUNT(DISTINCT DATE(smcr.create_time_)) trainDays,
			SUM(smcr.play_time_) trainTime
		FROM sys_music_compare_record smcr
			LEFT JOIN sys_user su ON smcr.user_id_=su.id_
			LEFT JOIN sys_music_score sms ON smcr.sys_music_score_id_ = sms.id_
		WHERE EXISTS (SELECT user_id_ FROM student WHERE user_id_=smcr.user_id_)
		AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') BETWEEN #{startTime} AND #{endTime}
		<if test="heardLevel!=null">
			AND smcr.heard_level_ = #{heardLevel, typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
		</if>
		GROUP BY smcr.user_id_
	</select>

	<select id="getUserTrainOverView" resultType="com.ym.mec.biz.dal.dto.StudentTrainOverviewDto">
		SELECT
			COUNT(DISTINCT smcr.behavior_id_) trainNum,
			COUNT(DISTINCT DATE(smcr.create_time_)) trainDays,
			SUM(smcr.play_time_) trainTime
		FROM sys_music_compare_record smcr
		WHERE smcr.user_id_=#{userId}
	</select>

	<select id="getUserTrainChartData" resultType="com.ym.mec.biz.dal.dto.StudentTrainChartDto">
		SELECT
			DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') trainDate,
			COUNT(DISTINCT smcr.behavior_id_) trainNum,
			SUM(smcr.play_time_) trainTime
		FROM sys_music_compare_record smcr
		WHERE smcr.user_id_=#{userId}
		  AND EXISTS (SELECT user_id_ FROM student WHERE user_id_=smcr.user_id_)
		  AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') BETWEEN #{startTime} AND #{endTime}
		GROUP BY DATE_FORMAT(smcr.create_time_, '%Y-%m-%d')
		ORDER BY trainDate;
	</select>

	<sql id="queryMusicGroupStudentTrainDataConditon">
		<where>
			sr.music_group_status_='NORMAL' AND stu.user_id_ IS NOT NULL and sr.tenant_id_ = #{tenantId}
			<if test="startTime!=null and endTime!=null">
				AND DATE_FORMAT( smcr.create_time_, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime}
			</if>
			<if test="musicGroupId!=null">
				AND sr.music_group_id_ = #{musicGroupId}
			</if>
			<if test="search!=null">
				AND (su.username_ LIKE CONCAT('%', #{search}, '%'))
			</if>
		</where>
	</sql>

	<select id="queryMusicGroupStudentTrainData" resultType="com.ym.mec.biz.dal.dto.MusicCompareRankingDto">
		SELECT
			smcr.user_id_ userId,
			su.avatar_ avatar,
			su.username_ studentName,
			COUNT( smcr.id_ ) trainNum,
			COUNT( DISTINCT DAY ( smcr.create_time_ )) trainDays,
			SUM( smcr.play_time_ ) trainTime,
			CASE WHEN stu.member_rank_setting_id_ IS NULL THEN 0 ELSE 1 END vipUser
		FROM
			sys_music_compare_record smcr
				LEFT JOIN sys_user su ON smcr.user_id_ = su.id_
				LEFT JOIN student stu ON stu.user_id_ = smcr.user_id_
				LEFT JOIN student_registration sr ON sr.user_id_=smcr.user_id_
		<include refid="queryMusicGroupStudentTrainDataConditon"></include>
		GROUP BY smcr.user_id_
		<if test="sortField!=null and sortField!=''">
			<if test="sortField == 'TRAINDAYS'">
				ORDER BY trainDays
			</if>
			<if test="sortField == 'TRAINTIME'">
				ORDER BY trainTime
			</if>
			<if test="sortField == 'TRAINNUM'">
				ORDER BY trainNum
			</if>
		</if>
		<include refid="global.limit"></include>
	</select>

	<select id="countMusicGroupStudentTrainData" 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 stu.user_id_ = smcr.user_id_
		LEFT JOIN student_registration sr ON sr.user_id_=smcr.user_id_
		<include refid="queryMusicGroupStudentTrainDataConditon"/>
	</select>

	<select id="queryStudentTrainData" resultType="com.ym.mec.biz.dal.dto.EduOrganStudentListDto">
		SELECT
			user_id_ studentId,
			COUNT(DISTINCT behavior_id_) cloudStudyUseNum,
			SUM(play_time_) cloudStudyUseTime
		FROM
			sys_music_compare_record
		GROUP BY
			user_id_
	</select>
	<resultMap id="CountStudentTrainDataDto" type="com.ym.mec.biz.dal.dto.CountStudentTrainDataDto">
		<result property="trainNum" column="train_num_"/>
		<result property="recordNum" column="record_num_"/>
		<result property="avatar" column="avatar_"/>
		<result property="userId" column="user_id_"/>
		<result property="username" column="username_"/>
		<result property="phone" column="phone_"/>
		<result property="totalPlayTime" column="total_play_time_"/>
		<result property="trainDay" column="train_day_"/>
	</resultMap>
	<select id="queryStudentTrain" resultMap="CountStudentTrainDataDto">
		SELECT s.user_id_,su.avatar_,su.phone_,su.username_,ROUND(SUM(mcr.play_time_) / 60) total_play_time_,
			   COUNT(DISTINCT DATE_FORMAT(mcr.create_time_,"%Y-%m-%d")) train_day_,
			   COUNT(DISTINCT mcr.behavior_id_) train_num_,
		COUNT(CASE WHEN mcr.feature_ = 'CLOUD_STUDY_EVALUATION' THEN mcr.behavior_id_ ELSE NULL END) record_num_
		FROM teacher t
				 LEFT JOIN student s ON t.id_ = s.teacher_id_
				 LEFT JOIN sys_user su ON su.id_ = s.user_id_
				 LEFT JOIN sys_music_compare_record mcr ON mcr.user_id_ = s.user_id_
		<if test="startTime != null and startTime != ''">
			AND (DATE_FORMAT(mcr.create_time_, '%Y-%m-%d') >= #{startTime} OR mcr.id_ IS NULL)
		</if>
		<if test="endTime != null and endTime != ''">
			AND (DATE_FORMAT(mcr.create_time_, '%Y-%m-%d') &lt;= #{endTime} OR mcr.id_ IS NULL)
		</if>
		WHERE s.teacher_id_ = #{teacherId}
		<if test="search != null and search != ''">
			AND (su.phone_ LIKE CONCAT('%',#{search},'%') OR su.username_ LIKE CONCAT('%',#{search},'%'))
		</if>
		<if test="visitStudents != null and visitStudents.size > 0">
			AND s.user_id_ NOT IN
			<foreach collection="visitStudents" open="(" close=")" item="userId" separator=",">
				#{userId}
			</foreach>
		</if>
		<if test="hasCourseUserIds != null and hasCourseUserIds.size > 0">
			AND s.user_id_ IN
			<foreach collection="hasCourseUserIds" open="(" close=")" item="userId" separator=",">
				#{userId}
			</foreach>
		</if>
		GROUP BY s.user_id_
		<if test="having == 1">
			HAVING total_play_time_ &lt; ${totalTime} OR train_num_ &lt; ${trainNum}
		</if>
		ORDER BY
		<if test="sort != null and sort != ''">
			${sort}
			<if test="order != null and order != ''">
				${order}
			</if>
		</if>
		<if test="sort == null or sort == ''">
			total_play_time_ DESC
		</if>
		,s.user_id_
		<include refid="global.limit"/>
	</select>

	<select id="getOrganNewCloudStudyNum" resultType="int">
		SELECT
			COUNT( DISTINCT user_id_ )
		FROM
			(
				SELECT
					smcr.user_id_
				FROM
					sys_music_compare_record smcr
						LEFT JOIN sys_user su ON smcr.user_id_ = su.id_
				WHERE
					su.del_flag_ = 0
					AND su.organ_id_ = #{organId}
				GROUP BY
					user_id_
				HAVING
						COUNT(
								DISTINCT DATE( smcr.create_time_ ))= 1
				   AND MAX(
							   DATE( smcr.create_time_ ))= CURDATE()) t
	</select>

	<select id="getOrgansTotalNewCloudStudyNum" resultType="int">
		SELECT
			COUNT( DISTINCT user_id_ )
		FROM
			(
				SELECT
					smcr.user_id_
				FROM
					sys_music_compare_record smcr
						LEFT JOIN sys_user su ON smcr.user_id_ = su.id_
				WHERE
					su.del_flag_ = 0
					<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
					user_id_
				HAVING
						COUNT(DISTINCT DATE( smcr.create_time_ ))= 1
				   AND MAX(DATE( smcr.create_time_ ))= CURDATE()) t
	</select>

	<select id="getOrgansNewCloudStudyNum" resultType="map">
		SELECT
			organ_id_ 'key',
			COUNT( DISTINCT user_id_ ) 'value'
		FROM
			(
				SELECT
					su.organ_id_,
					smcr.user_id_
				FROM
					sys_music_compare_record smcr
						LEFT JOIN sys_user su ON smcr.user_id_ = su.id_
				WHERE
					su.del_flag_ = 0
					<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
					user_id_
				HAVING
						COUNT(
								DISTINCT DATE( smcr.create_time_ ))= 1
				   AND MAX(
							   DATE( smcr.create_time_ ))= CURDATE()) t
		GROUP BY t.organ_id_
	</select>

    <select id="getUserLastEvaluationData" resultMap="SysMusicCompareRecord">
		SELECT * FROM sys_music_compare_record WHERE user_id_=#{userId} AND feature_ = 'CLOUD_STUDY_EVALUATION' ORDER BY create_time_ DESC LIMIT 1
	</select>

	<select id="getUserWeekCompareData" resultType="com.ym.mec.biz.dal.entity.SysMusicCompareWeekData">
		SELECT
			COUNT(smcr.id_) trainNum,
			COUNT(DISTINCT DATE(smcr.create_time_)) trainDays,
			SUM(smcr.play_time_) trainTime,
			MAX(IF(heard_level_='BEGINNER' AND source_time_ &gt;= play_time_, smcr.score_, 0)) beginnerMaxScore,
			MAX(IF(heard_level_='ADVANCED' AND source_time_ &gt;= play_time_, smcr.score_, 0)) advancedMaxScore,
			MAX(IF(heard_level_='PERFORMER' AND source_time_ &gt;= play_time_, smcr.score_, 0)) performerMaxScore,smcr.tenant_id_ tenantId
		FROM sys_music_compare_record smcr
		WHERE user_id_=#{userId} AND monday_ = #{monday}
	</select>

	<select id="getUserWeekMaxMusicScoreId" resultType="java.lang.Integer">
		SELECT sys_music_score_id_ FROM sys_music_compare_record
		WHERE user_id_=#{userId} AND monday_ = #{monday} AND heard_level_ = #{heardLevel, typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
		ORDER BY score_ DESC LIMIT 1
	</select>

	<select id="queryCurrentDatePlayTimeByUserId" resultType="int">
		SELECT sum(ifnull(cr.`play_time_`,0))  FROM `sys_music_compare_record` cr WHERE date(cr.`create_time_`) = CURDATE() AND cr.`user_id_` = #{userId}
	</select>
	<resultMap id="ExportCompareRecordDto" type="com.ym.mec.biz.dal.dto.ExportCompareRecordDto">
		<result property="userId" column="user_id_" />
		<result property="username" column="username_" />
		<result property="phone" column="phone_" />
		<result property="organName" column="organ_name_" />
		<result property="heardNum" column="heard_num_" />
		<result property="playDays" column="play_days_" />
		<result property="playTime" column="play_time_" />
		<result property="playNum" column="play_num_" />
	</resultMap>
    <select id="exportCompareRecord" resultMap="ExportCompareRecordDto">
		select o.name_ organ_name_,smcr.user_id_,su.username_,su.phone_,ROUND(sum(smcr.play_time_) / 60) play_time_,
			   COUNT(su.id_) play_num_,COUNT(DISTINCT DATE_FORMAT(smcr.create_time_,'%Y-%m-%d')) play_days_,
			   COUNT(CASE WHEN smcr.score_ IS NULL THEN NULL ELSE 1 END) heard_num_
		from sys_music_compare_record smcr
		left join sys_user su ON su.id_ = smcr.user_id_
		left join organization o ON o.id_ = su.organ_id_
		<where>
			<if test="queryInfo.organId != null and queryInfo.organId != ''">
				AND FIND_IN_SET(su.organ_id_, #{queryInfo.organId})
			</if>
			<if test="queryInfo.startDate != null and queryInfo.startDate != ''">
				AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') &gt;= #{queryInfo.startDate}
			</if>
			<if test="queryInfo.endDate != null and queryInfo.endDate != ''">
				AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') &lt;= #{queryInfo.endDate}
			</if>
		</where>
		group by smcr.user_id_
		order by o.id_
	</select>
	<select id="countExportCompareRecord" resultType="java.lang.Integer">
		select COUNT(DISTINCT smcr.user_id_)
		from sys_music_compare_record smcr
		left join sys_user su ON su.id_ = smcr.user_id_
		<where>
			<if test="queryInfo.organId != null and queryInfo.organId != ''">
				AND FIND_IN_SET(su.organ_id_, #{queryInfo.organId})
			</if>
			<if test="queryInfo.startDate != null and queryInfo.startDate != ''">
				AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') &gt;= #{queryInfo.startDate}
			</if>
			<if test="queryInfo.endDate != null and queryInfo.endDate != ''">
				AND DATE_FORMAT(smcr.create_time_, '%Y-%m-%d') &lt;= #{queryInfo.endDate}
			</if>
		</where>
	</select>
</mapper>
