<?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.pcloud.book.timecontrol.mapper.TimeControlTaskSubscribeMapper" >
  <resultMap id="BaseResultMap" type="com.pcloud.book.timecontrol.entity.TimeControlTaskSubscribe" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="wx_user_id" property="wxUserId" jdbcType="VARCHAR" />
    <result column="robot_wx_id" property="robotWxId" jdbcType="VARCHAR" />
    <result column="book_id" property="bookId" jdbcType="INTEGER" />
    <result column="task_id" property="taskId" jdbcType="INTEGER" />
    <result column="state" property="state" jdbcType="INTEGER" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
  </resultMap>

  <insert id="subscribeTask" parameterType="com.pcloud.book.timecontrol.entity.TimeControlTaskSubscribe" useGeneratedKeys="true" keyProperty="id">
    insert into time_control_task_subscribe (wx_user_id, book_id, task_id, state, create_time, update_time, robot_wx_id)
    values (#{wxUserId}, #{bookId}, #{taskId}, #{state}, now(), now(), #{robotWxId})
  </insert>

  <update id="subscribeTaskExist">
    UPDATE time_control_task_subscribe set  state = 1, update_time = now()
    where id = #{id}
  </update>

  <update id="unSubscribeTask">
    UPDATE time_control_task_subscribe set state = #{state}, update_time = now()
    where id = #{id}
  </update>

  <update id="unSubscribeTaskByTaskId">
    UPDATE time_control_task_subscribe set state = 0, update_time = now()
    where task_id = #{taskId}
  </update>

  <select id="getSubscribe" resultMap="BaseResultMap">
    select wx_user_id, book_id, task_id, state, robot_wx_id, id
    from time_control_task_subscribe
    where wx_user_id = #{wxUserId}
    <if test="bookId != null">
    and book_id = #{bookId}
    </if>
    and task_id = #{taskId}
  </select>

   <select id="countTaskSubscribe" resultType="java.lang.Integer">
     SELECT count(1) FROM time_control_task_subscribe
     WHERE book_id = #{bookId}
     AND task_id= #{taskId}
     AND state IN (1,2)
   </select>

  <select id="getById" resultMap="BaseResultMap">
    select wx_user_id, book_id, task_id, state, create_time, update_time, robot_wx_id, id
    from time_control_task_subscribe WHERE id = #{subscribeId}
  </select>

  <update id="completedTaskById">
    UPDATE time_control_task_subscribe set state = 2, update_time = now()
    where id = #{subscribeId}
  </update>

  <select id="getSubscribeStatics" parameterType="Integer" resultType="com.pcloud.book.timecontrol.dto.TaskProgressDTO">
    SELECT
        count(1) subscribeCount,
        sum(IF(state = 2, 1, 0)) finishCount
    FROM
        time_control_task_subscribe
    WHERE
        task_id = #{taskId}
    AND state IN (1, 2)
  </select>
</mapper>