<?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="WebMembership">
    <select id="selectTotalAppUserCount" parameterType="hashmap" resultType="Integer">
        SELECT COUNT(*)                         AS "totalCount"
        FROM MU_USER AS MU
        LEFT JOIN
        MU_CATEGORY_ITEM AS MCIN
        ON MCIN.MU_CATEGORY_ITEM_ID = MU.NATIONALITY
        LEFT JOIN
        MU_CATEGORY_ITEM AS MCIT
        ON MCIT.MU_CATEGORY_ITEM_ID = MU.USER_TYPE
        WHERE MU.USE_YN = 'Y'
        AND MU.APP_USE_YN='Y'
        <if test="userType != null and userType != ''">
            AND MCIT.CATEGORY_ITEM_CODE = #{userType}
            AND MCIT.CATEGORY_CODE = #{userTypeCode}
        </if>
        <if test="nationality != null and nationality != ''">
            AND MCIN.CATEGORY_ITEM_CODE = #{nationality}
            AND MCIN.CATEGORY_CODE = #{nationalityCode}
        </if>
        <if test="membershipYn != null and membershipYn != ''">
            AND MU.MEMBERSHIP_YN = #{membershipYn}
        </if>
        <if test="userSearchKeywordParam != null and userSearchKeywordParam != ''">
            AND (MU.USER_NAME LIKE CONCAT('%',TRIM(#{userSearchKeywordParam}),'%')
            OR MU.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{userSearchKeywordParam}),'%'))
        </if>
    </select>

    <select id="selectTotalMembershipProcedureCount" parameterType="hashmap" resultType="Integer">
        SELECT COUNT(1)     AS totalCount
        FROM MU_TREATMENT_PROCEDURE MTP
         JOIN MU_TREATMENT MT
              ON MTP.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
              AND MT.TREATMENT_NAME = '멤버십'
         JOIN MU_TREATMENT_PROCEDURE_PRICE MTPP
              ON MTP.MU_TREATMENT_PROCEDURE_ID = MTPP.MU_TREATMENT_PROCEDURE_ID
              AND MTP.USE_YN='Y'
              AND MT.USE_YN='Y'
              AND MTPP.USE_YN='Y'
    </select>

    <select id="selectListMembershipProcedure" parameterType="hashmap" resultType="hashmap">
        SELECT MTP.MU_TREATMENT_PROCEDURE_ID AS muTreatmentProcedureId
             , TREATMENT_PROCEDURE_NAME      AS treatmentProcedureName
             , IFNULL(PRICE,0)               AS price
             , IFNULL(VAT,0)                 AS vat
             , IFNULL(ADDITIONAL_AMOUNT,0)   AS additionalAmount
             , IFNULL(PRICE,0)
                +IFNULL(VAT,0)
                +IFNULL(ADDITIONAL_AMOUNT,0) AS totalAmount
        FROM MU_TREATMENT_PROCEDURE MTP
        JOIN MU_TREATMENT MT
            ON MTP.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
            AND MT.TREATMENT_NAME = '멤버십'
        JOIN MU_TREATMENT_PROCEDURE_PRICE MTPP
            ON MTP.MU_TREATMENT_PROCEDURE_ID = MTPP.MU_TREATMENT_PROCEDURE_ID
            AND MTP.USE_YN='Y'
            AND MT.USE_YN='Y'
            AND MTPP.USE_YN='Y'
    </select>

    <select id="selectTotalMembershipCount" parameterType="hashmap" resultType="Integer">
        SELECT COUNT(*)                         AS "totalCount"
          FROM MU_MEMBERSHIP AS MM
          JOIN MU_USER MU ON MM.MU_USER_ID = MU.MU_USER_ID
           AND MU.USE_YN = 'Y'
         WHERE MM.USE_YN = 'Y'
        <if test="userSearchKeywordParam != null and userSearchKeywordParam != ''">
            AND (MM.USER_NAME LIKE CONCAT('%',TRIM(#{userSearchKeywordParam}),'%')
            OR MM.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{userSearchKeywordParam}),'%'))
        </if>
    </select>

    <select id="selectMembershipProcedureCount" parameterType="hashmap" resultType="Integer">
        SELECT COUNT(1)
          FROM (
                   SELECT TREATMENT_PROCEDURE_NAME 				                        AS productNames
                     FROM MU_TREATMENT_PROCEDURE MTP
                     JOIN MU_TREATMENT_PROCEDURE_PRICE MTPP
                       ON MTP.MU_TREATMENT_PROCEDURE_ID = MTPP.MU_TREATMENT_PROCEDURE_ID
                      AND MTPP.USE_YN='Y'
                    WHERE MTP.USE_YN='Y'
                      AND MTP.TREATMENT_PROCEDURE_NAME ='멤버십'
                      AND INSURANCE_TYPE ='N'
                      AND PRICE = #{price}
                      AND VAT =#{vat}
                      AND ADDITIONAL_AMOUNT=#{additionalAmount}
                    GROUP BY MTP.MU_TREATMENT_PROCEDURE_ID
                           , MTP.TREATMENT_PROCEDURE_NAME
                           , INSURANCE_TYPE
                           , PRICE
                           , VAT
               )AS MTP
    </select>
    <select id="selectListMembership" parameterType="hashmap" resultType="hashmap">
        SELECT   MM.MU_USER_ID                                  AS muUserId
                ,MU.USER_NAME                                   AS userName
                ,MCIN.CATEGORY_ITEM_NAME                        AS nationality
                ,DATE_FORMAT(MU.BIRTHDAY, '%Y-%m-%d')           AS birth
                ,TIMESTAMPDIFF(YEAR, MU.BIRTHDAY, CURDATE())    AS age
                ,CASE MU.GENDER
                    WHEN 'M' THEN '남'
                    WHEN 'F' THEN '여'
                 END                                            AS "gender"
                ,MU.PHONE_NUMBER                                AS phoneNumber
                ,FORMAT(MM.MEMBERSHIP_BALANCE,0)                AS membershipBalance
                ,DATE_FORMAT(MM.LAST_RECHARGE_DATE, '%Y-%m-%d') AS lastRechargeDate
                ,DATE_FORMAT(MM.LAST_USE_DATE, '%Y-%m-%d')      AS lastUseDate
          FROM MU_MEMBERSHIP MM
          JOIN MU_USER MU ON MM.MU_USER_ID = MU.MU_USER_ID
     LEFT JOIN MU_CATEGORY_ITEM AS MCIN
            ON MCIN.MU_CATEGORY_ITEM_ID = MU.NATIONALITY
         WHERE MU.USE_YN = 'Y'
           AND MM.USE_YN = 'Y'
        <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
            AND (MU.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
            OR MU.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
            OR DATE_FORMAT(MU.BIRTHDAY, '%Y%m%d') LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
        </if>
        <choose>
            <when test="membershipSort != null and membershipSort != ''">
                ORDER BY ${membershipSort}
            </when>
            <otherwise>
                ORDER BY MM.MOD_DATE DESC
            </otherwise>
        </choose>
        <if test="membershipStart != null and membershipStart != ''">
            LIMIT ${membershipStart}
            <if test="membershipLimit != null and membershipLimit != ''">
                ,${membershipLimit}
            </if>
        </if>
    </select>

    <select id="downloadMembershipExcel" parameterType="hashmap" resultType="hashmap">
        SELECT MM.MU_USER_ID                                  AS muUserId
              ,MU.USER_NAME                                   AS userName
              ,MCIN.CATEGORY_ITEM_NAME                        AS nationality
              ,DATE_FORMAT(MU.BIRTHDAY, '%Y-%m-%d')           AS birth
              ,TIMESTAMPDIFF(YEAR, MU.BIRTHDAY, CURDATE())    AS age
              ,CASE MU.GENDER
                 WHEN 'M' THEN '남'
                 WHEN 'F' THEN '여'
               END                                            AS "gender"
              ,MU.PHONE_NUMBER                                AS phoneNumber
              ,FORMAT(MM.MEMBERSHIP_BALANCE,0)                AS membershipBalance
              ,DATE_FORMAT(MM.LAST_RECHARGE_DATE, '%Y-%m-%d') AS lastRechargeDate
              ,DATE_FORMAT(MM.LAST_USE_DATE, '%Y-%m-%d')      AS lastUseDate
          FROM MU_MEMBERSHIP MM
          JOIN MU_USER MU ON MM.MU_USER_ID = MU.MU_USER_ID
     LEFT JOIN MU_CATEGORY_ITEM AS MCIN
            ON MCIN.MU_CATEGORY_ITEM_ID = MU.NATIONALITY
         WHERE MU.USE_YN = 'Y'
           AND MM.USE_YN = 'Y'
        <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
            AND (MU.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
            OR MU.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
        </if>
        <choose>
            <when test="membershipSort != null and membershipSort != ''">
                ORDER BY ${membershipSort}
            </when>
            <otherwise>
                ORDER BY MM.MOD_DATE DESC
            </otherwise>
        </choose>
    </select>
    
    <select id="selectSumMembershipBalance" parameterType="hashmap" resultType="hashmap">
        SELECT
            FORMAT(
                    SUM(
                            CASE
                                WHEN USAGE_TYPE = 'C' THEN RECHARGE_AMOUNT
                                WHEN USAGE_TYPE = 'A' THEN RECHARGE_AMOUNT
                                ELSE 0
                                END
                    ), 0) AS 'sumChargeBalance',
            FORMAT(
                    SUM(
                            CASE
                                WHEN USAGE_TYPE = 'U' THEN USED_AMOUNT
                                WHEN USAGE_TYPE = 'D' THEN -RECHARGE_AMOUNT
                                ELSE 0
                                END
                    ), 0) AS 'sumUsageBalance'
        FROM MU_MEMBERSHIP_HISTORY MMH
        JOIN MU_USER MU
        ON MMH.MU_USER_ID=MU.MU_USER_ID
        WHERE MU.USE_YN = 'Y'
        AND MMH.USE_YN='Y'
    </select>

    <select id="selectTotalMembershipHistoryInfo" parameterType="hashmap" resultType="hashmap">
        SELECT MU.MU_USER_ID                                       AS muUserId
              ,MU.USER_NAME                                        AS userName
              ,MU.PHONE_NUMBER                                     AS phoneNumber
              ,MU.MEMBERSHIP_YN                                    AS membershipYn
              ,IFNULL(DATE_FORMAT(MU.BIRTHDAY, '%Y-%m-%d'), '-')   AS birth
              ,IFNULL(TIMESTAMPDIFF(YEAR, MU.BIRTHDAY, CURDATE()), '-')
                                                                   AS age
              ,CASE MU.GENDER
               WHEN 'M' THEN '남'
               WHEN 'F' THEN '여'
               ELSE '-'
                END                                                AS gender
              ,MCIN.CATEGORY_ITEM_NAME                             AS nationality
              ,FORMAT(IFNULL(MM.MEMBERSHIP_BALANCE,0),0)           AS membershipBalance
              ,FORMAT(SUM(CASE
                          WHEN MMH.USAGE_TYPE = 'C' THEN MMH.RECHARGE_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'D' THEN MMH.RECHARGE_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'P' THEN MMH.RECHARGE_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'A' THEN MMH.RECHARGE_AMOUNT
                          ELSE 0
                          END
                      ), 0)                                        AS sumChargeBalance
              ,FORMAT(SUM(CASE
                          WHEN MMH.USAGE_TYPE = 'U' THEN MMH.USED_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'T' THEN MMH.USED_AMOUNT
                          ELSE 0
                          END
                      ), 0)                                        AS sumUsageBalance
          FROM MU_USER MU
     LEFT JOIN MU_MEMBERSHIP MM
            ON MM.MU_USER_ID = MU.MU_USER_ID
           AND MM.USE_YN = 'Y'
     LEFT JOIN MU_MEMBERSHIP_HISTORY MMH
            ON MMH.MU_USER_ID = MU.MU_USER_ID
           AND MMH.USE_YN = 'Y'
     LEFT JOIN MU_CATEGORY_ITEM MCIN
            ON MCIN.MU_CATEGORY_ITEM_ID = MU.NATIONALITY
         WHERE MU.USE_YN = 'Y'
           AND MU.MU_USER_ID = #{muUserId}
      GROUP BY MU.MU_USER_ID
              ,MU.USER_NAME
              ,MU.BIRTHDAY
              ,MU.GENDER
              ,MCIN.CATEGORY_ITEM_NAME
              ,MM.MEMBERSHIP_BALANCE
      ORDER BY MU.USER_NAME
    </select>

    <select id="selectTotalMembershipHistoryCount" parameterType="hashmap" resultType="Integer">
        SELECT COUNT(*)
        FROM MU_MEMBERSHIP_HISTORY MMH
        LEFT JOIN MU_TREATMENT MT
            ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
        LEFT JOIN MU_TREATMENT_PROCEDURE MTP
            ON MTP.MU_TREATMENT_PROCEDURE_ID = MMH.MU_TREATMENT_PROCEDURE_ID
        LEFT JOIN MU_MEMBER MM2
            ON MMH.MU_MEMBER_ID = MM2.MU_MEMBER_ID
        LEFT JOIN MU_MEMBER MM
            ON MMH.RESERVE_MEMBER_ID = MM.MU_MEMBER_ID
        WHERE MMH.USE_YN = 'Y'
        AND MMH.MU_USER_ID=#{muUserId}
        <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
            AND MT.TREATMENT_NAME != '비만'
            AND MT.TREATMENT_NAME != '피부'
            AND MT.TREATMENT_NAME != '쁘띠'
        </if>
        <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
            AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
        </if>
        <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
            AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
            AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
        </if>
    </select>

    <select id="selectListMembershipHistory" parameterType="hashmap" resultType="hashmap">
        SELECT *
          FROM (
                SELECT MU_MEMBERSHIP_HISTORY_ID                                            AS muMembershipHistoryId
                      ,DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')                             AS writeDate
                      ,IF(MT.TREATMENT_NAME='멤버십','기타',MT.TREATMENT_NAME)               AS treatmentName
                      ,CASE
                          WHEN MMH.USAGE_TYPE = 'T' THEN CONCAT('멤버십 양도', ' (', MU_TO.USER_NAME, ')')
                          WHEN MMH.USAGE_TYPE = 'P' THEN CONCAT('멤버십 양수', ' (', MU_FROM.USER_NAME, ')')
                          ELSE MTP.TREATMENT_PROCEDURE_NAME
                       END                                                                 AS procedureName
                      ,MM.NAME                                                             AS reserveMemberNm
                      ,MM2.NAME                                                            AS muMemberNm
                      ,FORMAT(MMH.USED_AMOUNT,0)                                           AS usedAmount
                      ,FORMAT(MMH.RECHARGE_AMOUNT,0)                                       AS rechargeAmount
                      ,MMH.MEMO                                                            AS memo
                      ,CASE MMH.USAGE_TYPE
                          WHEN 'C' THEN '충전'
                          WHEN 'U' THEN '사용'
                          WHEN 'T' THEN '양도'
                          WHEN 'P' THEN '양수'
                          WHEN 'D' THEN '환불'
                          WHEN 'A' THEN '적립'
                       END                                                                 AS usageType
                      ,MMH.REG_DATE                                                        AS regDate
                FROM MU_MEMBERSHIP_HISTORY MMH
                LEFT JOIN MU_TREATMENT MT
                        ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
                LEFT JOIN MU_TREATMENT_PROCEDURE MTP
                        ON MTP.MU_TREATMENT_PROCEDURE_ID = MMH.MU_TREATMENT_PROCEDURE_ID
                LEFT JOIN MU_MEMBER MM2
                        ON MMH.MU_MEMBER_ID = MM2.MU_MEMBER_ID
                LEFT JOIN MU_MEMBER MM
                        ON MMH.RESERVE_MEMBER_ID = MM.MU_MEMBER_ID
                LEFT JOIN MU_USER MU_TO
                        ON MMH.TRANSFER_TO_USER_ID = MU_TO.MU_USER_ID
                LEFT JOIN MU_USER MU_FROM
                        ON MMH.TRANSFER_FROM_USER_ID = MU_FROM.MU_USER_ID
            WHERE MMH.USE_YN='Y'
                AND MMH.MU_USER_ID=#{muUserId}
                AND MMH.CRM_MEMBER_PAY_PID IS NULL
                <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                    AND MT.TREATMENT_NAME != '비만'
                    AND MT.TREATMENT_NAME != '피부'
                    AND MT.TREATMENT_NAME != '쁘띠'
                </if>
                <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                    AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
                </if>
                <if test="usedType != null and usedType != ''">
                    AND MMH.USAGE_TYPE = #{usedType}
                </if>
                <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                    AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                    AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
                </if>

             UNION ALL

                SELECT MU_MEMBERSHIP_HISTORY_ID                                            AS muMembershipHistoryId
                      ,DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')                             AS writeDate
                      ,MMH.CRM_MEMBER_PAY_M_DIVI1_NAME                                     AS treatmentName
                      ,CASE
                          WHEN MMH.USAGE_TYPE = 'T' THEN CONCAT('멤버십 양도', ' (', MU_TO.USER_NAME, ')')
                          WHEN MMH.USAGE_TYPE = 'P' THEN CONCAT('멤버십 양수', ' (', MU_FROM.USER_NAME, ')')
                          ELSE CASE
                               WHEN CRM_MEMBER_PAY_M_DIVI4_NAME != ''
                               THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI3_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI4_NAME)
                               WHEN CRM_MEMBER_PAY_M_DIVI3_NAME != ''
                               THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI3_NAME)
                               WHEN CRM_MEMBER_PAY_M_DIVI2_NAME != ''
                               THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME)
                               ELSE ''
                                END
                       END                                                                 AS procedureName
                      ,MMH.CRM_MEMBER_PAY_DOCTOR_NAME                                      AS reserveMemberNm
                      ,MMH.CRM_MEMBER_PAY_STAFF_NAME                                       AS muMemberNm
                      ,FORMAT(MMH.USED_AMOUNT,0)                                           AS usedAmount
                      ,FORMAT(MMH.RECHARGE_AMOUNT,0)                                       AS rechargeAmount
                      ,MMH.MEMO                                                            AS memo
                      ,CASE MMH.USAGE_TYPE
                          WHEN 'C' THEN '충전'
                          WHEN 'U' THEN '사용'
                          WHEN 'T' THEN '양도'
                          WHEN 'P' THEN '양수'
                          WHEN 'D' THEN '환불'
                          WHEN 'A' THEN '적립'
                       END                                                                 AS usageType
                      ,MMH.REG_DATE                                                        AS regDate
                FROM MU_MEMBERSHIP_HISTORY MMH
                LEFT JOIN MU_TREATMENT MT
                        ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
                LEFT JOIN MU_TREATMENT_PROCEDURE MTP
                        ON MTP.MU_TREATMENT_PROCEDURE_ID = MMH.MU_TREATMENT_PROCEDURE_ID
                LEFT JOIN MU_MEMBER MM2
                        ON MMH.MU_MEMBER_ID = MM2.MU_MEMBER_ID
                LEFT JOIN MU_MEMBER MM
                        ON MMH.RESERVE_MEMBER_ID = MM.MU_MEMBER_ID
                LEFT JOIN MU_USER MU_TO
                        ON MMH.TRANSFER_TO_USER_ID = MU_TO.MU_USER_ID
                LEFT JOIN MU_USER MU_FROM
                        ON MMH.TRANSFER_FROM_USER_ID = MU_FROM.MU_USER_ID
            WHERE MMH.USE_YN='Y'
                AND MMH.MU_USER_ID=#{muUserId}
                AND MMH.CRM_MEMBER_PAY_PID IS NOT NULL
                <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                    AND MT.TREATMENT_NAME != '비만'
                    AND MT.TREATMENT_NAME != '피부'
                    AND MT.TREATMENT_NAME != '쁘띠'
                </if>
                <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                    AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
                </if>
                <if test="usedType != null and usedType != ''">
                    AND MMH.USAGE_TYPE = #{usedType}
                </if>
                <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                    AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                    AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
                </if>
          ) AS MMH
        <choose>
            <when test="membershipSort != null and membershipSort != ''">
                ORDER BY ${membershipSort}
            </when>
            <otherwise>
                ORDER BY MMH.regDate DESC
            </otherwise>
        </choose>
        <if test="membershipStart != null and membershipStart != ''">
            LIMIT ${membershipStart}
            <if test="membershipLimit != null and membershipLimit != ''">
                ,${membershipLimit}
            </if>
        </if>
    </select>

    <select id="downloadMembershipHistoryExcel" parameterType="hashmap" resultType="hashmap">
        SELECT
             DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')                             AS writeDate
            ,MT.TREATMENT_NAME                                                   AS treatmentName
            ,CASE
                WHEN MMH.USAGE_TYPE = 'T' THEN CONCAT('멤버십 양도', ' (', MU_TO.USER_NAME, ')')
                WHEN MMH.USAGE_TYPE = 'P' THEN CONCAT('멤버십 양수', ' (', MU_FROM.USER_NAME, ')')
                ELSE MTP.TREATMENT_PROCEDURE_NAME
             END                                                                 AS procedureName
            ,MM.NAME                                                             AS reserveMemberNm
            ,MM2.NAME                                                            AS muMemberNm
            ,FORMAT(MMH.USED_AMOUNT,0)                                           AS usedAmount
            ,FORMAT(MMH.RECHARGE_AMOUNT,0)                                       AS rechargeAmount
            ,MMH.MEMO                                                            AS memo
            ,CASE MMH.USAGE_TYPE
                WHEN 'C' THEN '충전'
                WHEN 'U' THEN '사용'
                WHEN 'T' THEN '양도'
                WHEN 'P' THEN '양수'
                WHEN 'D' THEN '환불'
                WHEN 'A' THEN '적립'
             END                                                                 AS usageType
        FROM MU_MEMBERSHIP_HISTORY MMH
        LEFT JOIN MU_TREATMENT MT
                ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
        LEFT JOIN MU_TREATMENT_PROCEDURE MTP
                ON MTP.MU_TREATMENT_PROCEDURE_ID = MMH.MU_TREATMENT_PROCEDURE_ID
        LEFT JOIN MU_MEMBER MM2
                ON MMH.MU_MEMBER_ID = MM2.MU_MEMBER_ID
        LEFT JOIN MU_MEMBER MM
                ON MMH.RESERVE_MEMBER_ID = MM.MU_MEMBER_ID
        LEFT JOIN MU_USER MU_TO
                ON MMH.TRANSFER_TO_USER_ID = MU_TO.MU_USER_ID
        LEFT JOIN MU_USER MU_FROM
                ON MMH.TRANSFER_FROM_USER_ID = MU_FROM.MU_USER_ID
    WHERE MMH.USE_YN='Y'
        AND MMH.MU_USER_ID=#{muUserId}
        <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
            AND MT.TREATMENT_NAME != '비만'
            AND MT.TREATMENT_NAME != '피부'
            AND MT.TREATMENT_NAME != '쁘띠'
        </if>
        <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
            AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
        </if>
        <if test="usedType != null and usedType != ''">
            AND MMH.USAGE_TYPE = #{usedType}
        </if>
        <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
            AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
            AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
        </if>
        <choose>
            <when test="membershipSort != null and membershipSort != ''">
                ORDER BY ${membershipSort}
            </when>
            <otherwise>
                ORDER BY MMH.REG_DATE DESC
            </otherwise>
        </choose>
    </select>
    <select id="selectToTransferUser" parameterType="hashmap" resultType="hashmap">
        SELECT MU.MU_USER_ID                                       AS muUserId
              ,MU.MEMBERSHIP_YN                                    AS membershipYn
              ,MU.USER_NAME                                        AS userName
              ,MU.PHONE_NUMBER                                     AS phoneNumber
              ,IFNULL(DATE_FORMAT(MU.BIRTHDAY, '%Y-%m-%d'), '-')   AS birth
              ,IFNULL(TIMESTAMPDIFF(YEAR, MU.BIRTHDAY, CURDATE()), '-')
                                                                   AS age
              ,CASE MU.GENDER
               WHEN 'M' THEN '남'
               WHEN 'F' THEN '여'
               ELSE '-'
               END                                                 AS gender
              ,IFNULL(MCIN.CATEGORY_ITEM_NAME, '-')                AS nationality
              ,FORMAT(MM.MEMBERSHIP_BALANCE, 0)                    AS membershipBalance
              ,FORMAT(SUM(CASE
                          WHEN MMH.USAGE_TYPE = 'C' THEN MMH.RECHARGE_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'D' THEN -MMH.RECHARGE_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'P' THEN MMH.RECHARGE_AMOUNT
                          ELSE 0
                          END
                      ), 0)                                        AS sumChargeBalance
              ,FORMAT(SUM(CASE
                          WHEN MMH.USAGE_TYPE = 'U' THEN MMH.USED_AMOUNT
                          WHEN MMH.USAGE_TYPE = 'T' THEN MMH.USED_AMOUNT
                          ELSE 0
                          END
                      ), 0)                                        AS sumUsageBalance
          FROM MU_USER MU
     LEFT JOIN MU_MEMBERSHIP MM
            ON MU.MU_USER_ID = MM.MU_USER_ID
     LEFT JOIN MU_MEMBERSHIP_HISTORY MMH
            ON MU.MU_USER_ID = MMH.MU_USER_ID
     LEFT JOIN MU_CATEGORY_ITEM MCIN
            ON MCIN.MU_CATEGORY_ITEM_ID = MU.NATIONALITY
         WHERE MU.USE_YN = 'Y'
           AND MU.USER_TYPE2 ='Y'
        <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
           AND (MU.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
            OR MU.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
        </if>
      GROUP BY MU.MU_USER_ID
              ,MU.USER_NAME
              ,MU.BIRTHDAY
              ,MU.GENDER
              ,MCIN.CATEGORY_ITEM_NAME
              ,MM.MEMBERSHIP_BALANCE
      ORDER BY MU.USER_NAME
    </select>
    <select id="selectMembershipTransfer" parameterType="hashmap" resultType="hashmap">
        SELECT MU.USER_NAME                                   AS senderName
              ,IFNULL(DATE_FORMAT(MU.BIRTHDAY, '%Y-%m-%d'), '-')
                                                              AS senderBirthday
              ,IFNULL(TIMESTAMPDIFF(YEAR, MU.BIRTHDAY, CURDATE()), '-')
                                                              AS senderAge
              ,CASE MU.GENDER
               WHEN 'M' THEN '남'
               WHEN 'F' THEN '여'
               ELSE '-'
               END                                            AS senderGender
              ,IFNULL(MCIN.CATEGORY_ITEM_NAME, '-')           AS senderNationality
              ,MU.PHONE_NUMBER                                AS senderPhoneNumber
              ,FORMAT(MMH.BEFORE_AMOUNT, 0)                   AS senderBeforeAmount
              ,FORMAT(MMH.AFTER_AMOUNT, 0)                    AS senderAfterAmount
              ,MU2.USER_NAME                                  AS receiverName
              ,IFNULL(DATE_FORMAT(MU2.BIRTHDAY, '%Y-%m-%d'), '-')
                                                              AS receiverBirthday
              ,IFNULL(TIMESTAMPDIFF(YEAR, MU2.BIRTHDAY, CURDATE()), '-')
                                                              AS receiverAge
              ,CASE MU2.GENDER
               WHEN 'M' THEN '남'
               WHEN 'F' THEN '여'
               ELSE '-'
                END                                           AS receiverGender
              ,IFNULL(MCIN2.CATEGORY_ITEM_NAME, '-')          AS receiverNationality
              ,MU2.PHONE_NUMBER                               AS receiverPhoneNumber
              ,MMH2.BEFORE_AMOUNT                             AS receiverBeforeAmount
              ,MMH2.AFTER_AMOUNT                              AS receiverAfterAmount
              ,IFNULL(MMH.USED_AMOUNT, MMH.RECHARGE_AMOUNT)   AS transferAmount
              ,MMH.MEMO                                       AS memo
              ,DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')        AS writeDate
          FROM MU_MEMBERSHIP_HISTORY MMH
          JOIN MU_MEMBERSHIP_HISTORY MMH2
            ON MMH2.TRANSFER_HISTORY_ID = MMH.MU_MEMBERSHIP_HISTORY_ID
          JOIN MU_USER MU
            ON MMH.MU_USER_ID = MU.MU_USER_ID
          JOIN MU_USER MU2
            ON MMH2.MU_USER_ID = MU2.MU_USER_ID
     LEFT JOIN MU_CATEGORY_ITEM AS MCIN
            ON MCIN.MU_CATEGORY_ITEM_ID = MU.NATIONALITY
     LEFT JOIN MU_CATEGORY_ITEM AS MCIN2
            ON MCIN2.MU_CATEGORY_ITEM_ID = MU2.NATIONALITY
         WHERE MMH.MU_MEMBERSHIP_HISTORY_ID = #{muMembershipHistoryId}
            OR MMH2.MU_MEMBERSHIP_HISTORY_ID = #{muMembershipHistoryId}
    </select>
    <select id="selectMembershipCheckBatch" parameterType="hashmap" resultType="hashmap">
        SELECT MM.MU_MEMBERSHIP_ID   AS "muMembershipId"
          FROM MU_MEMBERSHIP AS MM
         WHERE MM.USE_YN = 'Y'
           AND MM.MU_USER_ID = #{muUserId}
        LIMIT 0, 1
    </select>
    <select id="selectMembershipHistoryCheckBatch" parameterType="hashmap" resultType="hashmap">
        SELECT COUNT(*)     AS "totalCount"
          FROM MU_MEMBERSHIP_HISTORY AS MMH
         WHERE MMH.USE_YN = 'Y'
           AND MMH.MU_USER_ID = #{muUserId}
    </select>
    <insert id="insertMembership" parameterType="hashmap">
        <selectKey resultType="string" keyProperty="id" order="BEFORE">
            SELECT CONCAT(#{muMembershipId},LPAD((SELECT NEXTVAL(MU_MEMBERSHIP_SEQ)), 11, 0))
        </selectKey>
        INSERT INTO MU_MEMBERSHIP(
            MU_MEMBERSHIP_ID
            ,MU_USER_ID
            ,MEMBERSHIP_BALANCE
            ,LAST_RECHARGE_DATE
            ,CUD_FLAG
            ,USE_YN
            ,REG_ID
            ,REG_DATE
            ,MOD_ID
            ,MOD_DATE
            ,T_ID
            ,T_DATE
        )VALUES(
            #{id}
            ,#{muUserId}
            ,#{membershipBalance}
            ,NOW()
            ,'C'
            ,'Y'
            ,#{regId}
            ,NOW()
            ,#{modId}
            ,NOW()
            ,#{tId}
            ,NOW()
        )
    </insert>
    <insert id="insertMembershipBatch" parameterType="hashmap">
        <selectKey resultType="string" keyProperty="id" order="BEFORE">
            SELECT CONCAT(#{muMembershipId},LPAD((SELECT NEXTVAL(MU_MEMBERSHIP_SEQ)), 11, 0))
        </selectKey>
        INSERT INTO MU_MEMBERSHIP(
            MU_MEMBERSHIP_ID
            ,MU_USER_ID
            ,MEMBERSHIP_BALANCE
            ,LAST_RECHARGE_DATE
            ,CUD_FLAG
            ,USE_YN
            ,REG_ID
            ,REG_DATE
            ,MOD_ID
            ,MOD_DATE
            ,T_ID
            ,T_DATE
        )VALUES(
            #{id}
            ,#{muUserId}
            ,(SELECT MMH.MEMBERSHIP_BALANCE
                FROM (
                      SELECT MMH.MU_USER_ID
                            ,SUM(MMH.RECHARGE_AMOUNT) - SUM(MMH.USED_AMOUNT)   AS MEMBERSHIP_BALANCE
                        FROM (
                              SELECT MMH.MU_USER_ID              AS MU_USER_ID
                                    ,IFNULL(USED_AMOUNT, 0)      AS USED_AMOUNT
                                    ,IFNULL(RECHARGE_AMOUNT, 0)  AS RECHARGE_AMOUNT
                                FROM MU_MEMBERSHIP_HISTORY AS MMH
                               WHERE MMH.USE_YN = 'Y'
                                 AND MMH.CRM_MEMBER_PAY_PID IS NOT NULL
                                 AND MMH.MU_USER_ID = #{muUserId}
                        ) AS MMH
                    GROUP BY MMH.MU_USER_ID
                ) AS MMH)
            ,NOW()
            ,'C'
            ,'Y'
            ,'BatchSystem'
            ,NOW()
            ,'BatchSystem'
            ,NOW()
            ,#{tId}
            ,#{tDate}
        )
    </insert>
    <insert id="insertMembershipHistory" parameterType="hashmap">
        <selectKey resultType="string" keyProperty="id" order="BEFORE">
            SELECT CONCAT(#{muMembershipHistoryId},LPAD((SELECT NEXTVAL(MU_MEMBERSHIP_HISTORY_SEQ)), 11, 0))
        </selectKey>
        INSERT INTO MU_MEMBERSHIP_HISTORY(
            MU_MEMBERSHIP_HISTORY_ID
            ,MU_USER_ID
            <if test="muTreatmentId != null and muTreatmentId != ''">
            ,MU_TREATMENT_ID
            </if>
            <if test="muTreatmentProcedureId != null and muTreatmentProcedureId != ''">
            ,MU_TREATMENT_PROCEDURE_ID
            </if>
            <if test="transferHistoryId != null and transferHistoryId != ''">
            ,TRANSFER_HISTORY_ID
            </if>
            <if test="transferFromUserId != null and transferFromUserId != ''">
            ,TRANSFER_FROM_USER_ID
            </if>
            <if test="transferToUserId != null and transferToUserId != ''">
            ,TRANSFER_TO_USER_ID
            </if>
            <if test="reserveMemberId != null and reserveMemberId != ''">
            ,RESERVE_MEMBER_ID
            </if>
            ,MU_MEMBER_ID
            <if test="beforeAmount != null and beforeAmount != ''">
            ,BEFORE_AMOUNT
            </if>
            <if test="afterAmount != null and afterAmount != ''">
            ,AFTER_AMOUNT
            </if>
            <if test="usedAmount != null and usedAmount != ''">
            ,USED_AMOUNT
            </if>
            <if test="rechargeAmount != null and rechargeAmount != ''">
            ,RECHARGE_AMOUNT
            </if>
            <if test="chargePaymentItemId != null and chargePaymentItemId != ''">
            ,CHARGE_PAYMENT_ITEM_ID
            </if>
            <if test="chargePaymentItemName != null and chargePaymentItemName != ''">
            ,CHARGE_PAYMENT_ITEM_NAME
            </if>
            <if test="memo != null and memo != ''">
            ,MEMO
            </if>
            ,USAGE_TYPE
            ,WRITE_DATE
            ,CUD_FLAG
            ,USE_YN
            ,REG_ID
            ,REG_DATE
            ,MOD_ID
            ,MOD_DATE
            ,T_ID
            ,T_DATE
        )VALUES(
            #{id}
            ,#{muUserId}
            <if test="muTreatmentId != null and muTreatmentId != ''">
            ,#{muTreatmentId}
            </if>
            <if test="muTreatmentProcedureId != null and muTreatmentProcedureId != ''">
            ,#{muTreatmentProcedureId}
            </if>
            <if test="transferHistoryId != null and transferHistoryId != ''">
            ,#{transferHistoryId}
            </if>
            <if test="transferFromUserId != null and transferFromUserId != ''">
            ,#{transferFromUserId}
            </if>
            <if test="transferToUserId != null and transferToUserId != ''">
            ,#{transferToUserId}
            </if>
            <if test="reserveMemberId != null and reserveMemberId != ''">
            ,#{reserveMemberId}
            </if>
            ,#{muMemberId}
            <if test="beforeAmount != null and beforeAmount != ''">
            ,#{beforeAmount}
            </if>
            <if test="afterAmount != null and afterAmount != ''">
            ,#{afterAmount}
            </if>
            <if test="usedAmount != null and usedAmount != ''">
            ,#{usedAmount}
            </if>
            <if test="rechargeAmount != null and rechargeAmount != ''">
            ,#{rechargeAmount}
            </if>
            <if test="chargePaymentItemId != null and chargePaymentItemId != ''">
            ,#{chargePaymentItemId}
            </if>
            <if test="chargePaymentItemName != null and chargePaymentItemName != ''">
            ,#{chargePaymentItemName}
            </if>
            <if test="memo != null and memo != ''">
            ,#{memo}
            </if>
            ,#{usageType}
            ,NOW()
            ,'C'
            ,'Y'
            ,#{regId}
            ,NOW()
            ,#{modId}
            ,NOW()
            ,#{tId}
            ,NOW()
        )
    </insert>

    <insert id="insertMembershipHistoryBatch" parameterType="hashmap">
        <selectKey resultType="string" keyProperty="id" order="BEFORE">
            SELECT CONCAT(#{muMembershipHistoryId},LPAD((SELECT NEXTVAL(MU_MEMBERSHIP_HISTORY_SEQ)), 11, 0))
        </selectKey>
        INSERT INTO MU_MEMBERSHIP_HISTORY(
                    MU_MEMBERSHIP_HISTORY_ID
                    ,MU_USER_ID
                    ,MU_TREATMENT_ID
                    ,MU_TREATMENT_PROCEDURE_ID
                    ,TRANSFER_HISTORY_ID
                    ,TRANSFER_FROM_USER_ID
                    ,TRANSFER_TO_USER_ID
                    ,RESERVE_MEMBER_ID
                    ,MU_MEMBER_ID
                    ,BEFORE_AMOUNT
                    ,AFTER_AMOUNT
                    ,USED_AMOUNT
                    ,RECHARGE_AMOUNT
                    ,MEMO
                    ,USAGE_TYPE
                    ,WRITE_DATE
                    ,CUD_FLAG
                    ,USE_YN
                    ,REG_ID
                    ,REG_DATE
                    ,MOD_ID
                    ,MOD_DATE
                    ,T_ID
                    ,T_DATE
                    ,CRM_MEMBER_PAY_PID
                    ,CRM_MEMBER_PAY_MB_PID
                    ,CRM_MEMBER_PAY_PAY_MEMO
                    ,CRM_MEMBER_PAY_PAY_MEMO2
                    ,CRM_MEMBER_PAY_M_DIVI1
                    ,CRM_MEMBER_PAY_M_DIVI2
                    ,CRM_MEMBER_PAY_M_DIVI3
                    ,CRM_MEMBER_PAY_M_DIVI4
                    ,CRM_MEMBER_PAY_M_DIVI1_NAME
                    ,CRM_MEMBER_PAY_M_DIVI2_NAME
                    ,CRM_MEMBER_PAY_M_DIVI3_NAME
                    ,CRM_MEMBER_PAY_M_DIVI4_NAME
                    ,CRM_MEMBER_PAY_PAY_DOCTOR
                    ,CRM_MEMBER_PAY_DOCTOR_NAME
                    ,CRM_MEMBER_PAY_PAY_STAFF
                    ,CRM_MEMBER_PAY_STAFF_NAME
                    ,CRM_MEMBER_PAY_PAY_STAFF2
                    ,CRM_MEMBER_PAY_STAFF_NAME2
                    ,CRM_MEMBER_PAY_PAY_DIVI1
                    ,CRM_MEMBER_PAY_PAY_DIVI2
                    ,CRM_MEMBER_PAY_M_CNT
                    ,CRM_MEMBER_PAY_M_CNT_DIVI
                    ,CRM_MEMBER_PAY_PAY_MEMBERSHIP
                    ,CRM_MEMBER_PAY_PAY_SUM
                    ,CRM_MEMBER_PAY_PAY_CARD
                    ,CRM_MEMBER_PAY_PAY_CASH_RECEIPT_TYPE
                    ,CRM_MEMBER_PAY_PAY_CASH_RECEIPT
                    ,CRM_MEMBER_PAY_PAY_CASH
                    ,CRM_MEMBER_PAY_PAY_CASH_BANK
                    ,CRM_MEMBER_PAY_PAY_VAT
                    ,CRM_MEMBER_PAY_PAY_DEBT
                    ,CRM_MEMBER_PAY_PAY_BACK
                    ,CRM_MEMBER_PAY_TAX_FREE
                    ,CRM_MEMBER_PAY_PAY_RECEIPT
                    ,CRM_MEMBER_PAY_PAY_CARD_NAME
                    ,CRM_MEMBER_PAY_STAFF_PID
                    ,CRM_MEMBER_PAY_PAY_BACK_CARD_NAME
                    ,CRM_MEMBER_PAY_PAY_BACK_CARD_COMMISSION
                    ,CRM_MEMBER_PAY_PAY_BACK_CARD_COMMISSION_PAY
                    ,CRM_MEMBER_PAY_PAY_BACK_CARD_IN
                    ,CRM_MEMBER_PAY_PAY_SUM_CARD_NAME
                    ,CRM_MEMBER_PAY_PAY_SUM_CARD_COMMISSION
                    ,CRM_MEMBER_PAY_PAY_SUM_CARD_COMMISSION_PAY
                    ,CRM_MEMBER_PAY_PAY_SUM_CARD_IN
                    ,CRM_MEMBER_PAY_PAY_SUM_CARD
                    ,CRM_MEMBER_PAY_PAY_TYPE
                    ,CRM_MEMBER_PAY_PAY_COUNTRY
                    ,CRM_MEMBER_PAY_MBSHIP_NOTE
                    ,CRM_MEMBER_PAY_MBSHIP_TYPE
        )     SELECT #{id}                                       AS MU_MEMBERSHIP_HISTORY_ID <!-- 식별자 -->
                    ,#{muUserId}                                 AS MU_USER_ID <!-- 고객 식별자 -->
                    ,(SELECT MCI.MU_CATEGORY_ITEM_ID
                        FROM MU_CATEGORY_ITEM AS MCI
                       WHERE MCI.MU_CATEGORY_ID = 'C17128016604480000000005'
                         AND MCI.CATEGORY_ITEM_NAME = (CASE
                                                       WHEN CMP.M_DIVI1_NAME LIKE '%비만%'
                                                       THEN '비만'
                                                       WHEN CMP.M_DIVI1_NAME = '쁘띠'
                                                       THEN '쁘띠'
                                                       WHEN CMP.M_DIVI1_NAME = '제모'
                                                       THEN '제모'
                                                       WHEN CMP.M_DIVI1_NAME = '피부'
                                                       THEN '피부'
                                                       ELSE '기타'
                                                       END))     AS MU_TREATMENT_ID <!-- 진료 식별자 -->
                    ,NULL                                        AS MU_TREATMENT_PROCEDURE_ID <!-- 시술 식별자 -->
                    ,NULL                                        AS TRANSFER_HISTORY_ID <!-- 양도/양수 내역 식별자 -->
                    ,CASE
                     WHEN CMP.M_DIVI2_NAME LIKE '%양도%'
                      AND CMP.PAY_MEMBERSHIP &lt; 0      <!-- 구분에 '양도'가 들어가면서 0 보다 작으면 : 양도 -->
                     THEN (SELECT MU_USER_ID
                             FROM MU_USER AS MU
                            WHERE MU.CRM_MEMBER_PID = CMP.MB_PID
                            LIMIT 0, 1)
                     END                                         AS TRANSFER_FROM_USER_ID <!-- 양도자 식별자 -->
                    ,CASE
                     WHEN CMP.M_DIVI2_NAME LIKE '%양도%'
                      AND CMP.PAY_MEMBERSHIP &gt; 0      <!-- 구분에 '양도'가 들어가면서 0 보다 크면 : 양도받음 -->
                     THEN (SELECT MU_USER_ID
                             FROM MU_USER AS MU
                            WHERE MU.CRM_MEMBER_PID = CMP.MB_PID
                            LIMIT 0, 1)
                     END                                         AS TRANSFER_TO_USER_ID <!-- 양수자 식별자 -->
                    ,NULL                                        AS RESERVE_MEMBER_ID <!-- 담당의사 -->
                    ,NULL                                        AS MU_MEMBER_ID <!-- 담당자 -->
                    ,0                                           AS BEFORE_AMOUNT <!-- 기존 보유 멤버십 금액 -->
                    ,0                                           AS AFTER_AMOUNT <!-- 이후 보유 멤버십 금액 -->
                    ,CASE
                     WHEN CMP.M_DIVI2_NAME LIKE '%양도%'
                      AND CMP.PAY_MEMBERSHIP &gt; 0      <!-- 구분에 '양도'가 들어가면서 0 보다 크면 : 양도받음 -->
                     THEN NULL
                     WHEN CMP.M_DIVI1_NAME = '멤버쉽'
                      AND CMP.M_DIVI2_NAME != ''
                     THEN NULL
                     WHEN CMP.M_DIVI2_NAME LIKE '%멤버쉽%'
                     THEN NULL
                     WHEN CMP.M_DIVI2_NAME LIKE '%멤버십%'
                     THEN NULL
                     WHEN CMP.M_DIVI1_NAME = '멤버쉽'
                      AND CMP.MBSHIP_TYPE LIKE '%멤버쉽%'
                     THEN NULL
                     ELSE ABS(CMP.PAY_MEMBERSHIP)
                     END                                         AS USED_AMOUNT <!-- 멤버십 사용금액 -->
                    ,CASE
                     WHEN CMP.M_DIVI2_NAME LIKE '%양도%'
                      AND CMP.PAY_MEMBERSHIP &gt; 0      <!-- 구분에 '양도'가 들어가면서 0 보다 크면 : 양도받음 -->
                     THEN ABS(CMP.PAY_MEMBERSHIP)
                     WHEN CMP.M_DIVI1_NAME = '멤버쉽'
                      AND CMP.M_DIVI2_NAME != ''      <!-- 구분에 ''이 아니면 충전 또는 적립 -->
                     THEN ABS(CMP.PAY_MEMBERSHIP)
                     WHEN CMP.M_DIVI2_NAME LIKE '%멤버쉽%'
                     THEN ABS(CMP.PAY_MEMBERSHIP)
                     WHEN CMP.M_DIVI2_NAME LIKE '%멤버십%'
                     THEN ABS(CMP.PAY_MEMBERSHIP)
                     WHEN CMP.M_DIVI1_NAME = '멤버쉽'
                      AND CMP.MBSHIP_TYPE LIKE '%멤버쉽%'
                     THEN ABS(CMP.PAY_MEMBERSHIP)
                     END                                         AS RECHARGE_AMOUNT <!-- 멤버십 충전금액 -->
                    ,CONCAT(CMP.PAY_MEMO, '\n', CMP.PAY_MEMO2)   AS MEMO <!-- 결제메모 -->
                    ,CASE
                     WHEN CMP.M_DIVI2_NAME LIKE '%양도%'
                      AND CMP.PAY_MEMBERSHIP &lt; 0      <!-- 구분에 '양도'가 들어가면서 0 보다 작으면 : 양도 -->
                     THEN 'T'
                     WHEN CMP.M_DIVI2_NAME LIKE '%양도%'
                      AND CMP.PAY_MEMBERSHIP &gt; 0      <!-- 구분에 '양도'가 들어가면서 0 보다 크면 : 양도받음 -->
                     THEN 'P'
                     WHEN CMP.M_DIVI2_NAME LIKE '%멤버쉽%'
                     THEN 'C'
                     WHEN CMP.M_DIVI2_NAME LIKE '%멤버십%'
                     THEN 'C'
                     WHEN CMP.M_DIVI1_NAME = '멤버쉽'
                      AND CMP.MBSHIP_TYPE LIKE '%멤버쉽%'
                     THEN 'C'
                     WHEN CMP.PAY_MEMBERSHIP &lt; CMP.PAY_SUM
                     THEN 'U'
                     ELSE ''
                      END                                        AS USAGE_TYPE <!-- 사용구분(C:충전, U: 사용, T:양도 P:양수 D: 환불,A:적립) -->
                    ,CMP.PAY_DATE                                AS WRITE_DATE <!-- 작성일자 -->
                    ,'C'                                         AS CUD_FLAG <!-- 작업타입 (C: 등록, U: 수정, D : 삭제) -->
                    ,CASE
                     WHEN UPPER(CMP.LIST_DEL) = 'N'
                     THEN 'Y'
                     WHEN UPPER(CMP.LIST_DEL) = 'Y'
                     THEN 'N'
                     ELSE ''
                      END                                        AS USE_YN <!-- 사용여부 -->
                    ,'BatchSystem'                               AS REG_ID <!-- 등록자 -->
                    ,CMP.REG_DATE                                AS REG_DATE <!-- 등록일자 -->
                    ,'BatchSystem'                               AS MOD_ID <!-- 수정자 -->
                    ,CMP.UP_DATE                                 AS MOD_DATE <!-- 수정일자 -->
                    ,#{tId}                                      AS T_ID
                    ,#{tDate}                                    AS T_DATE
                    ,CMP.PID                                     AS CRM_MEMBER_PAY_PID <!-- 기존 DB 식별자 -->
                    ,CMP.MB_PID                                  AS CRM_MEMBER_PAY_MB_PID <!-- 기존 DB 고객 식별자 -->
                    ,CMP.PAY_MEMO                                AS CRM_MEMBER_PAY_PAY_MEMO <!-- 기존 DB 메모 -->
                    ,CMP.PAY_MEMO2                               AS CRM_MEMBER_PAY_PAY_MEMO2 <!-- 기존 DB 메모2 -->
                    ,CMP.M_DIVI1                                 AS CRM_MEMBER_PAY_M_DIVI1 <!-- 기존 DB 시술분류 (진료 식별자) -->
                    ,CMP.M_DIVI2                                 AS CRM_MEMBER_PAY_M_DIVI2 <!-- 기존 DB 시술분류 (진료 시술 식별자) -->
                    ,CMP.M_DIVI3                                 AS CRM_MEMBER_PAY_M_DIVI3 <!-- 기존 DB 시술분류 (진료 시술 식별자) -->
                    ,CMP.M_DIVI4                                 AS CRM_MEMBER_PAY_M_DIVI4 <!-- 기존 DB 시술분류 (진료 시술 식별자) -->
                    ,CMP.M_DIVI1_NAME                            AS CRM_MEMBER_PAY_M_DIVI1_NAME <!-- 기존 DB 시술분류 (진료명) -->
                    ,CMP.M_DIVI2_NAME                            AS CRM_MEMBER_PAY_M_DIVI2_NAME <!-- 기존 DB 시술분류 (진료 시술명) -->
                    ,CMP.M_DIVI3_NAME                            AS CRM_MEMBER_PAY_M_DIVI3_NAME <!-- 기존 DB 시술분류 (진료 시술명) -->
                    ,CMP.M_DIVI4_NAME                            AS CRM_MEMBER_PAY_M_DIVI4_NAME <!-- 기존 DB 시술분류 (진료 시술명) -->
                    ,CMP.PAY_DOCTOR                              AS CRM_MEMBER_PAY_PAY_DOCTOR <!-- 기존 DB 담당의사 식별자 -->
                    ,CMP.DOCTOR_NAME                             AS CRM_MEMBER_PAY_DOCTOR_NAME <!-- 기존 DB 담당의사 이름 -->
                    ,CMP.PAY_STAFF                               AS CRM_MEMBER_PAY_PAY_STAFF <!-- 기존 DB 담당자 식별자 -->
                    ,CMP.STAFF_NAME                              AS CRM_MEMBER_PAY_STAFF_NAME <!-- 기존 DB 담당자 이름 -->
                    ,CMP.PAY_STAFF2                              AS CRM_MEMBER_PAY_PAY_STAFF2 <!-- 기존 DB 담당자 식별자2 -->
                    ,CMP.STAFF_NAME2                             AS CRM_MEMBER_PAY_STAFF_NAME2 <!-- 기존 DB 담당자 이름2 -->
                    ,CMP.PAY_DIVI1                               AS CRM_MEMBER_PAY_PAY_DIVI1 <!-- 기존 DB 결제상태 -->
                    ,CMP.PAY_DIVI2                               AS CRM_MEMBER_PAY_PAY_DIVI2 <!-- 기존 DB 결제상태2 -->
                    ,CMP.M_CNT                                   AS CRM_MEMBER_PAY_M_CNT <!-- 기존 DB 초진/재진 카운트 -->
                    ,CMP.M_CNT_DIVI                              AS CRM_MEMBER_PAY_M_CNT_DIVI <!-- 기존 DB 초진/재진 구분 -->
                    ,CMP.PAY_MEMBERSHIP                          AS CRM_MEMBER_PAY_PAY_MEMBERSHIP <!-- 기존 DB 멤버쉽 -->
                    ,CMP.PAY_SUM                                 AS CRM_MEMBER_PAY_PAY_SUM <!-- 기존 DB 계 -->
                    ,CMP.PAY_CARD                                AS CRM_MEMBER_PAY_PAY_CARD <!-- 기존 DB 카드 -->
                    ,CMP.PAY_CASH_RECEIPT_TYPE                   AS CRM_MEMBER_PAY_PAY_CASH_RECEIPT_TYPE <!-- 기존 DB 현금영수증(현금, 통장) 구분 -->
                    ,CMP.PAY_CASH_RECEIPT                        AS CRM_MEMBER_PAY_PAY_CASH_RECEIPT <!-- 기존 DB 현금영수증 금액 -->
                    ,CMP.PAY_CASH                                AS CRM_MEMBER_PAY_PAY_CASH <!-- 기존 DB 현금 -->
                    ,CMP.PAY_CASH_BANK                           AS CRM_MEMBER_PAY_PAY_CASH_BANK <!-- 기존 DB 통장 -->
                    ,CMP.PAY_VAT                                 AS CRM_MEMBER_PAY_PAY_VAT <!-- 기존 DB vat -->
                    ,CMP.PAY_DEBT                                AS CRM_MEMBER_PAY_PAY_DEBT <!-- 기존 DB 미수 -->
                    ,CMP.PAY_BACK                                AS CRM_MEMBER_PAY_PAY_BACK <!-- 기존 DB 환불 -->
                    ,CMP.TAX_FREE                                AS CRM_MEMBER_PAY_TAX_FREE <!-- 기존 DB TAX_FREE -->
                    ,CMP.PAY_RECEIPT                             AS CRM_MEMBER_PAY_PAY_RECEIPT <!-- 기존 DB 영수증 -->
                    ,CMP.PAY_CARD_NAME                           AS CRM_MEMBER_PAY_PAY_CARD_NAME <!-- 기존 DB 결제카드명 -->
                    ,CMP.STAFF_PID                               AS CRM_MEMBER_PAY_STAFF_PID <!-- 기존 DB 직원 식별자 -->
                    ,CMP.PAY_BACK_CARD_NAME                      AS CRM_MEMBER_PAY_PAY_BACK_CARD_NAME <!-- 기존 DB 결제취소 카드명 -->
                    ,CMP.PAY_BACK_CARD_COMMISSION                AS CRM_MEMBER_PAY_PAY_BACK_CARD_COMMISSION <!-- 기존 DB 결제취소 카드 수수료 -->
                    ,CMP.PAY_BACK_CARD_COMMISSION_PAY            AS CRM_MEMBER_PAY_PAY_BACK_CARD_COMMISSION_PAY <!-- 기존 DB 결제취소 수수료 금액 -->
                    ,CMP.PAY_BACK_CARD_IN                        AS CRM_MEMBER_PAY_PAY_BACK_CARD_IN <!-- 기존 DB 결제취소 금액 -->
                    ,CMP.PAY_SUM_CARD_NAME                       AS CRM_MEMBER_PAY_PAY_SUM_CARD_NAME <!-- 기존 DB 결제 카드명 -->
                    ,CMP.PAY_SUM_CARD_COMMISSION                 AS CRM_MEMBER_PAY_PAY_SUM_CARD_COMMISSION <!-- 기존 DB 카드 수수료% -->
                    ,CMP.PAY_SUM_CARD_COMMISSION_PAY             AS CRM_MEMBER_PAY_PAY_SUM_CARD_COMMISSION_PAY <!-- 기존 DB 카드 수수료 금액 -->
                    ,CMP.PAY_SUM_CARD_IN                         AS CRM_MEMBER_PAY_PAY_SUM_CARD_IN <!-- 기존 DB 정산금액 -->
                    ,CMP.PAY_SUM_CARD                            AS CRM_MEMBER_PAY_PAY_SUM_CARD <!-- 기존 DB 카드사 식별번호 -->
                    ,CMP.PAY_TYPE                                AS CRM_MEMBER_PAY_PAY_TYPE <!-- 기존 DB 결제타입 -->
                    ,CMP.PAY_COUNTRY                             AS CRM_MEMBER_PAY_PAY_COUNTRY <!-- 기존 DB 결제국가 -->
                    ,CMP.MBSHIP_NOTE                             AS CRM_MEMBER_PAY_MBSHIP_NOTE <!-- 기존 DB 멤버쉽 비고 -->
                    ,CMP.MBSHIP_TYPE                             AS CRM_MEMBER_PAY_MBSHIP_TYPE <!-- 기존 DB 멤버십 타입(멤버십 상품) -->
                FROM CRM_MEMBER_PAY AS CMP
               WHERE CMP.PID = #{crmMemberPayPid}
    </insert>
    <insert id="insertTreatmentProcedurePrice" parameterType="hashmap">
        <selectKey resultType="string" keyProperty="id" order="BEFORE">
            SELECT CONCAT(#{muTreatmentProcedurePriceId},LPAD((SELECT NEXTVAL(MU_TREATMENT_PROCEDURE_PRICE_SEQ)), 9, 0))
        </selectKey>
        INSERT INTO MU_TREATMENT_PROCEDURE_PRICE(
            MU_TREATMENT_PROCEDURE_PRICE_ID
            ,MU_TREATMENT_PROCEDURE_ID
            ,INSURANCE_TYPE
            ,PRICE
            ,VAT
            ,ADDITIONAL_AMOUNT
            ,WRITE_DATE
            ,WRITE_TIME
            ,CUD_FLAG
            ,USE_YN
            ,REG_ID
            ,REG_DATE
            ,MOD_ID
            ,MOD_DATE
            ,T_ID
            ,T_DATE
        )VALUES(
            #{id}
            ,#{muTreatmentProcedureId}
            ,#{insuranceType}
            ,#{price}
            ,#{vat}
            ,#{additionalAmount}
            ,CURDATE()
            ,CURTIME()
            ,'C'
            ,'Y'
            ,#{regId}
            ,NOW()
            ,#{modId}
            ,NOW()
            ,#{tId}
            ,#{tDate}
        )
    </insert>
    <insert id="insertMembershipProcedure" parameterType="hashmap">
        <selectKey resultType="hashmap" keyProperty="key" order="BEFORE">
			SELECT CONCAT(#{muTreatmentProcedureId},LPAD((SELECT NEXTVAL(MU_TREATMENT_PROCEDURE_SEQ)), 10, 0)) AS id
                   ,MU_TREATMENT_ID AS muTreatmentId
            FROM MU_TREATMENT
            WHERE TREATMENT_NAME='멤버십'
            AND USE_YN='Y'
            LIMIT 0,1
		</selectKey>
		INSERT INTO MU_TREATMENT_PROCEDURE(
					 MU_TREATMENT_PROCEDURE_ID
					,MU_TREATMENT_ID
					,TREATMENT_PROCEDURE_NAME
					,ENABLE_YN
					,WRITE_DATE
					,WRITE_TIME
					,CUD_FLAG
					,USE_YN
					,REG_ID
					,REG_DATE
					,MOD_ID
					,MOD_DATE
					,T_ID
					,T_DATE
		)VALUES(
					 #{key.id}
					,#{key.muTreatmentId}
					,#{procedureName}
					,'Y'
					,CURDATE()
					,CURTIME()
					,'C'
					,'Y'
					,#{muMemberId}
					,NOW()
					,#{muMemberId}
					,NOW()
					,#{tId}
					,#{tDate}
		)
    </insert>

    <update id="updateMembership" parameterType="hashmap">
        UPDATE MU_MEMBERSHIP
        SET
        MEMBERSHIP_BALANCE =  #{membershipBalance}
        <if test="lastRechargeDate != null and lastRechargeDate != ''">
            ,LAST_RECHARGE_DATE = #{lastRechargeDate}
        </if>
        <if test="lastUseDate != null and lastUseDate != ''">
            ,LAST_USE_DATE =  #{lastUseDate}
        </if>
        ,CUD_FLAG = 'U'
        ,USE_YN = 'Y'
        ,MOD_ID = #{modId}
        ,MOD_DATE = NOW()
        ,T_ID = #{tId}
        ,T_DATE = NOW()
        WHERE MU_USER_ID = #{muUserId}
        AND  USE_YN        = 'Y'
    </update>

    <update id="updateMembershipBatch" parameterType="hashmap">
        UPDATE MU_MEMBERSHIP
           SET MOD_ID   = #{modId}
              ,MOD_DATE = NOW()
              ,CUD_FLAG = 'U'
              ,MEMBERSHIP_BALANCE =  (SELECT MMH.MEMBERSHIP_BALANCE
                                        FROM (
                                              SELECT MMH.MU_USER_ID
                                                    ,SUM(MMH.RECHARGE_AMOUNT) - SUM(MMH.USED_AMOUNT)   AS MEMBERSHIP_BALANCE
                                                FROM (
                                                      SELECT MMH.MU_USER_ID              AS MU_USER_ID
                                                            ,IFNULL(USED_AMOUNT, 0)      AS USED_AMOUNT
                                                            ,IFNULL(RECHARGE_AMOUNT, 0)  AS RECHARGE_AMOUNT
                                                        FROM MU_MEMBERSHIP_HISTORY AS MMH
                                                       WHERE MMH.USE_YN = 'Y'
                                                         AND MMH.CRM_MEMBER_PAY_PID IS NOT NULL
                                                         AND MMH.MU_USER_ID = #{muUserId}
                                                ) AS MMH
                                            GROUP BY MMH.MU_USER_ID
                                        ) AS MMH)
         WHERE USE_YN = 'Y'
           AND MU_USER_ID = #{muUserId}
    </update>

    <select id="selectTotalUseMembershipCount" parameterType="hashmap" resultType="Integer">
        SELECT COUNT(1) AS totalCount
          FROM (
                SELECT DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')               AS WRITE_DATE
                      ,MU.USER_NAME                                          AS USER_NAME
                      ,MT.TREATMENT_NAME                                     AS TREATMENT_NAME
                      ,MTP.TREATMENT_PROCEDURE_NAME                          AS TREATMENT_PROCEDURE_NAME
                      ,MM.NAME                                               AS MEMBER_NAME
                      ,MM2.NAME                                              AS RESERVE_MEMBER_NAME
                      ,IF(MMH.USAGE_TYPE ='D',RECHARGE_AMOUNT,-USED_AMOUNT)  AS USED_AMOUNT
                      ,MMH.MEMO                                              AS MEMO
                      ,CASE MMH.USAGE_TYPE
                       WHEN 'U' THEN '사용'
                       WHEN 'D' THEN '환불'
                       END                                                   AS USAGE_TYPE
                      ,MU.PHONE_NUMBER                                       AS PHONE_NUMBER
                      ,MMH.REG_DATE                                          AS REG_DATE
                  FROM MU_MEMBERSHIP_HISTORY MMH
             LEFT JOIN MU_TREATMENT MT
                    ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
             LEFT JOIN MU_TREATMENT_PROCEDURE MTP
                    ON MMH.MU_TREATMENT_PROCEDURE_ID = MTP.MU_TREATMENT_PROCEDURE_ID
                  JOIN MU_USER MU
                    ON MMH.MU_USER_ID=MU.MU_USER_ID
                  JOIN MU_MEMBER MM
                    ON MMH.MU_MEMBER_ID = MM.MU_MEMBER_ID
             LEFT JOIN MU_MEMBER MM2
                    ON MMH.RESERVE_MEMBER_ID = MM2.MU_MEMBER_ID
                 WHERE USAGE_TYPE!='T'
                   AND USAGE_TYPE!='P'
                   AND USAGE_TYPE!='A'
                   AND USAGE_TYPE!='C'
                   AND MMH.CRM_MEMBER_PAY_PID IS NULL
                <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
                   AND (MU.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
                    OR MU.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
                </if>
                <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                   AND MT.TREATMENT_NAME != '비만'
                   AND MT.TREATMENT_NAME != '피부'
                   AND MT.TREATMENT_NAME != '쁘띠'
                </if>
                <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                   AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
                </if>
                <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
                </if>

             UNION ALL

                SELECT DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')                         AS WRITE_DATE
                      ,(SELECT MU.USER_NAME
                          FROM MU_USER AS MU
                         WHERE MU.USE_YN = 'Y'
                           AND MU.MU_USER_ID = MMH.MU_USER_ID
                         LIMIT 0, 1)                                                   AS USER_NAME
                      ,MMH.CRM_MEMBER_PAY_M_DIVI1_NAME                                 AS TREATMENT_NAME
                      ,CASE
                       WHEN CRM_MEMBER_PAY_M_DIVI4_NAME != ''
                       THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI3_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI4_NAME)
                       WHEN CRM_MEMBER_PAY_M_DIVI3_NAME != ''
                       THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI3_NAME)
                       WHEN CRM_MEMBER_PAY_M_DIVI2_NAME != ''
                       THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME)
                       ELSE ''
                        END                                                            AS TREATMENT_PROCEDURE_NAME
                      ,MMH.CRM_MEMBER_PAY_STAFF_NAME                                   AS MEMBER_NAME
                      ,MMH.CRM_MEMBER_PAY_DOCTOR_NAME                                  AS RESERVE_MEMBER_NAME
                      ,IF(MMH.USAGE_TYPE ='D', MMH.RECHARGE_AMOUNT, -MMH.USED_AMOUNT)  AS USED_AMOUNT
                      ,MMH.MEMO                                                        AS MEMO
                      ,CASE MMH.USAGE_TYPE
                       WHEN 'U' THEN '사용'
                       WHEN 'D' THEN '환불'
                       END                                                             AS USAGE_TYPE
                      ,(SELECT MU.PHONE_NUMBER
                          FROM MU_USER AS MU
                         WHERE MU.USE_YN = 'Y'
                           AND MU.MU_USER_ID = MMH.MU_USER_ID
                         LIMIT 0, 1)                                                   AS PHONE_NUMBER
                      ,MMH.REG_DATE                                                    AS REG_DATE
                  FROM MU_MEMBERSHIP_HISTORY AS MMH
                 WHERE MMH.USE_YN = 'Y'
                   AND MMH.USAGE_TYPE != 'T'
                   AND MMH.USAGE_TYPE != 'P'
                   AND MMH.USAGE_TYPE != 'A'
                   AND MMH.USAGE_TYPE != 'C'
                   AND MMH.CRM_MEMBER_PAY_PID IS NOT NULL
                <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                   AND MMH.TREATMENT_NAME != '비만'
                   AND MMH.TREATMENT_NAME != '피부'
                   AND MMH.TREATMENT_NAME != '쁘띠'
                </if>
                <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                   AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
                </if>
                <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
                </if>
          ) AS MMH
         WHERE 1 = 1
        <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
           AND (MMH.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
            OR MMH.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
        </if>
    </select>

    <select id="selectUseMembershipList" parameterType="hashmap" resultType="hashmap">
        SELECT MMH.WRITE_DATE                AS writeDate
              ,MMH.USER_NAME                 AS userName
              ,MMH.TREATMENT_NAME            AS treatmentName
              ,MMH.TREATMENT_PROCEDURE_NAME  AS treatmentProcedureName
              ,MMH.MEMBER_NAME               AS muMemberName
              ,MMH.RESERVE_MEMBER_NAME       AS reserveMemberName
              ,MMH.USED_AMOUNT               AS usedAmount
              ,MMH.MEMO                      AS memo
              ,MMH.USAGE_TYPE                AS usageType
              ,MMH.PHONE_NUMBER              AS phoneNumber
              ,MMH.REG_DATE                  AS regDate
          FROM (
                SELECT DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')               AS WRITE_DATE
                      ,MU.USER_NAME                                          AS USER_NAME
                      ,MT.TREATMENT_NAME                                     AS TREATMENT_NAME
                      ,MTP.TREATMENT_PROCEDURE_NAME                          AS TREATMENT_PROCEDURE_NAME
                      ,MM.NAME                                               AS MEMBER_NAME
                      ,MM2.NAME                                              AS RESERVE_MEMBER_NAME
                      ,IF(MMH.USAGE_TYPE ='D',RECHARGE_AMOUNT,-USED_AMOUNT)  AS USED_AMOUNT
                      ,MMH.MEMO                                              AS MEMO
                      ,CASE MMH.USAGE_TYPE
                       WHEN 'U' THEN '사용'
                       WHEN 'D' THEN '환불'
                       END                                                   AS USAGE_TYPE
                      ,MU.PHONE_NUMBER                                       AS PHONE_NUMBER
                      ,MMH.REG_DATE                                          AS REG_DATE
                  FROM MU_MEMBERSHIP_HISTORY MMH
             LEFT JOIN MU_TREATMENT MT
                    ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
             LEFT JOIN MU_TREATMENT_PROCEDURE MTP
                    ON MMH.MU_TREATMENT_PROCEDURE_ID = MTP.MU_TREATMENT_PROCEDURE_ID
                  JOIN MU_USER MU
                    ON MMH.MU_USER_ID=MU.MU_USER_ID
                  JOIN MU_MEMBER MM
                    ON MMH.MU_MEMBER_ID = MM.MU_MEMBER_ID
             LEFT JOIN MU_MEMBER MM2
                    ON MMH.RESERVE_MEMBER_ID = MM2.MU_MEMBER_ID
                 WHERE USAGE_TYPE!='T'
                   AND USAGE_TYPE!='P'
                   AND USAGE_TYPE!='A'
                   AND USAGE_TYPE!='C'
                   AND MMH.CRM_MEMBER_PAY_PID IS NULL
                <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                   AND MT.TREATMENT_NAME != '비만'
                   AND MT.TREATMENT_NAME != '피부'
                   AND MT.TREATMENT_NAME != '쁘띠'
                </if>
                <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                   AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
                </if>
                <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
                </if>

             UNION ALL

                SELECT DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d')                         AS WRITE_DATE
                      ,(SELECT MU.USER_NAME
                          FROM MU_USER AS MU
                         WHERE MU.USE_YN = 'Y'
                           AND MU.MU_USER_ID = MMH.MU_USER_ID
                         LIMIT 0, 1)                                                   AS USER_NAME
                      ,MMH.CRM_MEMBER_PAY_M_DIVI1_NAME                                 AS TREATMENT_NAME
                      ,CASE
                       WHEN CRM_MEMBER_PAY_M_DIVI4_NAME != ''
                       THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI3_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI4_NAME)
                       WHEN CRM_MEMBER_PAY_M_DIVI3_NAME != ''
                       THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME, '/', MMH.CRM_MEMBER_PAY_M_DIVI3_NAME)
                       WHEN CRM_MEMBER_PAY_M_DIVI2_NAME != ''
                       THEN CONCAT(MMH.CRM_MEMBER_PAY_M_DIVI2_NAME)
                       ELSE ''
                        END                                                            AS TREATMENT_PROCEDURE_NAME
                      ,MMH.CRM_MEMBER_PAY_STAFF_NAME                                   AS MEMBER_NAME
                      ,MMH.CRM_MEMBER_PAY_DOCTOR_NAME                                  AS RESERVE_MEMBER_NAME
                      ,IF(MMH.USAGE_TYPE ='D', MMH.RECHARGE_AMOUNT, -MMH.USED_AMOUNT)  AS USED_AMOUNT
                      ,MMH.MEMO                                                        AS MEMO
                      ,CASE MMH.USAGE_TYPE
                       WHEN 'U' THEN '사용'
                       WHEN 'D' THEN '환불'
                       END                                                             AS USAGE_TYPE
                      ,(SELECT MU.PHONE_NUMBER
                          FROM MU_USER AS MU
                         WHERE MU.USE_YN = 'Y'
                           AND MU.MU_USER_ID = MMH.MU_USER_ID
                         LIMIT 0, 1)                                                   AS PHONE_NUMBER
                      ,MMH.REG_DATE                                                    AS REG_DATE
                  FROM MU_MEMBERSHIP_HISTORY AS MMH
                 WHERE MMH.USE_YN = 'Y'
                   AND MMH.USAGE_TYPE != 'T'
                   AND MMH.USAGE_TYPE != 'P'
                   AND MMH.USAGE_TYPE != 'A'
                   AND MMH.USAGE_TYPE != 'C'
                   AND MMH.CRM_MEMBER_PAY_PID IS NOT NULL
                <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                   AND MMH.TREATMENT_NAME != '비만'
                   AND MMH.TREATMENT_NAME != '피부'
                   AND MMH.TREATMENT_NAME != '쁘띠'
                </if>
                <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                   AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
                </if>
                <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                   AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
                </if>
          ) AS MMH
         WHERE 1 = 1
        <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
           AND (MMH.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
            OR MMH.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
        </if>
        <choose>
        <when test="membershipSort != null and membershipSort != ''">
      ORDER BY ${membershipSort}
        </when>
        <otherwise>
      ORDER BY MMH.REG_DATE DESC
        </otherwise>
        </choose>
        <if test="membershipStart != null and membershipStart != ''">
         LIMIT ${membershipStart}
        <if test="membershipLimit != null and membershipLimit != ''">
              ,${membershipLimit}
        </if>
        </if>
    </select>

    <select id="selectUseMembershipExcel" parameterType="hashmap" resultType="hashmap">
       SELECT DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') AS writeDate
               ,MU.USER_NAME                    AS userName
               ,MT.TREATMENT_NAME               AS treatmentName
               ,MTP.TREATMENT_PROCEDURE_NAME    AS treatmentProcedureName
               ,MM.NAME                         AS muMemberName
               ,MM2.NAME                        AS reserveMemberName
               ,IF(MMH.USAGE_TYPE ='D',RECHARGE_AMOUNT,-USED_AMOUNT)  AS usedAmount
               ,MMH.MEMO                        AS memo
               ,CASE MMH.USAGE_TYPE
                    WHEN 'U' THEN '사용'
                    WHEN 'D' THEN '환불'
                END                             AS usageType
         FROM MU_MEMBERSHIP_HISTORY MMH
         LEFT JOIN MU_TREATMENT MT
         ON MMH.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
         LEFT JOIN MU_TREATMENT_PROCEDURE MTP
         ON MMH.MU_TREATMENT_PROCEDURE_ID = MTP.MU_TREATMENT_PROCEDURE_ID
         JOIN MU_USER MU
         ON MMH.MU_USER_ID=MU.MU_USER_ID
         JOIN MU_MEMBER MM
         ON MMH.MU_MEMBER_ID = MM.MU_MEMBER_ID
         LEFT JOIN MU_MEMBER MM2
         ON MMH.RESERVE_MEMBER_ID = MM2.MU_MEMBER_ID
         WHERE USAGE_TYPE!='T'
         AND USAGE_TYPE!='P'
         AND USAGE_TYPE!='A'
         AND USAGE_TYPE!='C'
            <if test="membershipSearchKeywordParam != null and membershipSearchKeywordParam != ''">
                AND (MU.USER_NAME LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%')
                OR MU.PHONE_NUMBER LIKE CONCAT('%',TRIM(#{membershipSearchKeywordParam}),'%'))
            </if>
            <if test="muTreatmentId != null and muTreatmentId != ''and treatmentName == '기타'">
                AND MT.TREATMENT_NAME != '비만'
                AND MT.TREATMENT_NAME != '피부'
                AND MT.TREATMENT_NAME != '쁘띠'
            </if>
            <if test="muTreatmentId != null and muTreatmentId != '' and treatmentName != '기타'">
                AND MMH.MU_TREATMENT_ID = #{muTreatmentId}
            </if>
            <if test="membershipSearchStartDate != null and membershipSearchStartDate != '' and membershipSearchEndDate != null and membershipSearchEndDate != ''">
                AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &gt;= #{membershipSearchStartDate}
                AND DATE_FORMAT(MMH.WRITE_DATE, '%Y-%m-%d') &lt;= #{membershipSearchEndDate}
            </if>
            <choose>
                <when test="membershipSort != null and membershipSort != ''">
                    ORDER BY ${membershipSort}
        </when>
        <otherwise>
        ORDER BY MMH.REG_DATE DESC
        </otherwise>
        </choose>
    </select>

    <update id="deleteMembershipProcedure" parameterType="hashmap">
        UPDATE MU_TREATMENT_PROCEDURE MTP
        JOIN MU_TREATMENT MT
        ON MTP.MU_TREATMENT_ID = MT.MU_TREATMENT_ID
        JOIN MU_TREATMENT_PROCEDURE_PRICE MTPP
        ON MTP.MU_TREATMENT_PROCEDURE_ID = MTPP.MU_TREATMENT_PROCEDURE_ID
        SET MTP.MOD_ID            = #{modId}
           ,MTPP.MOD_ID           = #{modId}
           ,MTP.MOD_DATE	      = NOW()
           ,MTPP.MOD_DATE	      = NOW()
           ,MTP.CUD_FLAG          = 'D'
           ,MTPP.CUD_FLAG         = 'D'
           ,MTP.USE_YN            = 'N'
           ,MTPP.USE_YN           = 'N'
        WHERE MTP.MU_TREATMENT_PROCEDURE_ID =#{muTreatmentProcedureId}
        AND MT.TREATMENT_NAME = '멤버십'
    </update>

</mapper>