<?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.TscShoplinkerDao">

	<!-- 샵링커 전송 이력 -->
	<insert id="insertShoplinerApiHst" parameterType="ShoplinkerGoods">
		/* TscShoplinkerDao.insertShoplinerApiHst */
		INSERT INTO SHOPLINKER_SYNC_HST (
		      LOG_SQ
			, API_TYPE
			, API_RESULT
			, API_MESSAGE
			, API_PRODUCT_ID
			, GOODS_CD
			, OPT_CD
			, QTY
			, ORD_DTL_NO
			, XML_TXT
			, REG_NO
			, REG_DT
		)
		VALUES (
		      null
		    , #{apiType}
			, #{apiResult}
			, #{apiMessage}
			, #{apiProductId}
			, #{goodsCd}
			, #{optCd}
			, #{quantity}
			, #{ordDtlNo}
			, #{xmlTxt}
			, #{regNo}
		    , NOW()
		)
	</insert>

	<!-- 샵링커 api 호출 가능여부   -->
	<select id="getCallRunableInfo" parameterType="ShoplinkerSearch" resultType="ShoplinkerSearch">
		/* TscShoplinkerDao.getCallRunableInfo */
		SELECT
			SID
			, RUN_STAT
			, RUN_STDT
			, RUN_EDDT
			, TXT
			, (SELECT COUNT(1) FROM SHOPLINKER_RUNABLE S WHERE S.API_TYPE = A.API_TYPE AND S.RUN_EDDT IS NULL
				<if test='apiType != null and apiType == "GOODS"'>AND S.REG_NO = #{regNo}</if>
			  ) AS RUN_CNT
			, (SELECT COUNT(1) FROM SHOPLINKER_ORDER S WHERE S.EXTMALL_REG_YN = 'N' AND S.SKU_MATCH_CODE != '') AS REMAIN_EXT_CNT
			, (SELECT COUNT(1) FROM TB_EXTMALL_ORDER_UPLOAD WHERE UPLOAD_STAT = 'G021_00' AND UPLOAD_GB = 'S') AS REMAIN_STYLE_CNT
		FROM SHOPLINKER_RUNABLE A
		WHERE A.API_TYPE = #{apiType}
		ORDER BY RUN_STDT DESC
		LIMIT 1
	</select>

	<!-- 샵링커 api 호출 가능여부-상품전송용   -->
	<select id="getCallRunableInfoGoods" parameterType="ShoplinkerSearch" resultType="ShoplinkerSearch">
		/* TscShoplinkerDao.getCallRunableInfoGoods */
		SELECT
			SID
			, RUN_STAT
			, RUN_STDT
			, RUN_EDDT
			, TXT
			, (SELECT COUNT(1) FROM SHOPLINKER_RUNABLE S WHERE S.API_TYPE = A.API_TYPE AND S.REG_NO = #{regNo} AND S.RUN_EDDT IS null ) AS RUN_CNT
			, (SELECT COUNT(1) FROM SHOPLINKER_RUNABLE S WHERE S.API_TYPE = A.API_TYPE AND S.REG_NO = #{regNo} AND S.SID = #{sid}) AS SID_OVERLAP_CNT
		FROM SHOPLINKER_RUNABLE A
		WHERE A.API_TYPE = 'GOODS'
		ORDER BY RUN_STDT DESC
		LIMIT 1

	</select>

	<!-- 샵링커 api 호출 가능여부 상태 저장  -->
	<insert id="saveCallApiRunable" parameterType="ShoplinkerSearch">
		/* TscShoplinkerDao.saveCallApiRunable */
		INSERT INTO SHOPLINKER_RUNABLE (
		    SID
		    , API_TYPE
			, RUN_STDT
			, RUN_EDDT
			, RUN_STAT
			, REG_NO
			, TXT
		)
		VALUES (
			#{sid}
		    , #{apiType}
			, NOW()
			, null
			, 'START'
			, #{regNo}
			, null
		) ON DUPLICATE KEY UPDATE
		  	RUN_EDDT = NOW()
			, RUN_STAT = #{runStat}
			, TXT = CONCAT(ifnull(TXT, ''), #{txt})
	</insert>

	<!-- 샵링커 api 호출 가능여부 상태 수정  -->
	<update id="updateCallApiRunable" parameterType="ShoplinkerSearch">
	/* TscShoplinkerDao.updateCallApiRunable */
		UPDATE SHOPLINKER_RUNABLE
		SET
			RUN_STAT = #{runStat}
			, TXT = CONCAT(ifnull(TXT, ''), #{txt})
			<if test='runStat != null and runStat == "END"'>
			, RUN_EDDT = NOW()
			</if>
		WHERE SID = #{sid}
	</update>



	<!-- 샵링커주문수집 - 주문수집등록 -->
	<insert id="insertShoplinkerOrder" parameterType="ShoplinkerOrder">
		/* TscShoplinkerDao.insertShoplinkerOrder */
		INSERT INTO SHOPLINKER_ORDER (
			ORDER_IF_IDX
		    , SHOPLINKER_ORDER_ID
			, MALL_ORDER_ID
			, MALL_NAME
			, BAESONG_STATUS
			, ORDER_NAME
			, ORDER_TEL
			, ORDER_CEL
			, ORDER_EMAIL
			, RECEIVE
			, RECEIVE_TEL
			, RECEIVE_CEL
			, RECEIVE_ZIPCODE
			, RECEIVE_ADDR
			, BAESONG_TYPE
			, BAESONG_BI
			, DELIVERY_MSG
			, ORDER_PRODUCT_ID
			, SHOPLINKER_PRODUCT_ID
			, PARTNER_PRODUCT_ID
			, PRODUCT_NAME
			, QUANTITY
			, ORDER_PRICE
			, SALE_PRICE
			, SUPPLY_PRICE
			, SKU
			, ORDERDATE
			, ORDER_REG_DATE
			, DELIVERY_INVOICE
			, ORDER_SEQ
			, TOTAL_COUNT
			, TOTAL_PAGE
			, TOTAL_STANDARD_COUNT
			, CURRENTLY_PAGE
			, CURRENTLY_COUNT
			, SELLER_ID
			, ONLY_SKU
			, ADD_SKU
			, MALL_ID
			, DIS_PRICE_MALL
			, DIS_PRICE_SELLER
			, DIS_PRICE_COUPON
			, DIS_PRICE_POINT
			, DISTRIBUTION_DELIVERY
			, SKU_MATCH_CODE
			, SKU_BARCODE
			, ORDER_CUSTOMS_NUMBER
			, ORDER_INPUT_TYPE
			, SUPPLY_ID
			, DELIVERY
			, ORDER_USER_ID
			, CRSPIK_USE
			, SHIP_NO
			, DEAL_NO
			, EXCHANGE_ORDER_YN
			, ORDER_MAIN_KEY
			, PAN_TYPE
			, CHANNEL_TYPE
			, SHIP_RSV_DATE
			, ORDER_FLAG
			, EXTMALL_REG_YN
			, REG_DT
		)
		SELECT
			#{orderIfIdx}
		    , #{shoplinkerOrderId}
			, #{mallOrderId}
			, #{mallName}
			, #{baesongStatus}
			, #{orderName}
			, #{orderTel}
			, #{orderCel}
			, #{orderEmail}
			, #{receive}
			, #{receiveTel}
			, #{receiveCel}
			, #{receiveZipcode}
			, #{receiveAddr}
			, #{baesongType}
			, #{baesongBi}
			, #{deliveryMsg}
			, #{orderProductId}
			, #{shoplinkerProductId}
			, #{partnerProductId}
			, #{productName}
			, #{quantity}
			, #{orderPrice}
			, #{salePrice}
			, #{supplyPrice}
			, #{sku}
			, #{orderdate}
			, #{orderRegDate}
			, #{deliveryInvoice}
			, #{orderSeq}
			, #{totalCount}
			, #{totalPage}
			, #{totalStandardCount}
			, #{currentlyPage}
			, #{currentlyCount}
			, #{sellerId}
			, #{onlySku}
			, #{addSku}
			, #{mallId}
			, #{disPriceMall}
			, #{disPriceSeller}
			, #{disPriceCoupon}
			, #{disPricePoint}
			, #{distributionDelivery}
			, #{skuMatchCode}
			, #{skuBarcode}
			, #{orderCustomsNumber}
			, #{orderInputType}
			, #{supplyId}
			, #{delivery}
			, #{orderUserId}
			, #{crspikUse}
			, #{shipNo}
			, #{dealNo}
			, #{exchangeOrderYn}
			, #{orderMainKey}
			, #{panType}
			, #{channelType}
			, #{shipRsvDate}
			, #{orderFlag}
			, 'N'
			, NOW()
		FROM DUAL
		WHERE NOT EXISTS(SELECT 1 FROM SHOPLINKER_ORDER WHERE SHOPLINKER_ORDER_ID = #{shoplinkerOrderId} )

	</insert>



	<!-- 샵링커주문수집 - 주문수집등록 여러개-->
	<insert id="insertShoplinkerOrderList" parameterType="java.util.HashMap" timeout="60">
		/* TscShoplinkerDao.insertShoplinkerOrderList */
		<if test="insertOrderList.size != 0">
			INSERT INTO SHOPLINKER_ORDER (
				ORDER_IF_IDX
			    , SHOPLINKER_ORDER_ID
				, MALL_ORDER_ID
				, MALL_NAME
				, BAESONG_STATUS
				, ORDER_NAME
				, ORDER_TEL
				, ORDER_CEL
				, ORDER_EMAIL
				, RECEIVE
				, RECEIVE_TEL
				, RECEIVE_CEL
				, RECEIVE_ZIPCODE
				, RECEIVE_ADDR
				, BAESONG_TYPE
				, BAESONG_BI
				, DELIVERY_MSG
				, ORDER_PRODUCT_ID
				, SHOPLINKER_PRODUCT_ID
				, PARTNER_PRODUCT_ID
				, PRODUCT_NAME
				, QUANTITY
				, ORDER_PRICE
				, SALE_PRICE
				, SUPPLY_PRICE
				, SKU
				, ORDERDATE
				, ORDER_REG_DATE
				, DELIVERY_INVOICE
				, ORDER_SEQ
				, TOTAL_COUNT
				, TOTAL_PAGE
				, TOTAL_STANDARD_COUNT
				, CURRENTLY_PAGE
				, CURRENTLY_COUNT
				, SELLER_ID
				, ONLY_SKU
				, ADD_SKU
				, MALL_ID
				, DIS_PRICE_MALL
				, DIS_PRICE_SELLER
				, DIS_PRICE_COUPON
				, DIS_PRICE_POINT
				, DISTRIBUTION_DELIVERY
				, SKU_MATCH_CODE
				, SKU_BARCODE
				, ORDER_CUSTOMS_NUMBER
				, ORDER_INPUT_TYPE
				, SUPPLY_ID
				, DELIVERY
				, ORDER_USER_ID
				, CRSPIK_USE
				, SHIP_NO
				, DEAL_NO
				, EXCHANGE_ORDER_YN
				, ORDER_MAIN_KEY
				, PAN_TYPE
				, CHANNEL_TYPE
				, SHIP_RSV_DATE
				, ORDER_FLAG
				, EXTMALL_REG_YN
				, REG_DT
			)
			<foreach collection="insertOrderList" item="item" separator=" union ">
			SELECT
				#{item.orderIfIdx}
			    , #{item.shoplinkerOrderId}
				, #{item.mallOrderId}
				, #{item.mallName}
				, #{item.baesongStatus}
				, #{item.orderName}
				, #{item.orderTel}
				, #{item.orderCel}
				, #{item.orderEmail}
				, #{item.receive}
				, #{item.receiveTel}
				, #{item.receiveCel}
				, #{item.receiveZipcode}
				, #{item.receiveAddr}
				, #{item.baesongType}
				, #{item.baesongBi}
				, #{item.deliveryMsg}
				, #{item.orderProductId}
				, #{item.shoplinkerProductId}
				, #{item.partnerProductId}
				, #{item.productName}
				, #{item.quantity}
				, #{item.orderPrice}
				, #{item.salePrice}
				, #{item.supplyPrice}
				, #{item.sku}
				, #{item.orderdate}
				, #{item.orderRegDate}
				, #{item.deliveryInvoice}
				, #{item.orderSeq}
				, #{item.totalCount}
				, #{item.totalPage}
				, #{item.totalStandardCount}
				, #{item.currentlyPage}
				, #{item.currentlyCount}
				, #{item.sellerId}
				, #{item.onlySku}
				, #{item.addSku}
				, #{item.mallId}
				, #{item.disPriceMall}
				, #{item.disPriceSeller}
				, #{item.disPriceCoupon}
				, #{item.disPricePoint}
				, #{item.distributionDelivery}
				, #{item.skuMatchCode}
				, #{item.skuBarcode}
				, #{item.orderCustomsNumber}
				, #{item.orderInputType}
				, #{item.supplyId}
				, #{item.delivery}
				, #{item.orderUserId}
				, #{item.crspikUse}
				, #{item.shipNo}
				, #{item.dealNo}
				, #{item.exchangeOrderYn}
				, #{item.orderMainKey}
				, #{item.panType}
				, #{item.channelType}
				, #{item.shipRsvDate}
				, #{item.orderFlag}
				, 'N'
				, NOW()
			FROM DUAL
			WHERE NOT EXISTS(SELECT 1 FROM SHOPLINKER_ORDER WHERE SHOPLINKER_ORDER_ID = #{item.shoplinkerOrderId} )
			</foreach>
		</if>
	</insert>

	<!-- 샵링커주문수집- 제휴몰 주문업로드여부 업데이트  -->
	<update id="updateShoplinkerOrder" parameterType="ShoplinkerOrder">
	/* TscShoplinkerDao.updateShoplinkerOrder */
		UPDATE SHOPLINKER_ORDER
		SET
			EXTMALL_REG_YN = 'Y'
		WHERE MALL_ID = #{mallId}
		AND SHOPLINKER_ORDER_ID = #{shoplinkerOrderId}
	</update>
	
	<!-- 샵링커주문수집- 제휴몰 등록실패사유 수정  -->
	<update id="updateOrderFailFlag" parameterType="ShoplinkerOrder">
	/* TscShoplinkerDao.updateOrderFailFlag */
		UPDATE TB_EXTMALL_ORDER_UPLOAD
		SET
			UPLOAD_FAIL_CD = 'G022_65'
		WHERE UPLOAD_STAT  = 'G021_40'
		AND	UPLOAD_FAIL_CD = 'G022_60'
		AND EXTMALL_ID = #{mallId}		
		AND AGENT_ORDER_ID = #{shoplinkerOrderId}
	
	</update>
	<!--
		제휴몰 주문등록 대상목록
		1. SKU_MATCH_CODE가 없는 것은 딜상품(딜상품은 엑셀 수동등록)
		2. 아래 4개 상점은 MALL_ORDER_ID를 SHIP_NO로 대처해서 저장
		   APISHOP_0003 옥션 / APISHOP_0010 지마켓 / APISHOP_0286 카카오톡스토어 / APISHOP_0287 위메프
		3. APISHOP_0021 는 주문생성 안함.(수집은 하고 주문생성은 안하도록 변경 21.10.07)
	-->
	<select id="getShoplinkerRegExtmallList" parameterType="ShoplinkerOrder" resultType="ShoplinkerOrder">
		/* TscShoplinkerDao.getShoplinkerRegExtmallList */
		SELECT
			 A.ORDER_IF_IDX
			, A.SHOPLINKER_ORDER_ID
			, CASE WHEN 'APISHOP_0003' = A.MALL_ID || 'APISHOP_0010' = A.MALL_ID || 'APISHOP_0286' = A.MALL_ID || 'APISHOP_0287' = A.MALL_ID
		           THEN IF(A.SHIP_NO = '' or SHIP_NO is NULL, A.MALL_ORDER_ID, A.SHIP_NO)
		           ELSE A.MALL_ORDER_ID
	          END MALL_ORDER_ID
			, A.MALL_NAME
			, A.BAESONG_STATUS
			, A.ORDER_NAME
			, A.ORDER_TEL
			, A.ORDER_CEL
			, A.ORDER_EMAIL
			, A.RECEIVE
			, A.RECEIVE_TEL
			, A.RECEIVE_CEL
			, A.RECEIVE_ZIPCODE
			, A.RECEIVE_ADDR
			, A.BAESONG_TYPE
			, A.BAESONG_BI
			, A.DELIVERY_MSG
			, A.ORDER_PRODUCT_ID
			, A.SHOPLINKER_PRODUCT_ID
			, A.PARTNER_PRODUCT_ID
			, A.PRODUCT_NAME
			, A.QUANTITY
			, A.ORDER_PRICE
			, A.SALE_PRICE
			, A.SUPPLY_PRICE
			, A.SKU
			, A.ORDERDATE
			, A.ORDER_REG_DATE
			, A.DELIVERY_INVOICE
			, A.ORDER_SEQ
			, A.TOTAL_COUNT
			, A.TOTAL_PAGE
			, A.TOTAL_STANDARD_COUNT
			, A.CURRENTLY_PAGE
			, A.CURRENTLY_COUNT
			, A.SELLER_ID
			, A.ONLY_SKU
			, A.ADD_SKU
			, A.MALL_ID
			, A.DIS_PRICE_MALL
			, A.DIS_PRICE_SELLER
			, A.DIS_PRICE_COUPON
			, A.DIS_PRICE_POINT
			, A.DISTRIBUTION_DELIVERY
			, A.SKU_MATCH_CODE
			, A.SKU_BARCODE
			, A.ORDER_CUSTOMS_NUMBER
			, A.ORDER_INPUT_TYPE
			, A.SUPPLY_ID
			, A.DELIVERY
			, A.ORDER_USER_ID
			, A.CRSPIK_USE
			, A.SHIP_NO
			, A.DEAL_NO
			, A.EXCHANGE_ORDER_YN
			, A.ORDER_MAIN_KEY
			, A.PAN_TYPE
			, A.CHANNEL_TYPE
			, A.SHIP_RSV_DATE
			, A.ORDER_FLAG
			, A.EXTMALL_REG_YN
			, A.REG_DT

		FROM SHOPLINKER_ORDER A
		WHERE A.EXTMALL_REG_YN = 'N'
		AND A.SKU_MATCH_CODE IS NOT NULL
		AND A.SKU_MATCH_CODE != ''
		AND A.MALL_ID != 'APISHOP_0021'
		ORDER BY A.MALL_ID, A.MALL_ORDER_ID, A.SHOPLINKER_ORDER_ID
	</select>

	<!-- 송장전송- 전송대상 목록 -->
	<select id="getShoplinkerInvoiceOrdDtlSendList" resultType="ShoplinkerInvoice">
		/* TscShoplinkerDao.getShoplinkerInvoiceOrdDtlSendList */
		SELECT
			B.ORD_NO
			, B.ORD_DTL_NO

		  	, C.SHIP_COMP_NM AS DELIVERY_NAME -- 택배사명
			, B.SHIP_COMP_CD AS DELIVERY_CODE-- 배송업체(택배사코드)
			, B.INVOICE_NO AS DELIVERY_INVOICE-- 송장번호

			, B.VENDOR_ID -- 외부몰벤더ID
			, B.EXTMALL_ID -- 외부몰ID(외부몰)
			, B.AGENT_ORDER_ID -- 에이전트주문번호
			, B.EXTMALL_ORDER_ID -- 외부몰주문번호
			, DELV_ASSIGN_STAT -- 출고지정상태(P:대기,Y:수락,N:거부)
			, ORD_EXCH_GB -- 주문교환구분(O:주문,E:교환)
			, ORD_DTL_STAT -- 주문상세상태(공통코드G013)
			, FN_GET_CODE_NM('G013', ORD_DTL_STAT) AS ORD_DTL_STAT_NM
		from
			TB_ORDER A
			inner join TB_ORDER_DETAIL B on A.ORD_NO = B.ORD_NO
		  	inner join TB_SHIP_COMPANY C on B.SHIP_COMP_CD = C.SHIP_COMP_CD

		WHERE A.MALL_GB = 'G011_20'
		and B.VENDOR_ID = 'G003_V001'
	 	and B.INVOICE_NO is not null
	 	and B.AGENT_ORDER_ID IS NOT NULL
	 	and B.ORD_DTL_STAT = 'G013_50' -- 배송중
		and B.DELV_STDT IS NOT NULL
		and b.EXTMALL_ID != 'TIMON' /* 티몬제외 */
		AND NOT EXISTS(SELECT 1 FROM SHOPLINKER_SYNC_HST S
			WHERE S.API_TYPE = 'INVOICE' AND S.ORD_DTL_NO = B.ORD_DTL_NO
			AND API_RESULT != 'error'
			)
		ORDER BY ORD_NO, ORD_DTL_NO
	</select>
	
	
	<!-- 알람SMS 생성 -->
	<insert id="createAlarmSmsDev" parameterType="Alarm">
		/* TscShoplinker.createAlarmSmsDev */
		INSERT INTO SSG_SEND_TRAN_SMS (
		       FSEQ
		     , FUSERID
		     , FSECTIONCODE
		     , FCAMPCODE
		     , FMSGTYPE
		     , FMESSAGE
		     , FSENDDATE
		     , FDESTINE
		     , FCALLBACK
		)
		SELECT NULL          AS FSEQ
		     , #{fuserid}    AS FUSERID
		     , ''            AS FSECTIONCODE
		     , ''            AS FCAMPCODE
		     , '0'           AS FMSGTYPE
		     , #{alarmMsg}   AS FMESSAGE
		     , NOW()         AS FSENDDATE
		     , AR.CELL_PHNNO AS FDESTINE
		     , #{fcallback}  AS FCALLBACK
		FROM   TB_ALARM_RECEIVER AR
		WHERE  AR.ALARM_ID = #{alarmId}
		AND    AR.USE_YN = 'Y'
	</insert>
	
	<!-- 알람SMS 생성 -->
	<insert id="createAlarmSms" parameterType="Alarm">
		/* TscShoplinker.createAlarmSms */
		INSERT INTO style24_msg.SSG_SEND_TRAN_SMS (
		       FSEQ
		     , FUSERID
		     , FSECTIONCODE
		     , FCAMPCODE
		     , FMSGTYPE
		     , FMESSAGE
		     , FSENDDATE
		     , FDESTINE
		     , FCALLBACK
		)
		SELECT NULL          AS FSEQ
		     , #{fuserid}    AS FUSERID
		     , ''            AS FSECTIONCODE
		     , ''            AS FCAMPCODE
		     , '0'           AS FMSGTYPE
		     , #{alarmMsg}   AS FMESSAGE
		     , NOW()         AS FSENDDATE
		     , AR.CELL_PHNNO AS FDESTINE
		     , #{fcallback}  AS FCALLBACK
		FROM   TB_ALARM_RECEIVER AR
		WHERE  AR.ALARM_ID = #{alarmId}
		AND    AR.USE_YN = 'Y'
	</insert>
	
</mapper>


