<?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.admin.biz.dao.TsaWithdrawDao">

	<!-- 목록 페이징 정보 -->
	<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="getRefundListCount" parameterType="WithdrawExc" resultType="int">
		/* TsaWithdraw.getRefundListCount */
		SELECT COUNT(*) AS TOTCNT
		  FROM (
			SELECT
				  O.ORD_NO        -- 주문번호
				, C.ORD_DTL_NO    -- 주문상세번호 
				, D.ORD_CHG_SQ    -- 주문변경일련번호 
			  FROM TB_WITHDRAW A
			  JOIN TB_WITHDRAW_DETAIL B ON A.WD_INVOICE_NO  = B.WD_INVOICE_NO AND A.ORD_CHG_SQ = B.ORD_CHG_SQ 
			  JOIN TB_ORDER_CHANGE_DETAIL C ON B.ORD_CHG_SQ = C.ORD_CHG_SQ AND B.ORD_DTL_NO = C.ORD_DTL_NO AND C.DEL_YN ='N'
			  JOIN TB_ORDER_CHANGE        D ON C.ORD_CHG_SQ = D.ORD_CHG_SQ 
			  JOIN TB_ORDER_DETAIL        O ON B.ORD_DTL_NO = O.ORD_DTL_NO 
			  JOIN TB_ORDER               I ON O.ORD_NO = I.ORD_NO
			 WHERE D.CHG_GB  = 'G680_30' -- 반품요청
			 <include refid="getRefundListCondition_sql"/>
			 	
			) A	
		
	</select>

	<!-- 환불관리 목록  -->
	<select id="getRefundList" parameterType="WmsWithdraw" resultType="WmsWithdraw">
		/* TsaWithdraw.getRefundList */
		
		SELECT Z.*
		    , FN_GET_CODE_NM('G688', Z.CHG_REASON) AS CHG_REASON -- 요청사유   
		FROM (
		    SELECT A.*, ROW_NUMBER() OVER(ORDER BY  A.ORD_NO DESC, A.ORD_DTL_NO) RNUM 
		    FROM (
				SELECT
					  O.ORD_NO        -- 주문번호
					, C.ORD_DTL_NO    -- 주문상세번호 
					, A.WD_INVOICE_NO -- 회수송장번호	
					, CASE WHEN C.COMPLETE_DT IS NOT NULL THEN '환불완료' ELSE '환불대기' END AS RFND_STAT -- 환불상태 
					, CASE WHEN D.WD_GB = 'W' THEN '회수요청' ELSE '직접배송' END AS WD_GB   -- 회수구분(W:회수요청, D:직접배송)
					, D.ORD_CHG_SQ    -- 주문변경일련번호 
					, I.ORD_NM        -- 주문자명
					, I.ORD_PHNNO     -- 주문자연락처	
					, A.SENDER_NM     -- 보내는사람
					, A.SENDER_PHNNO  -- 보낸연락처
					, A.ARRIVAL_DT    -- 도착일시
					, D.WD_EDDT       -- 환불확정일자
					, A.WD_MEMO       -- wms회수메모
					, B.GOODS_CD      -- 상품코드
					, B.OPT_CD1       -- 옵션1
					, B.OPT_CD2       -- 옵션2
					, C.CHG_QTY       -- 반품수량
					, B.WD_QTY        -- 회수수량
					, d.CHG_MEMO      -- 클레임메모
					, D.CHG_REASON    -- 요청사유 
					, C.COMPLETE_DT   -- 반품완료일자 
				  FROM TB_WITHDRAW A
				  JOIN TB_WITHDRAW_DETAIL B ON A.WD_INVOICE_NO  = B.WD_INVOICE_NO AND A.ORD_CHG_SQ = B.ORD_CHG_SQ 
				  JOIN TB_ORDER_CHANGE_DETAIL C ON B.ORD_CHG_SQ = C.ORD_CHG_SQ AND B.ORD_DTL_NO = C.ORD_DTL_NO AND C.DEL_YN ='N'
				  JOIN TB_ORDER_CHANGE        D ON C.ORD_CHG_SQ = D.ORD_CHG_SQ 
				  JOIN TB_ORDER_DETAIL        O ON B.ORD_DTL_NO = O.ORD_DTL_NO 
				  JOIN TB_ORDER               I ON O.ORD_NO = I.ORD_NO
				 WHERE D.CHG_GB  = 'G680_30' -- 반품요청		
				 <include refid="getRefundListCondition_sql"/>
		<include refid="getListPagingCondition_sql"/>
	</select>
	

    <!-- 환불관리 목록 조회 조건  -->
	<sql id="getRefundListCondition_sql">
		<if test="stDate != null and stDate != '' and edDate != null and edDate != ''">
			<if test="searchType == 'withdrawDt'"> -- 회수등록일자
			AND    B.REG_DT BETWEEN STR_TO_DATE(REPLACE(#{stDate},'-',''), '%Y%m%d%H%i%s') AND STR_TO_DATE(REPLACE(#{edDate},'-','') +1, '%Y%m%d%H%i%s')
			</if>
			<if test="searchType == 'returnDt'">   -- 반품접수일자
			AND    D.REG_DT BETWEEN STR_TO_DATE(REPLACE(#{stDate},'-',''), '%Y%m%d%H%i%s') AND STR_TO_DATE(REPLACE(#{edDate},'-','') +1, '%Y%m%d%H%i%s')
			</if>
			<if test="searchType == 'confirmDt'">  -- 반품완료일자
			AND    D.WD_EDDT BETWEEN STR_TO_DATE(REPLACE(#{stDate},'-',''), '%Y%m%d%H%i%s') AND STR_TO_DATE(REPLACE(#{edDate},'-','') +1, '%Y%m%d%H%i%s')
			</if>
		</if>
		<if test="ordNo != null and ordNo != ''">
			AND O.ORD_NO = #{ordNo}
		</if>
		<if test="wdInvoiceNo != null and wdInvoiceNo != ''">
			AND A.WD_INVOICE_NO = #{wdInvoiceNo}
		</if>
		<if test="withdrawType != null and withdrawType != ''">
			<choose>
				<when test='withdrawType == "N"'> -- 환불대기
				AND C.COMPLETE_DT IS NULL
				</when>
				<when test='withdrawType == "Y"'> -- 환불완료
				AND C.COMPLETE_DT IS NOT NULL
				</when>
			</choose>
		</if>
		<if test="goodsCd != null and goodsCd != ''">
			AND B.GOODS_CD = #{goodsCd}
		</if>
		<if test="ordNm != null and ordNm != ''">
			AND I.ORD_NM = #{ordNm}
		</if>
		<if test="senderNm != null and senderNm != ''">
			AND A.SENDER_NM = #{senderNm}
		</if>
	</sql>
	
	<!-- 회수예외목록 건수 -->
	<select id="getWithdrawExceptionListCount" parameterType="WithdrawExc" resultType="int">
		/* TsaWithdraw.getWithdrawExceptionListCount */
		SELECT COUNT(*) AS TOTCNT
		  FROM (		
				SELECT 
					  A.RECALL_STAT   -- 반품대기처리상태
					, A.STATUS_CD     -- 처리상태
					, A.RECALL_EXCEPTION_NO -- 반품예외처리번호 
				  FROM TB_ORDER_RECALL_EXCEPTION A 
				  JOIN TB_ORDER_RECALL_EXCEPTION_ITEM B ON A.RECALL_EXCEPTION_NO = B.RECALL_EXCEPTION_NO
				  WHERE B.REASON_CD NOT IN('확정 전 품절(재고없음)','확정 전 불량')
					<if test='customerName != null and customerName != ""'>
					AND   A.CUSTOMER_NAME = #{customerName}
					</if>
					<if test='orderNo != null and orderNo != ""'>
					AND   A.ORDER_NO  = #{orderNo}
					</if>
					<if test='recallStat != null and recallStat != ""'>
					AND   A.RECALL_STAT  = #{recallStat}
					</if>
					<if test='stDate != null and stDate != ""'>
					AND   A.DATE_CREATED <![CDATA[>= ]]> STR_TO_DATE(REPLACE(#{stDate},'-',''), '%Y%m%d%H%i%s') 
					</if>
					<if test='edDate != null and edDate != ""'>
					AND   A.DATE_CREATED <![CDATA[<]]> STR_TO_DATE(REPLACE(#{edDate},'-','') + 1 , '%Y%m%d%H%i%s') 
					</if>
			) A

	</select>
		
	<!-- 회수예외목록 -->
	<select id="getWithdrawExceptionList" parameterType="WithdrawExc" resultType="WithdrawExc">
		/* TsaWithdraw.getWithdrawExceptionList */
		SELECT Z.*
			, ROW_NUMBER() OVER W AS ROWSPAN_CNT
	        , ROW_NUMBER() OVER T AS ROWSPAN_RANK
		FROM (
		    SELECT A.*, ROW_NUMBER() OVER(ORDER BY  A.ORDER_NO, A.RECALL_EXCEPTION_NO, A.RECALL_EXCEPTION_ITEM_NO)  RNUM 
		    FROM (
				SELECT A.* 
				  FROM (
						SELECT 
							  A.RECALL_STAT   -- 반품대기처리상태
							, A.STATUS_CD     -- 처리상태
							, A.DATE_CREATED  -- 등록일자
							, A.CUSTOMER_NAME -- 고객명
							, A.ORDER_NO      -- 주문번호
							, B.ORDER_DTL_NO  -- 주문상세번호 
							, A.LOGISTICS_NAME -- 택배사명
							, A.INVOICE_NO     -- 반송장번호
							, A.CHARGE_TYPE    -- 요금구분
							, A.CHARGE_AMOUNT  -- 배송비
							, A.USER_NAME_CREATED -- 작업자
							, B.REASON_CD -- 예외사유
							, IFNULL((SELECT GROUP_CONCAT(ADMIN_MEMO ORDER BY RECALL_EXCEPTION_MEMO_NO ) 
							     FROM TB_ORDER_RECALL_EXCEPTION_MEMO C WHERE C.RECALL_EXCEPTION_NO = A.RECALL_EXCEPTION_NO  AND ADMIN_MEMO !='.'),'-') AS ADMIN_MEMO -- WMS메시지
							, IFNULL((SELECT BRAND_KNM FROM TB_BRAND BR JOIN TB_GOODS GD ON BR.BRAND_CD = GD.BRAND_CD WHERE GD.GOODS_CD = C.GOODS_CD),'') AS BRAND_NM           -- 브랜드명
							, B.PRODUCT_CODE   -- 상품코드
							, B.SKU_CODE       -- SKU코드
							, B.PRODUCT_NAME   -- 상품명
							, B.SKU_VALUE      -- 속성
							, C.SKU_MODEL_NO   -- 원코드
							, B.EXCEPTION_QTY  -- 수량
							, O.SITE_CD        -- 주문경로
							, A.RECALL_EXCEPTION_NO -- 반품예외처리번호 
							, IFNULL(C.GOODS_CD,'') AS GOODS_CD       -- 상품코드 
							, B.RECALL_EXCEPTION_ITEM_NO 
						  FROM TB_ORDER_RECALL_EXCEPTION A 
						  JOIN TB_ORDER_RECALL_EXCEPTION_ITEM B ON A.RECALL_EXCEPTION_NO = B.RECALL_EXCEPTION_NO
						  LEFT JOIN TB_ORDER O ON O.ORD_NO = A.ORDER_NO 
						  LEFT JOIN TB_OPTION C ON C.OPT_CD = B.SKU_CODE
						  WHERE B.REASON_CD NOT IN('확정 전 품절(재고없음)','확정 전 불량')
							<if test='customerName != null and customerName != ""'>
							AND   A.CUSTOMER_NAME = #{customerName}
							</if>
							<if test='orderNo != null and orderNo != ""'>
							AND   A.ORDER_NO  = #{orderNo}
							</if>
							<if test='recallStat != null and recallStat != ""'>
							AND   A.RECALL_STAT  = #{recallStat}
							</if>
							<if test='stDate != null and stDate != ""'>
							AND   A.DATE_CREATED <![CDATA[>= ]]> STR_TO_DATE(REPLACE(#{stDate},'-',''), '%Y%m%d%H%i%s') 
							</if>
							<if test='edDate != null and edDate != ""'>
							AND   A.DATE_CREATED <![CDATA[<]]> STR_TO_DATE(REPLACE(#{edDate},'-','')+ 1, '%Y%m%d%H%i%s')
							</if>
				) A
				ORDER BY A.ORDER_NO, A.RECALL_EXCEPTION_NO, A.RECALL_EXCEPTION_ITEM_NO
	<include refid="getListPagingCondition_sql"/>
	      WINDOW W AS (PARTITION BY ORDER_NO ORDER BY ORDER_NO), T AS (PARTITION BY ORDER_NO ORDER BY ORDER_NO , RECALL_EXCEPTION_ITEM_NO DESC )
	</select>


	<!-- 회수예외 처리완료-->
	<update id="updateWithdrawException" parameterType="WithdrawExc" >
		/* TsaWithdraw.updateWithdrawException */
		UPDATE TB_ORDER_RECALL_EXCEPTION SET
		  RECALL_STAT = #{recallStat}
		, RECALL_STAT_DT = NOW()
		WHERE RECALL_EXCEPTION_NO = #{recallExceptionNo}

	</update>

	<!-- 상품옵션 정보 -->
	<select id="getOptionInfo" parameterType="WmsWithdraw" resultType="WmsWithdraw">
		/* TsaWithdraw.getOptionInfo */
			SELECT GOODS_CD
			 FROM  TB_OPTION 
			WHERE OPT_CD = #{skucode} 
	</select>
	
	<!-- 회수지시 목록 건수 -->
	<select id="getWithdrawDirectiveListCount" parameterType="Withdraw" resultType="int">
		/* TsaWithdraw.getWithdrawDirectiveListCount */
				SELECT COUNT(*) AS TOTCNT
				  FROM (		
						SELECT 
						       O.ORD_NO                                 -- 주문번호
						     , OCD.ORD_DTL_NO                           -- 주문상세번호
						     , OD.GOODS_CD                   -- 상품코드
						FROM   TB_ORDER_CHANGE OC          
						JOIN   TB_ORDER_CHANGE_DETAIL OCD ON OC.ORD_CHG_SQ  = OCD.ORD_CHG_SQ 
						JOIN   TB_ORDER_DETAIL OD         ON OCD.ORD_DTL_NO = OD.ORD_DTL_NO
						JOIN   TB_ORDER O                 ON OD.ORD_NO      = O.ORD_NO
						JOIN   TB_GOODS G                 ON OD.GOODS_CD     = G.GOODS_CD
						JOIN   TB_DELIVERY_LOC D          ON OD.DELV_LOC_CD = D.DELV_LOC_CD AND OD.SUPPLY_COMP_CD = D.SUPPLY_COMP_CD
						WHERE  1=1 
						<include refid="getWithdrawDirectiveCondition_sql"/>
					) A

	</select>
	
	<!-- 회수지시 목록 -->
	<select id="getWithdrawDirectiveList" parameterType="Withdraw" resultType="Withdraw">
		/* TsaWithdraw.getWithdrawDirectiveList */
		SELECT Z.*
		     , FN_GET_CODE_NM('G680', Z.CHG_GB) AS CHG_GB_NM
		     , CASE WHEN CHG_GB = 'G680_30' THEN FN_GET_CODE_NM('G688', Z.CHG_REASON) ELSE FN_GET_CODE_NM('G689', Z.CHG_REASON) END AS CHG_REASON_NM
		     , FN_GET_CODE_NM('G320', Z.WD_SHIP_STATE) AS WD_SHIP_STATE_NM
		     , CASE WHEN WD_SHIP_STATE = '12' THEN   FN_GET_CODE_NM('G321', Z.WD_REASON_CD)
		            WHEN WD_SHIP_STATE = '84' THEN   FN_GET_CODE_NM('G322', Z.WD_REASON_CD) ELSE '' END AS WD_REASON_CD_NM
		     , FN_GET_CODE_NM('G685', Z.CHG_STAT) AS CHG_STAT_NM
		FROM (
		    SELECT A.*, ROW_NUMBER() OVER(ORDER BY  A.ORD_CHG_SQ, A.ORD_NO DESC, A.ORD_DTL_NO )  RNUM 
		    FROM ( 
				SELECT A.* 
				  FROM (
						SELECT DISTINCT
						       OC.ORD_CHG_SQ                            -- 주문변경번호 
						     , OC.CHG_GB                                -- 변경구분 G680
						     , OC.CHG_REASON                            -- 변경사유 반품G688 교환G689
						     , OC.WD_GB                                 -- 직접배송여부
						     , DATE_FORMAT(OC.REG_DT, '%Y-%m-%d') AS REG_DT  -- 회수요청일
						     , OC.WD_INVOICE_NO                         -- 회수송장번호
						     , OC.WD_SHIP_STATE                         -- 배송업체회수상태 G320
						     , OC.WD_STATE_DT                           -- 회수상태 수신일시 
						     , OC.WD_REASON_CD                          -- 미회수사유 G321 G322
						     , OC.WD_BF_SEND_YN                         -- 교환 선발송 여부 
						     , OC.WD_INVOICE_SEND_YN AS SEND_YN         -- 전송여부
						     , O.ORD_NO                                 -- 주문번호
						     , OCD.ORD_DTL_NO                           -- 주문상세번호
						     , OCD.CHG_STAT                             -- 변경상태 G685
						     , OD.GOODS_CD                              -- 상품코드
						     , G.GOODS_NM                               -- 상품명
						     , OCD.CHG_QTY                              -- 변경수량
						     , DATE_FORMAT(OC.WD_STDT, '%Y-%m-%d %H:%i:%S') AS WD_STDT  -- 배송시작일시
						     , DATE_FORMAT(OC.WD_EDDT, '%Y-%m-%d %H:%i:%S') AS WD_EDDT  -- 배송종료일시
						     , D.RTN_LOC_NM          AS RECIP_NM        -- 수취인명
						     , OC.CHGER_NM                              -- 변경자명
						     , OC.CHGER_PHNNO                           -- 변경자휴대전화번호
						     , OC.CHGER_TELNO                           -- 변경자전화번호
						     , OC.CHGER_ZIPCODE                         -- 변경자우편번호
						     , OC.CHGER_BASE_ADDR                       -- 변경자기본주소
						     , OC.CHGER_DTL_ADDR                        -- 변경자상세주소
						     , O.ORD_NM                                 -- 주문자명
						     , O.ORD_PHNNO                              -- 주문자휴대전화번호
						     , O.ORD_TELNO                              -- 주문자전화번호
						     , O.ORD_EMAIL                              -- 주문자이메일
						FROM   TB_ORDER_CHANGE OC          
						JOIN   TB_ORDER_CHANGE_DETAIL OCD ON OC.ORD_CHG_SQ  = OCD.ORD_CHG_SQ 
						JOIN   TB_ORDER_DETAIL OD         ON OCD.ORD_DTL_NO = OD.ORD_DTL_NO
						JOIN   TB_ORDER O                 ON OD.ORD_NO      = O.ORD_NO
						JOIN   TB_GOODS G                 ON OD.GOODS_CD     = G.GOODS_CD
						JOIN   TB_DELIVERY_LOC D          ON OD.DELV_LOC_CD = D.DELV_LOC_CD AND OD.SUPPLY_COMP_CD = D.SUPPLY_COMP_CD
						WHERE  1=1 
						<include refid="getWithdrawDirectiveCondition_sql"/>
					) A
				ORDER BY A.ORD_CHG_SQ, A.ORD_NO DESC, A.ORD_DTL_NO
				<include refid="getListPagingCondition_sql"/>
	</select>

    <!-- 환불관리 목록 조회 조건  -->
	<sql id="getWithdrawDirectiveCondition_sql">
		<if test="ordNm != null and ordNm != ''">
			AND O.ORD_NM = #{ordNm}
		</if>
		<if test="ordNo != null and ordNo != ''">
			AND O.ORD_NO = #{ordNo}
		</if>
		<if test="ordChgSq != null and ordChgSq != ''">
			AND OC.ORD_CHG_SQ = #{ordChgSq}
		</if>		
		<if test="chgGb == null or chgGb == ''">
			AND    OC.CHG_GB IN ('G680_30','G680_40') -- 반품요청,교환요청
		</if>
		<if test="chgGb != null and chgGb != ''">
			AND OC.CHG_GB = #{chgGb}
		</if>
		
		<if test="chgStat != null and chgStat != ''">
			AND OCD.CHG_STAT = #{chgStat}
		</if>
		<if test="chgStat == null or chgStat == ''">
			AND OCD.CHG_STAT IN('G685_20','G685_50','G685_30','G685_40','G685_60','G685_49','G685_69')
		</if>
		
		<if test="wdGb != null and wdGb != ''">
			AND OC.WD_GB = #{wdGb}
		</if>	
		<if test="sendYn != null and sendYn != ''">
		AND    OC.WD_INVOICE_SEND_YN = #{sendYn}
		</if>
		<if test="wdShipState != null and wdShipState != ''">
		AND    OC.WD_SHIP_STATE = #{wdShipState}
		</if>
		
		<if test="stDate != null and stDate != ''">
		AND    OC.REG_DT <![CDATA[>=]]> STR_TO_DATE(REPLACE(#{stDate},'-','') , '%Y%m%d%H%i%s')
		</if>
		<if test="edDate != null and edDate != ''">
		AND    OC.REG_DT <![CDATA[<]]> STR_TO_DATE(REPLACE(#{edDate},'-','')+1 , '%Y%m%d%H%i%s')
		</if>
		AND    G.SELF_GOODS_YN = 'Y' -- 자사상품만
		AND    OCD.DEL_YN      = 'N'	
	</sql>		
			
	<!-- 재회수지시-->
	<update id="updateReRecallOrder" parameterType="Withdraw" >
		/* TsaWithdraw.updateReRecallOrder */
		UPDATE TB_ORDER_CHANGE_DETAIL SET
		  CHG_STAT = #{chgStat}
		, UPD_NO   = #{updNo}
		, UPD_DT   = NOW()
		WHERE ORD_CHG_SQ = #{ordChgSq} 
		  AND ORD_DTL_NO = #{ordDtlNo}

	</update>

</mapper>