<?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.nbclass.activity.mapper.ContentMapper">

  <resultMap id="BaseResultMap" type="com.nbclass.activity.model.Content">
    <id column="id" jdbcType="BIGINT" property="id" />
	<collection property="tagList" column="id" ofType="ContentTags" select="getContentTags"/>
	<collection property="imgList" column="id" ofType="ContentImages" select="getContentImages"/>
  </resultMap>

	<resultMap id="BaseResultMap2" type="com.nbclass.activity.model.Content">
		<id column="id" property="id"/>
		<result column="createtime" property="createtime"/>
		<result column="updatetime" property="updatetime"/>
		<result column="type" property="type"/>
		<result column="isvalid" property="isvalid"/>
		<result column="fromid" property="fromid"/>
		<result column="title" property="title"/>
		<result column="desct" property="desct"/>
		<result column="viewno" property="viewno"/>
		<result column="praiseno" property="praiseno"/>
		<result column="collection_number" property="collectionNumber"/>
		<result column="listicon" property="listicon"/>
		<result column="qrcode" property="qrcode"/>
		<result column="sort" property="sort"/>
		<result column="url" property="url"/>
		<result column="content" property="content"/>
		<result column="content_text" property="content_text"/>
		<result column="attachment" property="attachment"/>
		<result column="label_feedback" property="labelFeedback"/>
		<result column="online_time" property="onlineTime"/>
		<result column="visibility" property="visibility"/>
		<result column="comments" property="comments"/>
		<result column="name" property="userName"/>
		<result column="position" property="position"/>
		<result column="release" property="release"/>
		<result column="status" property="status"/>
		<result column="checkStatus" property="checkStatus"/>
		<result column="applicationId" property="applicationId"/>


<!--		<association property="application" javaType="com.nbclass.activity.model.Application" column="id" select="getApplicationStatus">-->
<!--			<id column="id" property="id"/>-->
<!--			<result column="status" property="status"/>-->
<!--		</association>-->

		<collection property="tagList" ofType="com.nbclass.activity.model.ContentTags" column="id" select="getTagList">
			<id column="id" property="id"/>
			<result column="tagName" property="tagName"/>
		</collection>

	</resultMap>

 	<select id="getContentTags" resultType="com.nbclass.activity.model.ContentTags" parameterType="java.lang.Long">
       select t.*, data_dict_item.name tagName,data_dict.id as dictId
       from content_tags t
       left join data_dict_item on t.tid = data_dict_item.id
	   left join data_dict on data_dict.id = data_dict_item.dictid
       WHERE t.cid = #{id}
    </select>
    <select id="getContentImages" resultType="com.nbclass.activity.model.ContentImages" parameterType="java.lang.Long">
       select t.* from content_images t WHERE t.cid = #{id} order by `sort`
    </select>

	<select id="findById" resultMap="BaseResultMap" parameterType="java.lang.Long">
		SELECT content.*, data_dict_item.name as fromName
		FROM content
		LEFT JOIN data_dict_item ON content.fromid = data_dict_item.id
		WHERE content.id = #{id}
	</select>

	<delete id="deleteByIds" parameterType="java.util.List">
		delete from content where id in
	    <foreach item="item" collection="list" open="(" separator="," close=")">
			#{item}
		</foreach>
	</delete>

	<select id="getList" resultType="com.nbclass.activity.model.Content" parameterType="com.nbclass.activity.model.Content">
		select content.*, data_dict_item.name as fromName
		from content
		left join data_dict_item on content.fromid = data_dict_item.id
		where 1=1
		<if test="type != null and type != ''">
		    AND content.type = #{type}
		</if>
	  	<if test="isvalid != null and isvalid >= 0">
		    AND content.isvalid = #{isvalid}
		</if>
	  	<if test="title != null and title != ''">
	    	AND (content.title like CONCAT('%',#{title},'%') or content.desct like CONCAT('%',#{title},'%') )
	  	</if>
		order by content.id desc
	</select>

	<select id="getList2" resultMap="BaseResultMap2">
		SELECT DISTINCT
			c.id as cid,
			c.*,
			u.user_id as name,
			u2.position,
		    IF(a.status=2,c.`release`,IFNULL(a.status,5)) as status,
		    IFNULL(a.id,null) as applicationId
		FROM
			content c
		LEFT JOIN application a on c.id = a.content_id
		LEFT JOIN `user` u ON c.user_id = u.id
		LEFT JOIN wx_user u2 ON u2.userid = u.username
		INNER JOIN content_tags tags ON tags.cid = c.id
		INNER JOIN data_dict_item item ON tags.tid = item.id
		INNER JOIN data_dict dict ON dict.id = item.dictid
		<where>
			<if test="userId!=null and roleId == 3">
				c.user_id = #{userId}
			</if>
			<if test="id!=null">
				and c.id = #{id}
			</if>
			<if test="title!=null and title!=''">
				and c.title like concat(concat('%',#{title},'%'))
			</if>
			<if test="status!=null">
				and a.status = #{status}
			</if>
			<if test="quantity!=null and quantity == 0">
				and c.label_feedback = 0
			</if>
			<if test="quantity!=null and quantity == 1">
				and c.label_feedback > 0
			</if>
			<if test="createtime!=null">
				and DATE_FORMAT(c.createtime, '%Y-%m-%d')>=  DATE_FORMAT(#{createtime}, '%Y-%m-%d')
			</if>
			<if test="createtimeSection!=null">
				and DATE_FORMAT(c.createtime, '%Y-%m-%d') &lt;= DATE_FORMAT(#{createtimeSection}, '%Y-%m-%d')
			</if>
			<if test="updatetime!=null">
				and DATE_FORMAT(c.updatetime, '%Y-%m-%d')>=  DATE_FORMAT(#{updatetime}, '%Y-%m-%d')
			</if>
			<if test="updatetimeSection!=null">
				and DATE_FORMAT(c.updatetime, '%Y-%m-%d') &lt;= DATE_FORMAT(#{updatetimeSection}, '%Y-%m-%d')
			</if>
			<if test="onlineTime!=null">
				and DATE_FORMAT(c.online_time, '%Y-%m-%d')>=  DATE_FORMAT(#{onlineTime}, '%Y-%m-%d')
			</if>
			<if test="onlineTimeSection!=null">
				and DATE_FORMAT(c.online_time, '%Y-%m-%d') &lt;= DATE_FORMAT(#{onlineTimeSection}, '%Y-%m-%d')
			</if>
			<if test="tagLists!=null and tagLists!=''">
				and item.id in
				<foreach collection="tagLists" open="(" separator="," item="id" close=")">
					#{id}
				</foreach>
				GROUP BY c.id,name,u2.position,status,applicationId
				<if test="count!=null and count==1">
					HAVING
					count(c.id) > 0
				</if>
				<if test="count!=null and count>1">
					HAVING
					count(c.id) = #{count}
				</if>
			</if>
		</where>
		order by c.id desc
	</select>


	<select id="getTagList" resultType="com.nbclass.activity.model.ContentTags">
		SELECT
			dict.id,
			item.`name` as tagName
		FROM
			content_tags tags
		LEFT JOIN data_dict_item item ON tags.tid = item.id
		LEFT JOIN data_dict dict ON dict.id = item.dictid
		WHERE
		tags.cid = #{id}
	</select>

	<select id="getListByFront" resultMap="BaseResultMap" parameterType="com.nbclass.activity.model.Content">
		select content.*, data_dict_item.name as fromName
		from content
		left join data_dict_item on content.fromid = data_dict_item.id
		where 1=1
		<if test="type != null and type != ''">
		    AND content.type = #{type}
		</if>
	  	<if test="isvalid != null and isvalid >= 0">
		    AND content.isvalid = #{isvalid}
		</if>
	  	<if test="title != null and title != ''"><!-- ES搜索service中，通过title字段提交keyWord -->
	    	AND (content.title like CONCAT('%',#{title},'%') or content.desct like CONCAT('%',#{title},'%') )
	  	</if>
	  	<if test="fromids != null and fromids != ''">
	  		AND content.fromid IN (${fromids})
	  	</if>
	  	<if test="tags != null and tags != ''">
	  		AND content.id IN (SELECT DISTINCT cid FROM content_tags WHERE tid IN (${tags}))
	  	</if>
		order by content.sort desc, content.id desc
	</select>

	<delete id="deleteTags" parameterType="java.lang.Long">
		delete from content_tags WHERE cid = #{cid}
	</delete>

	<insert id="insertContentTags" parameterType="java.util.List">
		INSERT IGNORE INTO content_tags (cid, tid)
		values
		<foreach collection="list" item="item" index="index" separator=",">
      		(#{item.cid}, #{item.tid} )
		</foreach>
	</insert>

	<delete id="deleteImages" parameterType="java.lang.Long">
		delete from content_images WHERE cid = #{cid}
	</delete>

	<insert id="insertContentImages" parameterType="java.util.List">
		INSERT IGNORE INTO content_images (cid, imgurl, sort, ori_name)
		values
		<foreach collection="list" item="item" index="index" separator=",">
      		(#{item.cid}, #{item.imgurl}, #{item.sort}, #{item.ori_name} )
		</foreach>
	</insert>


	<update id="updateContentNum" parameterType="java.lang.String">
		UPDATE content
		<set>
			<if test="type != null and type == 'view'.toString()">
				viewno = IF(viewno IS NULL, 1, viewno+1)
			</if>
			<if test="type != null and type == 'like'.toString()">
				praiseno = IF(praiseno IS NULL, 1, praiseno+1)
			</if>
		</set>
		WHERE id = #{id}
	</update>

	<select id="getCaseTitle" resultType="com.nbclass.activity.model.Content">
		select id,title,praiseno from content
	</select>

	<insert id="addContentTags">
		insert ignore into content_tags
		(
		 createtime,
		 cid,
		 tid
		)
		values
		(
		now(),
		#{cid},
		#{tid}
		)
	</insert>

	<select id="getOtherLabels" resultType="com.nbclass.activity.model.DataDictItem">
		select id,name from data_dict_item where dictid = 25
	</select>

	<delete id="deleteContentTags">
		delete from content_tags where cid in
		<foreach collection="list" item="id" open="(" separator="," close=")">
			#{id}
		</foreach>
	</delete>

	<update id="updateComments">
		update content set
		<if test="contentId!=null">
			comments = comments + 1
		</if>
		where id = #{contentId}
	</update>

	<insert id="saveScore">
		insert into scoring_table
		(
		content_id,
		score,
		user_id,
		create_time
		)
		values
		(
		#{contentId},
		#{score},
		#{userId},
		now()
		)
	</insert>

	<select id="getScore" resultType="int">
		select count(*) from scoring_table where user_id = #{userId} and content_id = #{contentId}
	</select>

	<select id="getEditContent" resultMap="BaseResultMap2">
		select
		       c.*,
		       a.id as applicationId,
		       IF(a.status=2,c.`release`,IFNULL(a.status,5)) as status
		from content c left join application a on c.id = a.content_id where c.id = #{contentId}
	</select>

	<insert id="saveApplication" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
		insert into application
		(
		 content_id,
		 user_id,
		 type,
		 create_time
		)
		values
		(
		#{contentId},
		#{userId},
		#{type},
		now()
		)
	</insert>

	<insert id="saveCheck" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
		insert into `check`
		(
		 application_id,
		 check_id,
		 create_time
		)
		values
		(
		#{applicationId},
		#{checkId},
		now()
		)
	</insert>

	<select id="getApplicationCount" resultType="int">
		select count(*) from application where content_id = #{contentId}
	</select>

	<delete id="deleteApplication">
		delete from application where id = #{applicationId}
	</delete>

	<delete id="deleteCheck">
		delete from `check` where application_id = #{applicationId}
	</delete>

	<update id="updateApplicationStatus">
		update application set
		<if test="applicationId!=null">
			status = 1
		</if>
		where id = #{applicationId}
	</update>

	<update id="updateCheckStatus">
		update `check` set
		<if test="applicationId!=null">
			status = 1
		</if>
		where application_id = #{applicationId}
	</update>

	<select id="getContentApplication" resultMap="BaseResultMap2">
		SELECT DISTINCT
		c.id as cid,
		c.*,
		u.user_id as name,
		u2.position,
		IF(a.status=2,c.`release`,IFNULL(a.status,5)) as status,
		IFNULL(a.id,null) as applicationId
		FROM
		content c
		LEFT JOIN application a on c.id = a.content_id
		LEFT JOIN `user` u ON c.user_id = u.id
		LEFT JOIN wx_user u2 ON u2.userid = u.username
		LEFT JOIN `check` ck on ck.application_id = a.id
		INNER JOIN content_tags tags ON tags.cid = c.id
		INNER JOIN data_dict_item item ON tags.tid = item.id
		INNER JOIN data_dict dict ON dict.id = item.dictid
		WHERE
		ck.check_id = #{userId}
		<if test="id!=null">
			and c.id = #{id}
		</if>
		<if test="title!=null and title!=''">
			and c.title like concat(concat('%',#{title},'%'))
		</if>
		<if test="status!=null">
			and a.status = #{status}
		</if>
		<if test="quantity!=null and quantity == 0">
			and c.label_feedback = 0
		</if>
		<if test="quantity!=null and quantity == 1">
			and c.label_feedback > 0
		</if>
		<if test="tagLists!=null and tagLists!=''">
			and item.id in
			<foreach collection="tagLists" open="(" separator="," item="id" close=")">
				#{id}
			</foreach>
			GROUP BY c.id,name,u2.position,status,applicationId
			<if test="count!=null and count==1">
				HAVING
				count(c.id) > 0
			</if>
			<if test="count!=null and count>1">
				HAVING
				count(c.id) = #{count}
			</if>
		</if>
		order by c.id desc
	</select>

	<select id="getApplicationStatus" resultType="com.nbclass.activity.model.Application">
		select id,status from application where content_id = #{id}
	</select>

	<update id="updateCheck">
		update `check` set
		<if test="applicationId!=null and checkId!=null">
			status = #{status}
		</if>
		where application_id = #{applicationId} and check_id = #{checkId}
	</update>

	<select id="getContentId" resultType="java.lang.Long">
		select content_id from application where id = #{applicationId}
	</select>

	<update id="updateContentRelease">
		update content set
		<if test="release!=null and release == 1">
			online_time = null,
		</if>
		<if test="release!=null and release == 2">
			online_time = now(),
		</if>
		<if test="contentId!=null and release!=null and visibility!=null">
			`release` = #{release},visibility = #{visibility}
		</if>
		where id = #{contentId}
	</update>

	<update id="updateApplication">
		update application set
		<if test="id!=null and status!=null">
			status = #{status}
		</if>
		where id = #{id}
	</update>

	<select id="getApplication" resultType="com.nbclass.activity.model.Application">
		select * from application where content_id = #{contentId}
	</select>


	<select id="getCensus" resultType="com.nbclass.activity.model.Census">
		SELECT
			DISTINCT item.id,
			count(c.id) AS count
		FROM
			data_dict_item item
			LEFT JOIN content_tags tags ON item.id = tags.tid
			LEFT JOIN content c ON c.id = tags.cid and c.online_time is not null
		WHERE
			item.dictid = 26
		GROUP BY
			item.id,c.id
			<if test="type!=null and type==1">
				and YEARWEEK( date_format(c.online_time, '%Y-%m-%d' ), 1 ) = YEARWEEK(now())
			</if>
			<if test="type!=null and type==2">
				AND DATE_FORMAT( c.online_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ), '%Y%m' )
			</if>
			<if test="type!=null and type==3">
				AND QUARTER(c.online_time)=QUARTER(now())
			</if>
			<if test="type!=null and type==4">
				AND YEAR(c.online_time)=YEAR(NOW())
			</if>
	</select>

</mapper>
