<?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.microservices.dms.resourceLibrary.mapper.TaskResourceLibraryMapper">

    <insert id="insertClicker" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="com.microservices.dms.resourceLibrary.domain.Clicker">
        INSERT INTO clickers
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != clickType and '' != clickType">
                click_type,
            </if>
            <if test="null != clickId ">
                click_id,
            </if>
            <if test="null != userId ">
                user_id,
            </if>
            <if test="null != createdAt ">
                created_at,
            </if>
            <if test="null != extInfo and '' != extInfo">
                ext_info
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != clickType and '' != clickType">
                #{clickType},
            </if>
            <if test="null != clickId ">
                #{clickId},
            </if>
            <if test="null != userId ">
                #{userId},
            </if>
            <if test="null != createdAt ">
                #{createdAt},
            </if>
            <if test="null != extInfo and '' != extInfo">
                #{extInfo}
            </if>
        </trim>
    </insert>
    <select id="countClicker" resultType="java.lang.Long">
        select count(*) from clickers c
        inner join achievements a ON  a.id = c.click_id
        <where>
            and a.status='1'
            <if test="null != clickType and '' != clickType">
                and c.click_type = #{clickType}
            </if>
            and a.source='4'
        </where>
    </select>

    <select id="countClickerSimple" resultType="java.lang.Long">
        select count(*) from clickers c
        inner join expert_resource_library erl on c.click_id = erl.id
        <where>
            and erl.status='1'
            <if test="null != clickType and '' != clickType">
              and  c.click_type = #{clickType}
            </if>
        </where>
    </select>

    <insert id="insertSearcher" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="com.microservices.dms.resourceLibrary.domain.Searcher">
        INSERT INTO searchers
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != searchType and '' != searchType">
                search_type,
            </if>
            <if test="null != searchId ">
                search_id,
            </if>
            <if test="null != userId ">
                user_id,
            </if>
            <if test="null != createdAt ">
                created_at,
            </if>
            <if test="null != extInfo and '' != extInfo">
                ext_info
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != searchType and '' != searchType">
                #{searchType},
            </if>
            <if test="null != searchId ">
                #{searchId},
            </if>
            <if test="null != userId ">
                #{userId},
            </if>
            <if test="null != createdAt ">
                #{createdAt},
            </if>
            <if test="null != extInfo and '' != extInfo">
                #{extInfo}
            </if>
        </trim>
    </insert>

    <insert id="insertDownloader" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="com.microservices.dms.resourceLibrary.domain.Downloader">
        INSERT INTO downloads
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != downloadType and '' != downloadType">
                download_type,
            </if>
            <if test="null != downloadId ">
                download_id,
            </if>
            <if test="null != userId ">
                user_id,
            </if>
            <if test="null != createdAt ">
                created_at,
            </if>
            <if test="null != extInfo and '' != extInfo">
                ext_info
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != downloadType and '' != downloadType">
                #{downloadType},
            </if>
            <if test="null != downloadId ">
                #{downloadId},
            </if>
            <if test="null != userId ">
                #{userId},
            </if>
            <if test="null != createdAt ">
                #{createdAt},
            </if>
            <if test="null != extInfo and '' != extInfo">
                #{extInfo}
            </if>
        </trim>
    </insert>

    <insert id="insertFavorite" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="com.microservices.dms.resourceLibrary.domain.Favorite">
        INSERT INTO favorites
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != favoriteType and '' != favoriteType">
                favorite_type,
            </if>
            <if test="null != favoriteId ">
                favorite_id,
            </if>
            <if test="null != userId ">
                user_id,
            </if>
            <if test="null != createdAt ">
                created_at,
            </if>
            <if test="null != extInfo and '' != extInfo">
                ext_info
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != favoriteType and '' != favoriteType">
                #{favoriteType},
            </if>
            <if test="null != favoriteId ">
                #{favoriteId},
            </if>
            <if test="null != userId ">
                #{userId},
            </if>
            <if test="null != createdAt ">
                #{createdAt},
            </if>
            <if test="null != extInfo and '' != extInfo">
                #{extInfo}
            </if>
        </trim>
    </insert>

    <insert id="insertWatcher" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="com.microservices.dms.resourceLibrary.domain.Favorite">
        INSERT INTO watchers
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != watchableType and '' != watchableType">
                watchable_type,
            </if>
            <if test="null != watchableId ">
                watchable_id,
            </if>
            <if test="null != userId ">
                user_id,
            </if>
            <if test="null != createdAt ">
                created_at,
            </if>
            <if test="null != extInfo and '' != extInfo">
                ext_info
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != watchableType and '' != watchableType">
                #{watchableType},
            </if>
            <if test="null != watchableId ">
                #{watchableId},
            </if>
            <if test="null != userId ">
                #{userId},
            </if>
            <if test="null != createdAt ">
                #{createdAt},
            </if>
            <if test="null != extInfo and '' != extInfo">
                #{extInfo}
            </if>
        </trim>
    </insert>

    <select id="selectClickerCondition" resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select click_type as itemType, click_id as itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from clickers
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND click_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND click_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="selectVisitCondition" resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select visitable_type as itemType, visitable_id itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from visit_actions
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND visitable_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND visitable_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="selectSearcherCondition" resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select search_type as itemType, search_id as itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from searchers
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND search_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND search_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="selectDownloaderCondition"
            resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select download_type as itemType, download_id as itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from downloads
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND download_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND download_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="selectWatcherCondition" resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select watchable_type as itemType, watchable_id as itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from watchers
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND watchable_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND watchable_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="selectTaskJournalsCondition"
            resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select journalized_type as itemType, journalized_id as itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from task_journals
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND journalized_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND journalized_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="selectPapersCondition" resultType="com.microservices.dms.resourceLibrary.domain.vo.UserActionDataVo">
        select task_id as itemId, user_id as userId, created_at as createAt,
        (select login from users where id = user_id) as userName from papers
        <where>
            <if test="itemId != null">
                AND task_id = #{itemId}
            </if>
        </where>
    </select>

    <select id="selectTaskListCondition" resultType="com.microservices.dms.resourceLibrary.domain.vo.TaskListVo">
        select name,id,bounty,category_id,DATEDIFF(expired_at, published_at) as totalTaskDays,
        (select c.name from categories c where id = category_id) as categoryName,visits
        from tasks
        <where>
            <if test="categoryId != null">
                AND category_id = #{categoryId}
            </if>
            <if test="name != null and name.trim() != ''">
                AND `name` like concat('%', #{name}, '%')
            </if>
        </where>
    </select>

    <select id="countClickerCondition" resultType="long">
        select count(*) from clickers
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND click_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND click_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="countVisitCondition" resultType="long">
        select count(*) from visit_actions
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND visitable_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND visitable_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="countSearcherCondition" resultType="long">
        select count(*) from searchers
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND search_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND search_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="countDownloaderCondition" resultType="long">
        select count(*) from downloads
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND download_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND download_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="countWatcherCondition" resultType="long">
        select count(*) from watchers
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND watchable_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND watchable_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="countTaskJournalsCondition" resultType="long">
        select count(*) from task_journals
        <where>
            <if test="itemType != null and itemType.trim() != ''">
                AND journalized_type = #{itemType}
            </if>
            <if test="itemId != null">
                AND journalized_id = #{itemId}
            </if>
        </where>
    </select>
    <select id="countPapersCondition" resultType="long">
        select count(*) from papers
        <where>
            <if test="itemId != null">
                AND task_id = #{itemId}
            </if>
        </where>
    </select>


    <resultMap type="TaskResourceLibrary" id="TaskResourceLibraryResult">
        <result property="id" column="id"/>
        <result property="taskId" column="task_id"/>
        <result property="paperId" column="paper_id"/>
        <result property="taskName" column="task_name"/>
        <result property="taskDomain" column="task_domain"/>
        <result property="taskAmount" column="task_amount"/>
        <result property="submissionName" column="submission_name"/>
        <result property="submissionDate" column="submission_date"/>
        <result property="submitterName" column="submitter_name"/>
        <result property="submissionType" column="submission_type"/>
        <result property="submissionOrganization" column="submission_organization"/>
        <result property="submissionSummary" column="submission_summary"/>
        <result property="releaseDetails" column="release_details"/>
        <result property="contactName" column="contact_name"/>
        <result property="contactPhone" column="contact_phone"/>
        <result property="isTransferredToResultsLibrary" column="is_transferred_to_results_library"/>
        <result property="transferToResultsDate" column="transfer_to_results_date"/>
        <result property="isSelectedResult" column="is_selected_result"/>
        <result property="imageUrl" column="image_url"/>
        <result property="attachmentUrl" column="attachment_url"/>
    </resultMap>

    <sql id="selectTaskResourceLibraryVo">
        select id,
               task_id,
               paper_id,
               task_name,
               task_domain,
               task_amount,
               submission_name,
               submission_date,
               submitter_name,
               submission_type,
               submission_organization,
               submission_summary,
               release_details,
               contact_name,
               contact_phone,
               is_transferred_to_results_library,
               transfer_to_results_date,
               is_selected_result,
               image_url,
               attachment_url
        from task_resource_library
    </sql>

    <select id="selectTaskResourceLibraryList" parameterType="TaskResourceLibrary"
            resultType="com.microservices.dms.resourceLibrary.domain.TaskResourceLibrary">
        select ts.id,
        t.id as task_id,
        pd.paper_id as paper_id,
        t.name as task_name,
        IFNULL(ts.task_domain, t.category_id) as task_domain,
        t.bounty as task_total_amount,
        ROUND(t.bounty / (select count(1) from papers where status = 2 and t.id = task_id),2) as task_amount,
        p.number as submission_name,
        p.created_at as submission_date,
        (select u.login from users u where u.id = p.user_id) as submitter_name,
        submission_type,
        submission_organization,
        IFNULL(ts.submission_summary,pd.content) as submission_summary,
        IFNULL(ts.release_details,pd.content) as release_details,
        t.contact_name,
        t.contact_phone,
        is_transferred_to_results_library,
        transfer_to_results_date,
        is_selected_result,
        image_url,
        attachment_url,
        t.expert_review,
        create_by,
        create_time,
        update_by,
        update_time
        from tasks t
        join (select * from papers where status = 2) p on t.id = p.task_id
        join paper_details pd on p.id = pd.paper_id
        left join task_resource_library ts on p.id = ts.paper_id
        <where>

            <if test="taskName != null  and taskName != ''">and t.name like concat('%', #{taskName}, '%')</if>
            <if test="taskDomain != null  and taskDomain != ''">and task_domain = #{taskDomain}</if>
            <if test="taskAmount != null ">and task_amount = #{taskAmount}</if>
            <if test="submissionName != null  and submissionName != ''">and submission_name like concat('%',
                #{submissionName}, '%')
            </if>
            <if test="submissionDate != null ">and submission_date = #{submissionDate}</if>
            <if test="submitterName != null  and submitterName != ''">and submitter_name like concat('%',
                #{submitterName}, '%')
            </if>
            <if test="submissionType != null  and submissionType != ''">and submission_type = #{submissionType}</if>
            <if test="submissionOrganization != null  and submissionOrganization != ''">and submission_organization =
                #{submissionOrganization}
            </if>
            <if test="submissionSummary != null  and submissionSummary != ''">and submission_summary =
                #{submissionSummary}
            </if>
            <if test="releaseDetails != null  and releaseDetails != ''">and release_details = #{releaseDetails}</if>
            <if test="contactName != null  and contactName != ''">and t.contact_name like concat('%', #{contactName},
                '%')
            </if>
            <if test="contactPhone != null  and contactPhone != ''">and t.contact_phone = #{contactPhone}</if>
            <if test="isTransferredToResultsLibrary != null ">and is_transferred_to_results_library =
                #{isTransferredToResultsLibrary}
            </if>
            <if test="transferToResultsDate != null ">and transfer_to_results_date = #{transferToResultsDate}</if>
            <if test="isSelectedResult != null ">and is_selected_result = #{isSelectedResult}</if>
            <if test="imageUrl != null  and imageUrl != ''">and image_url = #{imageUrl}</if>
            <if test="attachmentUrl != null  and attachmentUrl != ''">and attachment_url = #{attachmentUrl}</if>
        </where>
        order by is_transferred_to_results_library,create_time desc,submission_date desc
    </select>

    <select id="selectTaskResourceLibraryById" parameterType="Long" resultMap="TaskResourceLibraryResult">
        <include refid="selectTaskResourceLibraryVo"/>
        where id = #{id}
    </select>

    <select id="getAttachments" resultType="com.microservices.dms.resourceLibrary.domain.vo.KeyValVo">
        select b.file_name as k, b.id as v
        from paper_details pd
                 join busi_attachments b on pd.files = b.id
        where pd.paper_id = #{id}
    </select>

    <select id="getTotalTasks" resultType="java.lang.Long">
        select count(distinct task_id)
        from tasks t
                 join (select * from papers where status = 2) p on t.id = p.task_id
    </select>

    <select id="getConvertedTaskAmount" resultType="java.lang.Double">
        select IFNULL(SUM(task_amount), 0) from task_resource_library where is_transferred_to_results_library = 1
    </select>

    <select id="getConvertedTaskAmount2" resultType="java.lang.Double">
        select IFNULL(SUM(t.task_amount), 0) from achievements a
        inner join task_resource_library t on a.source_id = t.id
        where a.source='2' and a.status= '1'
    </select>

    <select id="getConvertedTasksCount" resultType="java.lang.Long">
        select count(*)
        from tasks t
                 join (select distinct task_id from papers where status = 2) p on t.id = p.task_id
                 join task_resource_library on t.id = task_resource_library.task_id
        where is_transferred_to_results_library = 1
    </select>

    <select id="getTaskAmount" resultType="java.lang.Double">
        select IFNULL(sum(t.bounty), 0)
        from tasks t
                 join (select distinct task_id from papers where status = 2) p on t.id = p.task_id
    </select>

    <select id="getReviewTaskCount" resultType="java.lang.Long">
        select count(*)
        from tasks t
                 join (select * from papers where status = 2) p on t.id = p.task_id
        where expert_review = 1
    </select>

    <insert id="insertTaskResourceLibrary" parameterType="TaskResourceLibrary" useGeneratedKeys="true" keyProperty="id">
        insert into task_resource_library
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="taskId != null">task_id,</if>
            <if test="paperId != null">paper_id,</if>
            <if test="taskName != null">task_name,</if>
            <if test="taskDomain != null">task_domain,</if>
            <if test="taskAmount != null">task_amount,</if>
            <if test="submissionName != null">submission_name,</if>
            <if test="submissionDate != null">submission_date,</if>
            <if test="submitterName != null">submitter_name,</if>
            <if test="submissionType != null">submission_type,</if>
            <if test="submissionOrganization != null">submission_organization,</if>
            <if test="submissionSummary != null">submission_summary,</if>
            <if test="releaseDetails != null">release_details,</if>
            <if test="contactName != null">contact_name,</if>
            <if test="contactPhone != null">contact_phone,</if>
            <if test="isTransferredToResultsLibrary != null">is_transferred_to_results_library,</if>
            <if test="transferToResultsDate != null">transfer_to_results_date,</if>
            <if test="isSelectedResult != null">is_selected_result,</if>
            <if test="imageUrl != null">image_url,</if>
            <if test="attachmentUrl != null">attachment_url,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="taskId != null">#{taskId},</if>
            <if test="paperId != null">#{paperId},</if>
            <if test="taskName != null">#{taskName},</if>
            <if test="taskDomain != null">#{taskDomain},</if>
            <if test="taskAmount != null">#{taskAmount},</if>
            <if test="submissionName != null">#{submissionName},</if>
            <if test="submissionDate != null">#{submissionDate},</if>
            <if test="submitterName != null">#{submitterName},</if>
            <if test="submissionType != null">#{submissionType},</if>
            <if test="submissionOrganization != null">#{submissionOrganization},</if>
            <if test="submissionSummary != null">#{submissionSummary},</if>
            <if test="releaseDetails != null">#{releaseDetails},</if>
            <if test="contactName != null">#{contactName},</if>
            <if test="contactPhone != null">#{contactPhone},</if>
            <if test="isTransferredToResultsLibrary != null">#{isTransferredToResultsLibrary},</if>
            <if test="transferToResultsDate != null">#{transferToResultsDate},</if>
            <if test="isSelectedResult != null">#{isSelectedResult},</if>
            <if test="imageUrl != null">#{imageUrl},</if>
            <if test="attachmentUrl != null">#{attachmentUrl},</if>
        </trim>
    </insert>

    <update id="updateTaskResourceLibrary" parameterType="TaskResourceLibrary">
        update task_resource_library
        <trim prefix="SET" suffixOverrides=",">
            <if test="taskId != null">task_id = #{taskId},</if>
            <if test="paperId != null">paper_id = #{paperId},</if>
            <if test="taskName != null">task_name = #{taskName},</if>
            <if test="taskDomain != null">task_domain = #{taskDomain},</if>
            <if test="taskAmount != null">task_amount = #{taskAmount},</if>
            <if test="submissionName != null">submission_name = #{submissionName},</if>
            <if test="submissionDate != null">submission_date = #{submissionDate},</if>
            <if test="submitterName != null">submitter_name = #{submitterName},</if>
            <if test="submissionType != null">submission_type = #{submissionType},</if>
            <if test="submissionOrganization != null">submission_organization = #{submissionOrganization},</if>
            <if test="submissionSummary != null">submission_summary = #{submissionSummary},</if>
            <if test="releaseDetails != null">release_details = #{releaseDetails},</if>
            <if test="contactName != null">contact_name = #{contactName},</if>
            <if test="contactPhone != null">contact_phone = #{contactPhone},</if>
            <if test="isTransferredToResultsLibrary != null">is_transferred_to_results_library =
                #{isTransferredToResultsLibrary},
            </if>
            <if test="transferToResultsDate != null">transfer_to_results_date = #{transferToResultsDate},</if>
            <if test="isSelectedResult != null">is_selected_result = #{isSelectedResult},</if>
            <if test="imageUrl != null">image_url = #{imageUrl},</if>
            <if test="attachmentUrl != null">attachment_url = #{attachmentUrl},</if>
        </trim>
        where id = #{id}
    </update>

    <delete id="deleteTaskResourceLibraryById" parameterType="Long">
        delete
        from task_resource_library
        where id = #{id}
    </delete>

    <delete id="deleteTaskResourceLibraryByIds" parameterType="String">
        delete from task_resource_library where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>
    <delete id="delFavorite">
        delete
        from favorites
        where user_id = #{userId}
          and favorite_id = #{favoriteId}
          and favorite_type = #{favoriteType}
    </delete>

    <delete id="delWatcher">
        delete
        from watchers
        where user_id = #{userId}
          and watchable_id = #{watchableId}
          and watchable_type = #{watchableType}
    </delete>
</mapper>
