<?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="kr.co.jinwoosi.clfd.clfd.dgns.mapper.DgnsMapper">
    <insert id="insert" parameterType="dgns">
        <selectKey keyProperty="dgnsId" resultType="java.lang.Long" order="BEFORE" >
            select DGNS_ID_SEQ.NEXTVAL from DUAL
        </selectKey>
        INSERT INTO CF_DGNS (
            DGNS_ID, USER_ID, SK_TY_ID, OD_TOTAL_SCORE, SR_TOTAL_SCORE, PN_TOTAL_SCORE, WT_TOTAL_SCORE, DGNS_CNT,
            OD_DGNS_DTL_ID, SR_DGNS_DTL_ID, PN_DGNS_DTL_ID, WT_DGNS_DTL_ID,
            REG_ID, REG_DT, REC_ST
        ) VALUES (
            #{dgnsId}, #{userId}, #{skTyId}, #{odTotalScore}, #{srTotalScore}, #{pnTotalScore}, #{wtTotalScore}, #{dgnsCnt},
            #{odDgnsDtlId}, #{srDgnsDtlId}, #{pnDgnsDtlId}, #{wtDgnsDtlId},
            #{regId}, SYSDATE, 'Y'
        )
    </insert>

    <select id="select" parameterType="dgnsSearch" resultType="dgns">
        SELECT *
        FROM CF_DGNS
        WHERE DGNS_ID = #{dgnsId}
        <if test="userId != null" > AND USER_ID = #{userId} </if>
    </select>
    
    <select id="selectList" parameterType="dgnsSearch" resultType="dgns">
        SELECT *
        FROM (
            SELECT ROWNUM RNUM , LIST.*
            FROM (
                SELECT *
                FROM CF_DGNS
                WHERE DEL_DT IS NULL
                    <if test="dgnsId != null" > AND DGNS_ID = #{dgnsId} </if>
                    <if test="recSt != null" > AND REC_ST = #{recSt} </if>
                    <if test="userId != null" > AND USER_ID = #{userId} </if>
                    <if test="skTyId != null" > AND SK_TY_ID = #{skTyId} </if>
                <if test="!empty(sort) and !empty(sortOrd)">
                ORDER BY ${sort} ${sortOrd}
                </if>
            ) LIST
        )
        <if test="pagingYn == true" >
            <![CDATA[
			WHERE RNUM > #{start} AND RNUM <= #{start} + #{length}
		    ]]>
        </if>
    </select>

    <select id="count" parameterType="dgnsSearch" resultType="java.lang.Integer">
        select
            COUNT(*)
        from
            CF_DGNS
        WHERE DEL_DT IS NULL
        <if test="recSt != null" > AND REC_ST = #{recSt} </if>
        <if test="userId != null" > AND USER_ID = #{userId} </if>
        <if test="skTyId != null" > AND SK_TY_ID = #{skTyId} </if>
    </select>

    <select id="skinTypeStats"  parameterType="dgnsSearch" resultType="dgnsSearch">
        SELECT COUNT(CD.SK_TY_ID) AS SK_TY_COUNT, SK_TY_CD
        FROM CF_SK_TY CST
            LEFT JOIN (SELECT SK_TY_ID FROM CF_DGNS WHERE DGNS_ID IN (SELECT MAX(DGNS_ID) FROM CF_DGNS GROUP BY USER_ID)) CD
            ON CST.SK_TY_ID = CD.SK_TY_ID
        GROUP BY SK_TY_CD
        ORDER BY SK_TY_CD
    </select>

</mapper>
