<?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.style24.core.biz.dao.TscCouponDao">
    <!-- 쿠폰리스트 조회 -->
    <select id="getCouponList" parameterType="Coupon" resultType="Coupon">
        /* TscCoupon.getCouponList */
        SELECT Z.*
        FROM(
              SELECT  @rownum := @rownum + 1 AS RNUM
                    , A.*
              FROM (
                   SELECT SITE_CD
                       , CPN_ID
                       , CPN_NM
                       , CPN_DESC
                       , CPN_TYPE
                       , CPN_STAT
                       , DC_WAY
                       , DC_PVAL
                       , DC_MVAL
                       , MAX_DC_AMT
                       , PD_GB
                       , AVAIL_STDT
                       , AVAIL_EDDT
                       , AVAIL_DAYS
                       , FN_GET_USER_NM(REG_NO) AS REG_NM
                       , REG_DT
                       , (SELECT COUNT(CUST_CPN_SQ) FROM TB_CUST_COUPON WHERE 1=1 AND CPN_ID = C.CPN_ID) AS ISSUE_CNT
                       , (SELECT COUNT(USED_DT) FROM TB_CUST_COUPON WHERE 1=1 AND CPN_ID = C.CPN_ID) AS USE_CNT
                   FROM	TB_COUPON C JOIN ( SELECT @rownum := 0) R
                   WHERE	1=1
                 <if test="siteCd != null and siteCd != ''">
                     AND SITE_CD = #{siteCd}
                 </if>
                 <if test="cpnId != null and cpnId != ''">
                     AND CPN_ID = #{cpnId}
                 </if>
                 <if test="cpnType != null and cpnType != ''">
                     AND CPN_TYPE = #{cpnType}
                 </if>
                 <if test="regNm != null and regNm != ''">
                     AND REG_NO IN (
                         SELECT USER_NO
                         FROM   TB_USER
                         WHERE  1=1
                         AND    USER_NM = #{regNm}
                     )
                 </if>
                 <if test="regNo != null and regNo != ''">
                     AND REG_NO = #{regNo}
                 </if>
                 <if test="dcWay != null and dcWay != ''">
                     AND DC_WAY = #{dcWay}
                 </if>
                 <if test="cpnNm != null and cpnNm != ''">
                     AND CPN_NM LIKE CONCAT('%',UPPER(#{cpnNm}),'%')
                 </if>
                 <if test="pdGb != null and pdGb != ''">
                     AND PD_GB = #{pdGb}
                 </if>
                 <if test="availStdt != null and availStdt != ''">
                     AND AVAIL_EDDT >= DATE_FORMAT(#{availStdt} , '%Y-%m-%d %H:%i:%S')
                 </if>
                 <if test="availEddt != null and availEddt != ''">
                     AND AVAIL_STDT <![CDATA[ <= ]]> DATE_FORMAT(DATE_ADD(#{availEddt}, INTERVAL 1 DAY), '%Y-%m-%d %H:%i:%S')
                 </if>
                 <if test='chkExcep == "Y"'>
                     AND CPN_STAT <![CDATA[ <> ]]> 'G232_13'
                 </if>
                 ORDER BY C.REG_DT DESC
        <include refid="getListPagingCondition_sql"/>
    </select>

    <sql id="getListPagingCondition_sql">
        <choose>
            <when test="pageable != null">
                ) A
                )Z
                WHERE RNUM BETWEEN  #{pageable.startRow} AND #{pageable.endRow}
            </when>
            <otherwise>
                ) A
                )Z
            </otherwise>
        </choose>
    </sql>

    <!-- 쿠폰 리스트 카운트 조회-->
    <select id="getCouponListCnt" parameterType="Coupon" resultType="int">
        /* TscCoupon.getCouponListCnt */
        SELECT COUNT(1)
        FROM TB_COUPON
        WHERE 1=1
        <if test="siteCd != null and siteCd != ''">
            AND SITE_CD = #{siteCd}
        </if>
        <if test="cpnId != null and cpnId != ''">
            AND CPN_ID = #{cpnId}
        </if>
        <if test="cpnType != null and cpnType != ''">
            AND CPN_TYPE = #{cpnType}
        </if>
        <if test="regNm != null and regNm != ''">
            AND REG_NO IN (
                 SELECT USER_NO
                 FROM   TB_USER
                 WHERE  1=1
                 AND    USER_NM = #{regNm}
            )
        </if>
        <if test="regNo != null and regNo != ''">
            AND REG_NO = #{regNo}
        </if>
        <if test="dcWay != null and dcWay != ''">
            AND DC_WAY = #{dcWay}
        </if>
        <if test="cpnNm != null and cpnNm != ''">
            AND CPN_NM LIKE CONCAT('%',UPPER(#{cpnNm}),'%')
        </if>
        <if test="pdGb != null and pdGb != ''">
            AND PD_GB = #{pdGb}
        </if>
        <if test="availStdt != null and availStdt != ''">
            AND AVAIL_EDDT >= DATE_FORMAT(#{availStdt} , '%Y-%m-%d %H:%i:%S')
        </if>
        <if test="availEddt != null and availEddt != ''">
            AND AVAIL_STDT <![CDATA[ <= ]]> DATE_FORMAT(DATE_ADD(#{availEddt}, INTERVAL 1 DAY), '%Y-%m-%d %H:%i:%S')
        </if>
        <if test='chkExcep == "Y"'>
            AND CPN_STAT <![CDATA[ <> ]]> 'G232_13'
        </if>
    </select>

    <!-- 쿠폰 발급 개수 조회 -->
    <select id="getCouponIssueCnt" parameterType="Integer" resultType="int">
        /* TscCoupon.getCouponIssueCnt*/
        SELECT COUNT(1)
        FROM TB_CUST_COUPON
        WHERE CPN_ID = #{cpnId}
    </select>

    <!-- 쿠폰 상세 조회-->
    <select id="getCouponDetail" parameterType="Integer" resultType="Coupon">
        /* TscCoupon.getCouponDetail */
        SELECT B.CPN_ID
        , B.CPN_NM
        , B.CPN_DESC
        , B.SITE_CD
        , B.AF_LINK_CD
        , B.CPN_TYPE
        , B.APPLY_SCOPE
        , B.DC_WAY
        , B.DC_PVAL
        , B.DC_MVAL
        , B.DC_AVAL
        , B.MAX_DC_AMT
        , B.PD_GB
        , B.AVAIL_STDT
        , B.AVAIL_EDDT
        , B.AVAIL_DAYS
        , B.CUST_PUB_LIMIT_QTY
        , B.TOT_PUB_LIMIT_QTY
        , B.ONE_PUB_QTY
        , B.DN_GB
        , B.DOWN_STDT
        , B.DOWN_EDDT
        , B.BUY_LIMIT_AMT
        , B.PLAN_SQ
        , B.REISSUANCE
        , B.CPN_STAT
        , B.END_ALIM_YN
        , B.FIRST_ORD_YN
        , B.DOWN_ABL_YN
        , B.DC_CD_GB
        , B.CUST_JOIN_STDT
        , B.CUST_JOIN_EDDT
        , B.BUY_STDT
        , B.BUY_EDDT
        , B.NEW_CUST_YN
        , (SELECT AF_CHANNEL
        FROM TB_AF_LINK A
        WHERE A.AF_LINK_CD = B.AF_LINK_CD) AS AF_CHANNEL
        , RC.RD_CPN_NM AS RD_CPN_NM
        FROM TB_COUPON B
        LEFT OUTER JOIN (SELECT CPN_ID
        , RD_CPN_NM
        FROM TB_RANDOM_COUPON
        GROUP BY CPN_ID, RD_CPN_NM) RC
        ON B.CPN_ID = RC.CPN_ID
        AND B.DC_CD_GB = 'G233_10'		<!-- 시리얼 유형일 경우에만 랜덤쿠폰 검색 검색 -->
        WHERE B.CPN_ID = #{value}
    </select>

    <!-- 쿠폰 적용대상 - 공급처 조회 -->
    <select id="getCouponRefvalSupplyCompList" parameterType="CouponRefval" resultType="CouponRefval">
        /* TscCoupon.getCouponRefvalSupplyCompList */
        SELECT B.SUPPLY_COMP_CD
             , B.SUPPLY_COMP_NM
             , A.CPN_REFVAL_SQ
             , A.DEL_YN
        FROM TB_COUPON_REFVAL A
                 INNER JOIN TB_SUPPLY_COMPANY B ON A.REF_VAL = B.SUPPLY_COMP_CD
        WHERE A.CPN_ID = #{cpnId}
          AND A.CPN_TARGET = #{cpnTarget}
          AND A.DEL_YN = 'N'
        ORDER BY A.CPN_REFVAL_SQ DESC
    </select>

    <!-- 쿠폰 적용대상 조회 - 제외/적용 상품 -->
    <select id="getCouponRefvalGoodsList" parameterType="CouponRefval" resultType="CouponRefval">
        /* TscCoupon.getCouponRefvalGoodsList */
        SELECT FN_GET_CODE_NM('G073',B.GOODS_GB) AS GOODS_GB
             , B.GOODS_CD
             , B.GOODS_NM
             , C.BRAND_ENM
             , A.CPN_REFVAL_SQ
             , A.DEL_YN
        FROM TB_COUPON_REFVAL A
                 INNER JOIN TB_GOODS B ON A.REF_VAL = B.GOODS_CD
                 INNER JOIN TB_BRAND C ON B.BRAND_CD = C.BRAND_CD
        WHERE A.CPN_ID = #{cpnId}
          AND A.CPN_TARGET = #{cpnTarget}
          AND A.DEL_YN = 'N'
        ORDER BY A.CPN_REFVAL_SQ DESC
    </select>

    <!-- 쿠폰적용대상 - 카테고리 조회 -->
    <select id="getCouponRefvalCategoryList" parameterType="CouponRefval" resultType="CouponRefval">
        /* TscCoupon.getCouponRefvalCategoryList */
        SELECT B.CATE_GB
             , A.REF_VAL AS CATE_NO
             , B.FULL_CATE_NM 					AS CATE_NM
             , B.SITE_CD
             , A.REF_FORMAL_GB					AS FORMAL_GB
             , A.REF_BRAND_CD					AS BRAND_CD
             , A.CPN_REFVAL_SQ
             , A.DEL_YN
        FROM TB_COUPON_REFVAL A
                 INNER JOIN TB_CATE_4SRCH B ON A.REF_VAL = B.LEAF_CATE_NO
        WHERE A.CPN_ID = #{cpnId}
          AND A.CPN_TARGET = #{cpnTarget}
          AND A.DEL_YN = 'N'
        ORDER BY A.CPN_REFVAL_SQ DESC
    </select>

    <!-- 쿠폰 적용대상 조회 - 브랜드 -->
    <select id="getCouponRefvalBrandList" parameterType="CouponRefval" resultType="CouponRefval">
        /* TscCoupon.getCouponRefvalExceptGoodsList */
        SELECT B.BRAND_CD
             , B.BRAND_ENM
             , A.CPN_REFVAL_SQ
             , A.DEL_YN
        FROM TB_COUPON_REFVAL A
                 INNER JOIN TB_BRAND B ON A.REF_VAL = B.BRAND_CD
        WHERE A.CPN_ID = #{cpnId}
          AND A.CPN_TARGET = #{cpnTarget}
          AND A.DEL_YN = 'N'
        ORDER BY A.CPN_REFVAL_SQ DESC
    </select>

    <!-- 쿠폰 입점업체 분담율 조회-->
    <select id="getCouponBurdenList" parameterType="int" resultType="CouponBurden">
        /* TscCoupon.getCouponBurdenList */
        SELECT A.SUPPLY_COMP_CD
             , (SELECT SUPPLY_COMP_NM FROM TB_SUPPLY_COMPANY WHERE 1=1 AND SUPPLY_COMP_CD = A.SUPPLY_COMP_CD) AS SUPPLY_COMP_NM
             , A.BURDEN_RATE
             , A.BURDEN_RATE
             , A.DEL_YN
             , A.CPN_ID
        FROM TB_COUPON_BURDEN A
        WHERE A.CPN_ID = #{value}
          AND A.DEL_YN = 'N'
    </select>

    <!-- 랜덤쿠폰 발급 내역 조회 -->
    <select id="getRandomCouponInfo" parameterType="int" resultType="CustCoupon">
        /* TscCoupon.getRandomCouponInfo : 랜덤쿠폰 발급 내역 조회(시리얼 포함) */
        SELECT RC.CPN_ID
             , RC.RD_CPN_NM
             , C.CUST_NO
             , C.CUST_ID
             , C.CUST_NM
             , DATE_FORMAT(CC.REG_DT, '%Y-%m-%d %H:%i:%s') AS REG_DT
             , DATE_FORMAT(CC.USED_DT, '%Y-%m-%d %H:%i:%s') AS USED_DT
        FROM TB_RANDOM_COUPON RC
                 LEFT OUTER JOIN TB_CUSTOMER C
                                 ON RC.CUST_NO = C.CUST_NO
                 LEFT OUTER JOIN TB_CUST_COUPON CC
                                 ON RC.CPN_ID = CC.CPN_ID
                                     AND C.CUST_NO = CC.CUST_NO
        WHERE RC.CPN_ID = #{cpnId}
        ORDER BY (CASE WHEN C.CUST_NO IS NOT NULL THEN 1 ELSE 0 END) DESC
               , RC.REG_DT DESC
    </select>

    <!-- 쿠폰사용가능고객구분 조회-->
    <select id="getCouponCustGbList" parameterType="Integer" resultType="Coupon">
        /* TscCoupon.getCouponCustGbList */
        SELECT CPN_ID
             , USABLE_CUST_GB
        FROM TB_COUPON_CUST_GBN
        WHERE CPN_ID = #{cpnId}
    </select>

    <!-- 쿠폰사용가능고객등급 조회-->
    <select id="getCouponCustGradeList" parameterType="Integer" resultType="Coupon">
        /* TscCoupon.getCouponCustGradeList */
        SELECT CPN_ID
             , USABLE_CUST_GRADE
        FROM TB_COUPON_CUST_GRADE
        WHERE CPN_ID = #{cpnId}
    </select>

    <!-- 쿠폰사용가능결제수단 조회-->
    <select id="getCouponPayTypeList" parameterType="Integer" resultType="Coupon">
        /* TscCoupon.getCouponPayTypeList */
        SELECT CPN_ID
             , PAY_TYPE
        FROM TB_COUPON_PAYTYPE
        WHERE CPN_ID = #{cpnId}
    </select>

    <!-- 선착순쿠폰 조회 -->
    <select id="getLimitedTimeCouponList" parameterType="Integer" resultType="CouponLimitedTime">
        /* TscCoupon.getLimitedTimeCouponList */
        SELECT	LIMIT_CPN_ID
             ,LIMIT_CPN_NM
             ,CPN_ID
             ,DOWN_LIMIT_QTY
             ,DOWN_STDT
             ,DOWN_EDDT
             ,DATE_FORMAT(DOWN_STDT,'%Y-%m-%d') AS DOWN_ST_DATE
             ,DATE_FORMAT(DOWN_STDT,'%H:%i:%s') AS DOWN_ST_TIME
             ,DATE_FORMAT(DOWN_EDDT,'%Y-%m-%d') AS DOWN_ED_DATE
             ,DATE_FORMAT(DOWN_EDDT,'%H:%i:%s') AS DOWN_ED_TIME
             ,DEL_YN
             ,REG_NO
             ,REG_DT
             ,UPD_NO
             ,UPD_DT
        FROM	TB_LIMITED_TIME_COUPON
        WHERE	1=1
          AND  CPN_ID = #{cpnId}
          AND  DEL_YN = 'N'
    </select>

    <!-- 쿠폰 제휴채널 조회 -->
    <select id="getCouponAfChannelList" parameterType="Integer" resultType="CouponAfChannel">
        /* TscCoupon.getCouponAfChannelList */
        SELECT A.CPN_ID
             ,A.AF_LINK_CD
             ,B.AF_LINK_NM
             ,A.REG_DT
             ,B.FEE_RATE
             ,B.DISP_ORD
             ,B.AF_CHANNEL
        FROM TB_COUPON_AF_CHANNEL A LEFT JOIN TB_AF_LINK B ON A.AF_LINK_CD = B.AF_LINK_CD
        WHERE CPN_ID = #{cpnId}
    </select>

    <update id="updateCouponMstInfo" parameterType="Coupon">
        /* TscCoupon.updateCouponMstInfo */
        UPDATE	TB_COUPON	SET
        CPN_NM = #{cpnNm}
        , CPN_DESC = #{cpnDesc}
        , SITE_CD = #{siteCd}
        , AF_LINK_CD = #{afLinkCd}
        , CPN_TYPE = #{cpnType}
        , APPLY_SCOPE = #{applyScope}
        , DC_WAY = #{dcWay}
        , DC_PVAL = #{dcPval}
        , DC_MVAL = #{dcMval}
        , DC_AVAL = #{dcAval}
        , MAX_DC_AMT = #{maxDcAmt}
        , PD_GB = #{pdGb}
        <choose>
            <when test='pdGb != null and pdGb == "P"'>
                , AVAIL_STDT = DATE_FORMAT(#{availStdt} , '%Y-%m-%d %H:%i:%s')
                , AVAIL_EDDT = DATE_FORMAT(#{availEddt} , '%Y-%m-%d %H:%i:%s')
                , AVAIL_DAYS = null
            </when>
            <when test='pdGb != null and pdGb == "D"' >
                , AVAIL_STDT = null
                , AVAIL_EDDT = null
                , AVAIL_DAYS = #{availDays}
            </when>
        </choose>
        , CUST_PUB_LIMIT_QTY = #{custPubLimitQty}
        , TOT_PUB_LIMIT_QTY = #{totPubLimitQty}
        , ONE_PUB_QTY = #{onePubQty}
        , DOWN_STDT = DATE_FORMAT(#{downStdt} , '%Y-%m-%d %H:%i:%s')
        , DOWN_EDDT = DATE_FORMAT(#{downEddt} , '%Y-%m-%d %H:%i:%s')
        , BUY_LIMIT_AMT = #{buyLimitAmt}
        , PLAN_SQ = #{planSq}
        , REISSUANCE = #{reissuance}
        , CPN_STAT = #{cpnStat}
        , END_ALIM_YN = #{endAlimYn}
        , UPD_NO = #{updNo}
        , UPD_DT = CURRENT_TIMESTAMP()
        , FIRST_ORD_YN = #{firstOrdYn}
        , DOWN_ABL_YN = #{downAblYn}
        <choose>
            <when test='newCustYn != null and newCustYn == "Y"'>
                , CUST_JOIN_STDT = DATE_FORMAT(#{custJoinStdt} , '%Y-%m-%d %H:%i:%s')
                , CUST_JOIN_EDDT = DATE_FORMAT(#{custJoinEddt} , '%Y-%m-%d %H:%i:%s')
            </when>
            <when test='newCustYn != null and newCustYn == "N"'>
                , CUST_JOIN_STDT = null
                , CUST_JOIN_EDDT = null
            </when>
        </choose>
        <choose>
            <when test='firstOrdYn != null and firstOrdYn == "Y"'>
                , BUY_STDT = DATE_FORMAT(#{buyStdt} , '%Y-%m-%d %H:%i:%s')
                , BUY_EDDT = DATE_FORMAT(#{buyEddt} , '%Y-%m-%d %H:%i:%s')
            </when>
            <when test='firstOrdYn != null and firstOrdYn == "N"'>
                , BUY_STDT = null
                , BUY_EDDT = null
            </when>
        </choose>
        , NEW_CUST_YN = #{newCustYn}
        WHERE CPN_ID = #{cpnId}
    </update>

    <delete id="deleteCouponCustGubun" parameterType="Coupon">
        /* TscCoupon.deleteCouponCustGubun */
        DELETE FROM	TB_COUPON_CUST_GBN
        WHERE	CPN_ID = #{cpnId}
    </delete>

    <delete id="deleteCouponCustGrade" parameterType="Coupon">
        /* TscCoupon.deleteCouponCustGrade */
        DELETE FROM	TB_COUPON_CUST_GRADE
        WHERE	CPN_ID = #{cpnId}
    </delete>

    <delete id="deleteCouponPayType" parameterType="Coupon">
        /* TscCoupon.deleteCouponPayType */
        DELETE FROM	TB_COUPON_PAYTYPE
        WHERE	CPN_ID = #{cpnId}
    </delete>

    <update id="deleteCouponRefVal" parameterType="Coupon">
        /* TscCoupon.deleteCouponRefVal */
        UPDATE TB_COUPON_REFVAL SET
            DEL_YN = 'Y'
                                  , UPD_NO = #{updNo}
                                  , UPD_DT = CURRENT_TIMESTAMP
        WHERE CPN_ID = #{cpnId}
          AND DEL_YN = 'N'
    </update>

    <update id="deleteCouponBurden" parameterType="Coupon">
        /* TscCoupon.deleteCouponBurden */
        UPDATE TB_COUPON_BURDEN SET
            DEL_YN = 'Y'
                                  , UPD_NO = #{updNo}
                                  , UPD_DT = CURRENT_TIMESTAMP
        WHERE CPN_ID = #{cpnId}
          AND DEL_YN = 'N'
    </update>

    <update id="deleteLimitedTimeCoupon" parameterType="Coupon">
        /* TscCoupon.deleteLimitedTimeCoupon */
        UPDATE TB_LIMITED_TIME_COUPON SET
            DEL_YN = 'Y'
          , UPD_NO = #{updNo}
          , UPD_DT = CURRENT_TIMESTAMP
        WHERE CPN_ID = #{cpnId}
          AND DEL_YN = 'N'
    </update>

    <!-- 쿠폰 제휴링크 삭제 -->
    <update id="deleteCouponAfChannel" parameterType="Coupon">
        /* TscCoupon.deleteCouponAfChannel */
        UPDATE TB_COUPON_AF_CHANNEL SET
              REG_NO = #{updNo}
            , REG_DT = CURRENT_TIMESTAMP
        WHERE CPN_ID = #{cpnId}
    </update>

    <!-- 쿠폰 등록 -->
    <insert id="couponInsert" parameterType="Coupon" keyProperty="cpnId">
        /* TscCoupon.couponInsert*/
        INSERT INTO TB_COUPON (
        CPN_ID
        , CPN_NM
        , CPN_DESC
        , SITE_CD
        , AF_LINK_CD
        , CPN_TYPE
        , APPLY_SCOPE
        , DC_WAY
        , DC_PVAL
        , DC_MVAL
        , DC_AVAL
        , MAX_DC_AMT
        , PD_GB
        , AVAIL_STDT
        , AVAIL_EDDT
        , AVAIL_DAYS
        , CUST_PUB_LIMIT_QTY
        , TOT_PUB_LIMIT_QTY
        , ONE_PUB_QTY
        , DN_GB
        , DC_CD_GB
        , DOWN_STDT
        , DOWN_EDDT
        , BUY_LIMIT_AMT
        , PLAN_SQ
        , REISSUANCE
        , CPN_STAT
        , END_ALIM_YN
        , REG_NO
        , REG_DT
        , UPD_NO
        , UPD_DT
        , FIRST_ORD_YN
        , DOWN_ABL_YN
        , CUST_JOIN_STDT
        , CUST_JOIN_EDDT
        , BUY_STDT
        , BUY_EDDT
        , NEW_CUST_YN
        ) VALUES (
        #{cpnId}
        , #{cpnNm}
        , #{cpnDesc}
        , #{siteCd}
        , #{afLinkCd}
        , #{cpnType}
        , #{applyScope}
        , #{dcWay}
        , #{dcPval}
        , #{dcMval}
        , #{dcAval}
        , #{maxDcAmt}
        , #{pdGb}
        <choose>
            <when test='pdGb != null and pdGb == "P"'>
                , DATE_FORMAT(#{availStdt} , '%Y-%m-%d %H:%i:%s')
                , DATE_FORMAT(#{availEddt} , '%Y-%m-%d %H:%i:%s')
                , null
            </when>
            <when test='pdGb != null and pdGb == "D"' >
                , null
                , null
                , #{availDays}
            </when>
        </choose>
        , #{custPubLimitQty}
        , #{totPubLimitQty}
        , #{onePubQty}
        , #{dnGb}
        , IFNULL(#{dcCdGb},'G233_00')
        , DATE_FORMAT(#{downStdt} , '%Y-%m-%d %H:%i:%s')
        , DATE_FORMAT(#{downEddt} , '%Y-%m-%d %H:%i:%s')
        , #{buyLimitAmt}
        , #{planSq}
        , #{reissuance}
        , #{cpnStat}
        , #{endAlimYn}
        , #{regNo}
        , CURRENT_TIMESTAMP()
        , #{updNo}
        , CURRENT_TIMESTAMP()
        , #{firstOrdYn}
        , #{downAblYn}
        <choose>
            <when test='newCustYn != null and newCustYn == "Y"'>
                , DATE_FORMAT(#{custJoinStdt} , '%Y-%m-%d %H:%i:%s')
                , DATE_FORMAT(#{custJoinEddt} , '%Y-%m-%d %H:%i:%s')
            </when>
            <when test='newCustYn != null and newCustYn == "N"'>
                , null
                , null
            </when>
        </choose>
        <choose>
            <when test='firstOrdYn != null and firstOrdYn == "Y"'>
                , DATE_FORMAT(#{buyStdt} , '%Y-%m-%d %H:%i:%s')
                , DATE_FORMAT(#{buyEddt} , '%Y-%m-%d %H:%i:%s')
            </when>
            <when test='firstOrdYn != null and firstOrdYn == "N"'>
                , null
                , null
            </when>
        </choose>
        , #{newCustYn}
        ) ON DUPLICATE KEY UPDATE
        CPN_NM = #{cpnNm}
        , CPN_DESC = #{cpnDesc}
        , SITE_CD = #{siteCd}
        , AF_LINK_CD = #{afLinkCd}
        , CPN_TYPE = #{cpnType}
        , APPLY_SCOPE = #{applyScope}
        , DC_WAY = #{dcWay}
        , DC_PVAL = #{dcPval}
        , DC_MVAL = #{dcMval}
        , DC_AVAL = #{dcAval}
        , MAX_DC_AMT = #{maxDcAmt}
        , PD_GB = #{pdGb}
        <choose>
            <when test='pdGb != null and pdGb == "P"'>
                , AVAIL_STDT = DATE_FORMAT(#{availStdt} , '%Y-%m-%d %H:%i:%s')
                , AVAIL_EDDT = DATE_FORMAT(#{availEddt} , '%Y-%m-%d %H:%i:%s')
                , AVAIL_DAYS = null
            </when>
            <when test='pdGb != null and pdGb == "D"' >
                , AVAIL_STDT = null
                , AVAIL_EDDT = null
                , AVAIL_DAYS = #{availDays}
            </when>
        </choose>
        , CUST_PUB_LIMIT_QTY = #{custPubLimitQty}
        , TOT_PUB_LIMIT_QTY = #{totPubLimitQty}
        , ONE_PUB_QTY = #{onePubQty}
        , DOWN_STDT = DATE_FORMAT(#{downStdt} , '%Y-%m-%d %H:%i:%s')
        , DOWN_EDDT = DATE_FORMAT(#{downEddt} , '%Y-%m-%d %H:%i:%s')
        , BUY_LIMIT_AMT = #{buyLimitAmt}
        , PLAN_SQ = #{planSq}
        , REISSUANCE = #{reissuance}
        , CPN_STAT = #{cpnStat}
        , END_ALIM_YN = #{endAlimYn}
        , UPD_NO = #{updNo}
        , UPD_DT = now()
        , FIRST_ORD_YN = #{firstOrdYn}
        , DOWN_ABL_YN = #{downAblYn}
        <choose>
            <when test='newCustYn != null and newCustYn == "Y"'>
                , CUST_JOIN_STDT = DATE_FORMAT(#{custJoinStdt} , '%Y-%m-%d %H:%i:%s')
                , CUST_JOIN_EDDT = DATE_FORMAT(#{custJoinEddt} , '%Y-%m-%d %H:%i:%s')
            </when>
            <when test='newCustYn != null and newCustYn == "N"'>
                , CUST_JOIN_STDT = null
                , CUST_JOIN_EDDT = null
            </when>
        </choose>
        <choose>
            <when test='firstOrdYn != null and firstOrdYn == "Y"'>
                , BUY_STDT = DATE_FORMAT(#{buyStdt} , '%Y-%m-%d %H:%i:%s')
                , BUY_EDDT = DATE_FORMAT(#{buyEddt} , '%Y-%m-%d %H:%i:%s')
            </when>
            <when test='firstOrdYn != null and firstOrdYn == "N"'>
                , BUY_STDT = null
                , BUY_EDDT = null
            </when>
        </choose>
        , NEW_CUST_YN = #{newCustYn}
    </insert>

    <insert id="createCouponCustGubun" parameterType="Coupon">
        /* TscCoupon.createCouponCustGubun */
        INSERT INTO TB_COUPON_CUST_GBN (
                                         CPN_ID
                                       , USABLE_CUST_GB
                                       , REG_NO
                                       , REG_DT
        ) VALUES (
                     #{cpnId}
                 , #{usableCustGb}
                 , #{regNo}
                 , CURRENT_TIMESTAMP()
                 )
    </insert>

    <insert id="createCouponCustGrade" parameterType="Coupon">
        /* TscCoupon.createCouponCustGrade */
        INSERT INTO TB_COUPON_CUST_GRADE (
                                           CPN_ID
                                         , USABLE_CUST_GRADE
                                         , REG_NO
                                         , REG_DT
        ) VALUES (
                     #{cpnId}
                 , #{usableCustGrade}
                 , #{regNo}
                 , CURRENT_TIMESTAMP()
                 )
    </insert>

    <insert id="createCouponPayType" parameterType="Coupon">
        /* TscCoupon.createCouponPayType */
        INSERT INTO TB_COUPON_PAYTYPE (
                                        CPN_ID
                                      , PAY_TYPE
                                      , REG_NO
                                      , REG_DT
        ) VALUES (
                     #{cpnId}
                 , #{payType}
                 , #{regNo}
                 , CURRENT_TIMESTAMP()
                 )
    </insert>

    <!-- 쿠폰 적용대상 등록 -->
    <insert id="saveCouponRefVal" parameterType="CouponRefval" keyProperty="cpnRefvalSq">
        /* TscCoupon.saveCouponRefVal */
        INSERT INTO TB_COUPON_REFVAL (
        CPN_ID
        , CPN_REFVAL_SQ
        , CPN_TYPE
        , CPN_TARGET
        , REF_VAL
        <if test='refFormalGb != null and refFormalGb != ""'>
            , REF_FORMAL_GB
        </if>
        <if test='refBrandCd != null and refBrandCd != ""'>
            , REF_BRAND_CD
        </if>
        , REG_NO
        , REG_DT
        , UPD_NO
        , UPD_DT
        ) VALUES (
        #{cpnId}
        , #{cpnRefvalSq}
        , #{cpnType}
        , #{cpnTarget}
        , #{refVal}
        <if test='refFormalGb != null and refFormalGb != ""'>
            , #{refFormalGb}
        </if>
        <if test='refBrandCd != null and refBrandCd != ""'>
            , #{refBrandCd}
        </if>
        , #{regNo}
        , CURRENT_TIMESTAMP()
        , #{updNo}
        , CURRENT_TIMESTAMP()
        ) ON DUPLICATE KEY UPDATE
        REF_VAL = #{refVal}
        , CPN_TYPE = #{cpnType}
        , CPN_TARGET = #{cpnTarget}
        , REF_FORMAL_GB = #{refFormalGb}
        , REF_BRAND_CD = #{refBrandCd}
        , DEL_YN = #{delYn}
        , UPD_NO = #{updNo}
        , UPD_DT = now()
    </insert>

    <!-- 쿠폰 입점업체 분담율 등록 -->
    <insert id="saveCouponBurden" parameterType="CouponBurden">
        /* TscCoupon.saveCouponBurden */
        INSERT INTO TB_COUPON_BURDEN( CPN_ID
                                    , SUPPLY_COMP_CD
                                    , BURDEN_RATE
                                    , REG_NO
                                    , REG_DT
                                    , UPD_NO
                                    , UPD_DT)
        VALUES ( #{cpnId}
               , #{supplyCompCd}
               , IFNULL(#{burdenRate},0)
               , #{regNo}
               , CURRENT_TIMESTAMP()
               , #{updNo}
               , CURRENT_TIMESTAMP()
               ) ON DUPLICATE KEY UPDATE
            BURDEN_RATE = IFNULL(#{burdenRate},0)
            , DEL_YN = #{delYn}
            , UPD_NO = #{updNo}
            , UPD_DT = now()
    </insert>

    <insert id="createLimitedTimeCoupon" parameterType="CouponLimitedTime" keyProperty="limitCpnId">
        /* TscCoupon.createLimitedTimeCoupon */
        INSERT INTO TB_LIMITED_TIME_COUPON (
                                             LIMIT_CPN_ID
                                           , LIMIT_CPN_NM
                                           , CPN_ID
                                           , DOWN_LIMIT_QTY
                                           , DOWN_STDT
                                           , DOWN_EDDT
                                           , DEL_YN
                                           , REG_NO
                                           , REG_DT
                                           , UPD_NO
                                           , UPD_DT
        ) VALUES (
                     #{limitCpnId}
                 ,#{limitCpnNm}
                 ,#{cpnId}
                 ,#{downLimitQty}
                 ,DATE_FORMAT(#{downStdt},'%Y-%m-%d %H:%i:%s')
                 ,DATE_FORMAT(#{downEddt},'%Y-%m-%d %H:%i:%s')
                 ,'N'
                 ,#{regNo}
                 ,CURRENT_TIMESTAMP()
                 ,#{updNo}
                 ,CURRENT_TIMESTAMP()
                 ) ON DUPLICATE KEY UPDATE
            LIMIT_CPN_NM = #{limitCpnNm}
            , DOWN_LIMIT_QTY = #{downLimitQty}
            , DOWN_STDT = DATE_FORMAT(#{downStdt},'%Y-%m-%d %H:%i:%s')
            , DOWN_EDDT = DATE_FORMAT(#{downEddt},'%Y-%m-%d %H:%i:%s')
            , DEL_YN = 'N'
            , UPD_NO = #{updNo}
            , UPD_DT = CURRENT_TIMESTAMP()
    </insert>

    <!-- 쿠폰 제휴링크 저장 -->
    <insert id="createCouponAfChannel" parameterType="CouponAfChannel">
        /* TscCoupon.createLimitedTimeCoupon */
        INSERT INTO TB_COUPON_AF_CHANNEL (
                                          CPN_ID
                                          , AF_LINK_CD
                                          , REG_NO
                                          , REG_DT
        ) VALUES (
            #{cpnId}
            , #{afLinkCd}
            , #{regNo}
            , CURRENT_TIMESTAMP()
        ) ON DUPLICATE KEY UPDATE
          REG_NO = #{regNo}
        , REG_DT = CURRENT_TIMESTAMP()
    </insert>

    <!-- 특정 쿠폰 발급받은 회원 조회-->
    <select id="getCouponIssueCustList" parameterType="CustCoupon" resultType="CustCoupon">
        /* TscCoupon.getCouponIssueCustList */
        SELECT CUST_CPN_SQ
             , CUST_NO
             , CPN_ID
             , AVAIL_STDT
             , AVAIL_EDDT
        FROM TB_CUST_COUPON
        WHERE CPN_ID = #{cpnId}
          AND USED_DT IS NOT NULL
    </select>

    <!-- 특정 쿠폰 발급받은 고객 유효기간 수정-->
    <update id="updateCustCouponAvailEddt" parameterType="CustCoupon">
        /* TscCoupon.updateCustCouponAvailEddt */
        UPDATE TB_CUST_COUPON
        SET AVAIL_EDDT = DATE_FORMAT(#{availEddt} , '%Y-%m-%d')
          , UPD_NO = #{updNo}
          , UPD_DT = CURRENT_TIMESTAMP()
        WHERE CPN_ID = #{cpnId}
          AND USED_DT IS NOT NULL
          AND CUST_NO = #{custNo}
          AND CUST_CPN_SQ = #{custCpnSq}
    </update>

    <!-- 특정 쿠폰 발급받은 회원 조회-->
    <select id="getSerialOverlapCheck" parameterType="Coupon" resultType="int">
        /* TscCoupon.getSerialOverlapCheck : 기간 내 중복 시리얼넘버 체크 */
        WITH CHECK_DATA AS (
        SELECT C.CPN_ID
        , C.DOWN_STDT
        , C.DOWN_EDDT
        , C.AVAIL_STDT
        , C.AVAIL_EDDT
        , C.AVAIL_DAYS
        FROM TB_COUPON C
        INNER JOIN (SELECT CPN_ID
        , RD_CPN_NM
        FROM TB_RANDOM_COUPON
        WHERE RD_CPN_NM = #{rdCpnNm}
        GROUP BY CPN_ID, RD_CPN_NM ) RC
        ON C.CPN_ID = RC.CPN_ID
        )
        SELECT SUM(A.CNT) AS CNT
        FROM ( SELECT COUNT(1) AS CNT		<!-- 다운 시작일이 겹치는 쿠폰번호 찾기 -->
        FROM CHECK_DATA C
        WHERE 1=1
        AND C.DOWN_STDT >= STR_TO_DATE(#{downStdt}, '%Y-%m-%d %H:%i:%s')
        AND C.DOWN_STDT <![CDATA[ <= ]]> STR_TO_DATE(#{downEddt}, '%Y-%m-%d %H:%i:%s')
        UNION
        SELECT COUNT(1) AS CNT		<!-- 다운 종료일이 겹치는 쿠폰번호 찾기 -->
        FROM CHECK_DATA C
        WHERE 1=1
        AND C.DOWN_EDDT >= STR_TO_DATE(#{downStdt}, '%Y-%m-%d %H:%i:%s')
        AND C.DOWN_EDDT <![CDATA[ <= ]]> STR_TO_DATE(#{downEddt}, '%Y-%m-%d %H:%i:%s')
        ) A
    </select>

    <!-- 고객 쿠폰 발행 -->
    <insert id="createRandomCouponInfo" parameterType="Coupon">
        /* TscCoupon.createRandomCouponInfo */
        INSERT INTO TB_RANDOM_COUPON (
                                       RD_CPN_NM
                                     , CPN_ID
                                     , REG_NO
                                     , REG_DT
                                     , UPD_NO
                                     , UPD_DT
        ) VALUES (
                     #{rdCpnNm}
                 , #{cpnId}
                 , #{regNo}
                 , CURRENT_TIMESTAMP()
                 , #{updNo}
                 , CURRENT_TIMESTAMP()
                 )
    </insert>

    <!-- 특정 쿠폰 발급받은 회원 조회-->
    <select id="getRandomCouponNmCnt" parameterType="String" resultType="int">
        /* TscCoupon.getRandomCouponNmCnt : 중복 시리얼넘버 체크 */
        SELECT COUNT(1) AS CNT
        FROM TB_RANDOM_COUPON
        WHERE RD_CPN_NM = #{value}
    </select>

    <!-- 쿠폰 적용대상 수정-->
    <update id="updateCouponRefval" parameterType="CouponRefval" >
        /* TscCoupon.updateCouponRefval */
        UPDATE TB_COUPON_REFVAL
        SET DEL_YN = 'Y'
        , UPD_NO = #{updNo}
        , UPD_DT = CURRENT_TIMESTAMP()
        WHERE CPN_ID = #{cpnId}
        AND CPN_REFVAL_SQ IN
        <foreach collection="cpnRefvalSqArr" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </update>

    <!-- 고객 쿠폰 발행 -->
    <insert id="saveCouponCustPub" parameterType="CustCoupon">
        /* TscCoupon.saveCouponCustPub */
        INSERT INTO TB_CUST_COUPON (
                                     CUST_NO
                                   , CPN_ID
                                   , AVAIL_STDT
                                   , AVAIL_EDDT
                                   , PUB_REASON
                                   , PUB_REASON_DTL
                                   , END_ALIM_SEND_YN
                                   , REG_NO
                                   , REG_DT
                                   , UPD_NO
                                   , UPD_DT
        ) VALUES (
                     #{custNo}
                 , #{cpnId}
                 , DATE_FORMAT(#{availStdt} , '%Y%m%d%H%i%S')
                 , DATE_FORMAT(#{availEddt} , '%Y%m%d%H%i%S')
                 , #{pubReason}
                 , IFNULL(#{pubReasonDtl}, FN_GET_CODE_NM('G068', #{pubReason}))
                 , #{endAlimSendYn}
                 , #{regNo}
                 , CURRENT_TIMESTAMP()
                 , #{updNo}
                 , CURRENT_TIMESTAMP()
                 )
    </insert>

    <!-- 쿠폰발급받은회원 조회-->
    <select id="getCpnPubCustList" parameterType="Integer" resultType="Coupon">
        /* TscCoupon.getCpnPubCustList */
        SELECT	A.CUST_NO
             ,B.CUST_NM
             ,B.CUST_GB
             ,FN_GET_CODE_NM('G100',B.CUST_GB) AS CUST_GB_NM
             ,B.CUST_GRADE
             ,FN_GET_CODE_NM('G110',B.CUST_GRADE) AS CUST_GRADE_NM
             ,A.AVAIL_STDT
             ,A.AVAIL_EDDT
             ,CASE WHEN A.USED_DT IS NOT NULL THEN 'Y'
                   ELSE 'N' END USE_YN
             ,A.USED_DT
             ,A.PUB_REASON
             ,FN_GET_CODE_NM('G068',A.PUB_REASON) AS PUB_REASON_NM
             ,A.PUB_REASON_DTL
             ,A.REG_NO
             ,CASE WHEN FN_GET_USER_NM(A.REG_NO) = '본인' THEN '본인발급' ELSE FN_GET_USER_NM(A.REG_NO) END AS REG_NM
             ,A.REG_DT
        FROM 	TB_CUST_COUPON A
                    LEFT OUTER JOIN TB_CUSTOMER B
                                    ON		A.CUST_NO = B.CUST_NO
        WHERE 1=1
          AND A.CPN_ID = #{cpnId}
    </select>

    <!-- 선착순쿠폰 삭제 -->
    <update id="updateLimitedTimeCouponList" parameterType="CouponLimitedTime" >
        /* TscCoupon.updateLimitedTimeCouponList */
        UPDATE TB_LIMITED_TIME_COUPON
        SET DEL_YN = 'Y'
        , UPD_NO = #{updNo}
        , UPD_DT = CURRENT_TIMESTAMP()
        WHERE CPN_ID = #{cpnId}
        AND LIMIT_CPN_ID IN
        <foreach collection="arrLimitCpnId" item="item" index="index"  open="(" close=")" separator=",">
            #{item}
        </foreach>
    </update>

    <update id="updateCouponStat" parameterType="Coupon">
        /* TscCoupon.updateCouponStat */
        UPDATE TB_COUPON SET
        CPN_STAT = #{cpnStat}
        , UPD_NO = #{updNo}
        , UPD_DT = CURRENT_TIMESTAMP()
        WHERE CPN_ID = #{cpnId}
    </update>

    <!-- 쿠폰조회 목록 -->
    <select id="getCouponRetrieveList" parameterType="Coupon" resultType="Coupon">
        /* TscCoupon.getCouponRetrieveList */
        SELECT A.CPN_ID                                               /*쿠폰ID*/
        , A.CPN_NM                                               /*쿠폰명*/
        , A.CPN_DESC                                             /*쿠폰설명*/
        , A.CPN_STAT
        , A.SITE_CD                                              /*사이트코드(공통코드G000)*/
        , A.CPN_TYPE                                             /*쿠폰유형(공통코드G230)*/
        , A.DC_WAY                                               /*할인방식(공통코드G240)*/
        , A.DC_PVAL                                              /*할인값(PC). 할인방식이 금액이면 할인금액, 율이면 할인율*/
        , A.DC_MVAL                                              /*할인값(모바일). 할인방식이 금액이면 할인금액, 율이면 할인율*/
        , A.MAX_DC_AMT                                           /*최고할인값. 할인방식이 금액이면 최고할인금액, 율이면 최고할인율*/
        , A.PD_GB                                                /*기간/일수구분(P 기간, D 일수)*/
        , A.AVAIL_STDT /*유효시작일시(기간/일수구분 "P 기간"일 때 사용됨)*/
        , A.AVAIL_EDDT /*유효종료일시(기간/일수구분 "P 기간"일 때 사용됨)*/
        , A.AVAIL_DAYS                                           /*유효일수(기간/일수구분 "D 일수"일 때 사용됨)*/
        , A.CUST_PUB_LIMIT_QTY                                   /*고객당발행제한수량(0은 무제한)*/
        , A.TOT_PUB_LIMIT_QTY                                    /*총발행제한수량(0은 무제한)*/
        , A.ONE_PUB_QTY                                          /*1회발행수량*/
        , A.DN_GB                                                /*다운로드구분(A:자동다운로드, D:직접다운로드). 다운로드가능여부가 "Y 다운로드가능"일 때만 사용됨*/
        , A.BUY_LIMIT_AMT                                        /*구매제한금액(0은 제한없음)*/
        FROM   TB_COUPON A
        WHERE  A.SITE_CD = #{siteCd}
        <if test="cpnId !=null and cpnId !=''">
            AND	   A.CPN_ID = #{cpnId}
        </if>
        <if test="cpnNm !=null and cpnNm !=''">
            AND	   A.CPN_NM LIKE CONCAT('%',#{cpnNm},'%')
        </if>
        <if test="cpnType !=null and cpnType !=''">
            AND	   A.CPN_TYPE = #{cpnType}
        </if>
        ORDER BY CPN_ID DESC
    </select>

    <!-- 랜덤쿠폰 지급 -->
    <update id="updateGiveRandomCoupon" parameterType="CustCoupon">
        /* TscCoupon.updateGiveRandomCoupon : 랜덤쿠폰 지급 */
        UPDATE TB_RANDOM_COUPON SET
              CUST_NO = #{custNo}
            , UPD_NO = #{updNo}
            , UPD_DT = NOW()
        WHERE RD_CPN_ID = #{rdCpnId}
    </update>

	<insert id="createCustCoupon" parameterType="CustCoupon">
		/* TscCoupon.createCustCoupon */
		INSERT INTO TB_CUST_COUPON (
		      CUST_NO
		    , CPN_ID
		    , AVAIL_STDT
		    , AVAIL_EDDT
		    , PUB_REASON
		    , PUB_REASON_DTL
		    , END_ALIM_SEND_YN
		    , REG_NO
		    , REG_DT
		    , UPD_NO
		    , UPD_DT
		) VALUES (
		      #{custNo}
		    , #{cpnId}
		<if test='pdGb == "P"'>
		    , DATE_FORMAT(#{availStdt} , '%Y%m%d%H%i%S')
		    , DATE_FORMAT(#{availEddt} , '%Y%m%d%H%i%S')
		</if>
		<if test='pdGb == "D"'>
		    , NOW()
		    , DATE_ADD(NOW(), INTERVAL #{availDays} DAY )
		</if>
		    , #{pubReason}
		    , IFNULL(#{pubReasonDtl}, FN_GET_CODE_NM('G068', #{pubReason}))
		    , #{endAlimSendYn}
		    , #{regNo}
		    , CURRENT_TIMESTAMP()
		    , #{updNo}
		    , CURRENT_TIMESTAMP()
		)
	</insert>
	
	<!-- 공급업체목록으로 브랜정보목록 조회 -->
	<select id="getSupplyCompCdAndBrandCdList" parameterType="Coupon" resultType="Coupon">
		/* TscCoupon.getSupplyCompCdAndBrandCdList */
		SELECT BR.BRAND_CD                    /*브랜드코드*/
		     , BR.BRAND_ENM
		     , (CASE WHEN BG.DISP_NM_LANG = 'EN' THEN BG.BRAND_GROUP_ENM ELSE BG.BRAND_GROUP_KNM END) AS BRAND_GROUP_NM
		FROM   TB_BRAND BR
		INNER  JOIN TB_BRAND_GROUP BG
		ON     BR.BRAND_GROUP_NO = BG.BRAND_GROUP_NO
		AND    BG.USE_YN = 'Y'
		WHERE  1=1
		AND    BR.BRAND_CD IN (
			SELECT BRAND_CD
			FROM   TB_BRAND_SUPPLY Z
			WHERE  1=1
			AND    Z.SUPPLY_COMP_CD IN
			<foreach collection="supplyCompCdArr" item="item" open="(" separator="," close=")">
		           #{item}
			</foreach>
		)
	</select>
	
	<!-- 브랜드목록으로 공급업체정보목록 조회 -->
	<select id="getBrandCdAndSupplyCompList" parameterType="Coupon" resultType="Coupon">
		/* TscCoupon.getBrandCdAndSupplyCompList */
		SELECT SC.SUPPLY_COMP_CD
		     , SC.SUPPLY_COMP_NM
		FROM   TB_SUPPLY_COMPANY SC
		WHERE  1=1
		AND    SC.SUPPLY_COMP_CD IN (
			SELECT SUPPLY_COMP_CD
			FROM   TB_BRAND_SUPPLY Z
			WHERE  1=1
			AND    Z.BRAND_CD IN
			<foreach collection="brandCdArr" item="item" open="(" separator="," close=")">
		           #{item}
			</foreach>
		)
	</select>
</mapper>