<?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.oqpo.api.mapper.loanmng.UnpaidMngMapper">

    <select id="selectUnpaidMngGridList" resultType="com.oqpo.api.entity.settmng.StlMgntBaseInfoEntity">
        /* UnpaidMngMapper.selectUnpaidMngGridList */
        SELECT store.store_id, store.store_nm, store.brand_id, FN_BRAND_NM(store.brand_id) AS brand_nm,
            store.sttl_req_cfrm_term,       /* 정산요청확인기간 */
            store.sttl_rcp_amt_term,        /* 정산대금입금기간 */
            loan.loan_mgnt_unq_no,          /* 여신관리고유번호 */
            loan.loan_dvsn, FN_CODE_NM('LOAN_DVSN', loan.loan_dvsn) AS loan_dvsn_nm,       /* 여신구분(정산타입) */
            loan.credt_limit_amt - loan.use_amt_total + loan.acct_bal + loan.tmp_rcv_acct_total AS use_amt_total,    /* 사용가능한도 */
            loan.acct_bal,              /* 계좌잔액 */
            loan.credt_limit_amt,       /* 신용한도금액(후불) */
            loan.tmp_rcv_acct_total,    /* 가수금액합계(선결제) */
            DATE_FORMAT(stl.sttl_req_dt, '%Y.%m.%d') AS sttl_req_dt,        /* 정산요청일자 */
            DATE_FORMAT(stl.sttl_dt, '%Y.%m.%d') AS sttl_dt,                /* 정산확정일자 */
            stl.sttl_req_amt,           /* 정산요청금액 */
            stl.sttl_amt,               /* 정산확정금액 */
            stl.rcpt_amt,               /* 수납금액 */
            (IFNULL(stl.sttl_amt, stl.sttl_req_amt) - IFNULL(stl.rcpt_amt, 0)) AS unpaid_amt,       /* 미납금액 */
            stl.sttl_st_cd, FN_CODE_NM('STTL_ST_CD', stl.sttl_st_cd) AS sttl_st_nm,                 /* 정산상태코드 */
            <![CDATA[
            CASE WHEN store.sttl_req_cfrm_term > 0 AND store.sttl_rcp_amt_term > 0 THEN
                    CASE WHEN stl.sttl_req_dt IS NULL THEN '정산요청전'
                    ELSE CASE WHEN stl.sttl_dt IS NULL
                    THEN CASE WHEN ADDDATE(DATE_FORMAT(stl.sttl_req_dt, '%Y%m%d'), store.sttl_req_cfrm_term) < DATE_FORMAT(now(), '%Y-%m-%d')
                    THEN CASE WHEN ADDDATE(DATE_FORMAT(stl.sttl_req_dt, '%Y%m%d'), store.sttl_req_cfrm_term + store.sttl_rcp_amt_term) < DATE_FORMAT(NOW(), '%Y-%m-%d')
                    THEN '정산미납'
                    ELSE '정산대기' END
                ELSE '정산미확인' END
                ELSE CASE WHEN ADDDATE(DATE_FORMAT(stl.sttl_dt, '%Y%m%d'), store.sttl_rcp_amt_term) < DATE_FORMAT(NOW(), '%Y-%m-%d')
                THEN '정산미납'
                ELSE '정산대기' END
                END
                END
                ELSE '정산대기'
            END AS sttl_add_st_nm,          /* 정산부가상태명 */
            ]]>
            stl.sttl_mgnt_unq_no            /* 정산관리고유번호 */
        FROM store_base_info store
        INNER JOIN loan_mgnt_base_info loan
            ON store.loan_mgnt_unq_no = loan.loan_mgnt_unq_no
            AND store.loan_dvsn = loan.loan_dvsn
            AND store.store_id = loan.store_id
            AND loan.loan_dvsn = 'LD02'
            AND loan.use_amt_total > 0
        INNER JOIN stl_mgnt_base_info stl
            ON store.store_id = stl.store_id
            AND store.brand_id = stl.brand_id
            AND stl.sttl_req_dt BETWEEN #{fromDt} AND #{toDt}
            AND stl.sttl_st_cd IN ('ST10', 'ST20')      /* 정산요청/정산확정 */
            AND IFNULL(stl.rcpt_yn, 'N') = 'N'          /* 수납여부(후불사용) */
            AND IFNULL(stl.STTL_AMT, stl.STTL_REQ_AMT) - IFNULL(stl.RCPT_AMT, 0) > 0
        WHERE 1 = 1
            AND store.brand_id = #{sBrandId}
            AND IFNULL(stl.STTL_AMT, stl.STTL_REQ_AMT) - IFNULL(stl.RCPT_AMT, 0) - loan.ACCT_BAL > 0
        <if test="sStoreId != null and sStoreId != ''">
            AND store.store_id = #{sStoreId}
        </if>
        <choose>
            <when test="gridRequest.sidx != null and gridRequest.sidx != ''">
                <if test="gridRequest.sidx == 'VIEW_NUM'.toString()">
                    <if test="gridRequest.sord == 'asc'.toString()">
                        ORDER BY stl.sttl_mgnt_unq_no ASC
                    </if>
                    <if test="gridRequest.sord == 'desc'.toString()">
                        ORDER BY stl.sttl_mgnt_unq_no DESC
                    </if>
                </if>
            </when>
            <otherwise>
                ORDER BY stl.sttl_mgnt_unq_no ASC
            </otherwise>
        </choose>
        <if test="gridRequest.pagingYn == true">
            limit #{gridRequest.gridFirst}, #{gridRequest.gridSize}
        </if>
    </select>

    <select id="selectUnpaidMngGridCnt" resultType="int">
        /* UnpaidMngMapper.selectUnpaidMngGridCnt */
        SELECT COUNT(*)
        FROM store_base_info store
        INNER JOIN loan_mgnt_base_info loan
        ON store.loan_mgnt_unq_no = loan.loan_mgnt_unq_no
        AND store.loan_dvsn = loan.loan_dvsn
        AND store.store_id = loan.store_id
        AND loan.loan_dvsn = 'LD02'
        AND loan.use_amt_total > 0
        INNER JOIN stl_mgnt_base_info stl
        ON store.store_id = stl.store_id
        AND store.brand_id = stl.brand_id
        AND stl.sttl_req_dt BETWEEN #{fromDt} AND #{toDt}
        AND stl.sttl_st_cd IN ('ST10', 'ST20')      /* 정산요청/정산확정 */
        AND IFNULL(stl.rcpt_yn, 'N') = 'N'
        AND IFNULL(stl.STTL_AMT, stl.STTL_REQ_AMT) - IFNULL(stl.RCPT_AMT, 0) > 0
        WHERE 1 = 1
            AND store.brand_id = #{sBrandId}
        <if test="sStoreId != null and sStoreId != ''">
            AND store.store_id = #{sStoreId}
        </if>
            AND IFNULL(stl.STTL_AMT, stl.STTL_REQ_AMT) - IFNULL(stl.RCPT_AMT, 0) - loan.ACCT_BAL > 0
    </select>

    <select id="selectStlMgntBaseInfo" resultType="com.oqpo.api.entity.settmng.StlMgntBaseInfoEntity">
        /* UnpaidMngMapper.selectStlMgntBaseInfo */
        SELECT store.store_id, store.store_nm, store.brand_id, FN_BRAND_NM(store.brand_id) AS brand_nm,
            store.sttl_req_cfrm_term,       /* 정산요청확인기간 */
            store.sttl_rcp_amt_term,        /* 정산대금입금기간 */
            loan.loan_mgnt_unq_no,          /* 여신관리고유번호 */
            loan.loan_dvsn, FN_CODE_NM('LOAN_DVSN', loan.loan_dvsn) AS loan_dvsn_nm,       /* 여신구분(정산타입) */
            loan.credt_limit_amt - loan.use_amt_total + loan.acct_bal + loan.tmp_rcv_acct_total AS use_amt_total,    /* 사용가능한도 */
            loan.acct_bal,              /* 매장 계좌잔액 */
            loan.credt_limit_amt,       /* 신용한도금액(후불) */
            loan.tmp_rcv_acct_total,    /* 가수금액합계(선결제) */
            DATE_FORMAT(stl.sttl_req_dt, '%Y.%m.%d') AS sttl_req_dt,        /* 정산요청일자 */
            DATE_FORMAT(stl.sttl_dt, '%Y.%m.%d') AS sttl_dt,                /* 정산확정일자 */
            stl.sttl_req_amt,           /* 정산요청금액 */
            stl.sttl_amt,               /* 정산확정금액 */
            stl.rcpt_amt,               /* 수납금액 */
            (IFNULL(stl.sttl_amt, stl.sttl_req_amt) - IFNULL(stl.rcpt_amt, 0)) AS unpaid_amt,       /* 미납금액 : 정산금액 - 수납금액  */
            stl.sttl_st_cd, FN_CODE_NM('STTL_ST_CD', stl.sttl_st_cd) AS sttl_st_nm,                 /* 정산상태코드 */
            <![CDATA[
            CASE WHEN store.sttl_req_cfrm_term > 0 AND store.sttl_rcp_amt_term > 0 THEN
                    CASE WHEN stl.sttl_req_dt IS NULL THEN '정산요청전'
                    ELSE CASE WHEN stl.sttl_dt IS NULL
                    THEN CASE WHEN ADDDATE(DATE_FORMAT(stl.sttl_req_dt, '%Y%m%d'), store.sttl_req_cfrm_term) < DATE_FORMAT(now(), '%Y-%m-%d')
                    THEN CASE WHEN ADDDATE(DATE_FORMAT(stl.sttl_req_dt, '%Y%m%d'), store.sttl_req_cfrm_term + store.sttl_rcp_amt_term) < DATE_FORMAT(NOW(), '%Y-%m-%d')
                    THEN '정산미납'
                    ELSE '정산대기' END
                ELSE '정산미확인' END
                ELSE CASE WHEN ADDDATE(DATE_FORMAT(stl.sttl_dt, '%Y%m%d'), store.sttl_rcp_amt_term) < DATE_FORMAT(NOW(), '%Y-%m-%d')
                THEN '정산미납'
                ELSE '정산대기' END
                END
                END
                ELSE '정산대기'
            END AS sttl_add_st_nm,      /* 상태 */
            ]]>
            stl.sttl_mgnt_unq_no,       /* 정산관리고유번호 */
            stl.rcpt_yn,                /* 수납여부(후불사용) */
            DATE_FORMAT(stl.sys_reg_dttm,'%Y.%m.%d %H:%i:%s') AS sys_reg_dttm,
            FN_USER_NM(stl.sys_reg_id) AS sys_reg_nm,
            dspt.dspt_mgnt_no, dspt.dpst_st_cd           /* 여신관리번호 */
        FROM store_base_info store
        INNER JOIN loan_mgnt_base_info loan ON store.loan_mgnt_unq_no = loan.loan_mgnt_unq_no AND store.loan_dvsn = loan.loan_dvsn AND store.store_id = loan.store_id
        INNER JOIN stl_mgnt_base_info stl ON store.store_id = stl.store_id AND store.brand_id = stl.brand_id
        LEFT JOIN loan_mgnt_dspt_proc dspt ON stl.sttl_mgnt_unq_no = dspt.sttl_mgnt_unq_no
        WHERE stl.sttl_mgnt_unq_no = #{sttlMgntUnqNo}
    </select>

    <select id="selectStlMgntDtlPtclList" resultType="com.oqpo.api.entity.settmng.StlMgntDtlPtclEntity">
        /* UnpaidMngMapper.selectStlMgntDtlPtclList */
        SELECT A.sttl_mgnt_unq_no, A.sttl_mgnt_dtl_no,
            A.brand_id, FN_BRAND_NM(A.brand_id) AS brand_nm,
            A.store_id, FN_STORE_NM(A.brand_id, A.store_id) AS store_nm,
            A.item_id, A.item_nm, A.unit, A.unit_amt,
            A.podr_qty, A.dlv_qty,
            A.sttl_dvsn, FN_CODE_NM('STTL_DVSN', A.sttl_dvsn) AS sttl_dvsn_nm,  /* 정산구분 */
            CASE WHEN A.sttl_dvsn = 'SW00' THEN A.whs_qty WHEN A.sttl_dvsn = 'SC00' THEN A.col_qty END AS whs_col_qty,     /* 입고/수거수량 */
            DATE_FORMAT(CASE WHEN A.sttl_dvsn = 'SW00' THEN A.dlv_cmplt_dt WHEN A.sttl_dvsn = 'SC00' THEN A.col_dt END, '%Y.%m.%d') AS whs_col_dt,     /* 입고/수거일자 */
            CASE WHEN A.sttl_dvsn = 'SW00' THEN A.whs_amt WHEN A.sttl_dvsn = 'SC00' THEN A.col_amt END AS whs_col_amt,     /* 입고/수거금액 */
            A.dlv_qty * A.unit_amt AS sttl_req_amt,      /* 정산요청금액 : 납품수량 * 수량 */
            CASE WHEN A.sttl_dvsn = 'SW00' THEN A.pch_podr_unq_no WHEN A.sttl_dvsn = 'SC00' THEN A.rtn_podr_unq_no END AS podr_unq_no,      /* 발주고유번호 */
            CASE WHEN A.sttl_dvsn = 'SW00' THEN A.pch_podr_dtl_no WHEN A.sttl_dvsn = 'SC00' THEN A.rtn_podr_dtl_no END AS podr_dtl_no       /* 발주상세번호 */
        FROM stl_mgnt_dtl_ptcl A
        WHERE A.sttl_mgnt_unq_no = #{sttlMgntUnqNo}
        ORDER BY A.sttl_mgnt_dtl_no ASC
    </select>

    <select id="selectPgKiccBaseInfo" resultType="com.oqpo.api.entity.settmng.PgKiccBaseInfoEntity">
        /* UnpaidMngMapper.selectPgKiccBaseInfo */
        SELECT A.brand_id, A.mall_id, A.use_yn, A.mall_reg_dt, A.mall_del_dt,
            DATE_FORMAT(A.sys_reg_dttm,'%Y.%m.%d %H:%i:%s') AS sys_reg_dttm, A.sys_reg_id,
            DATE_FORMAT(A.sys_chg_dttm,'%Y.%m.%d %H:%i:%s') AS sys_chg_dttm, A.sys_chg_id
        FROM pg_kicc_base_info A
        WHERE A.brand_id = #{brandId}
          AND A.use_yn = 'Y'
        ORDER BY A.sys_reg_dttm DESC
        LIMIT 1
    </select>

    <insert id="insertPgKiccPayPtcl" >
        /* UnpaidMngMapper.insertPgKiccPayPtcl */
        INSERT INTO pg_kicc_pay_ptcl
            (po_ord_no, brand_id, store_id, mall_id, tran_type, res_cd, res_msg, cno, amount, auth_no,
             tran_date, stat_cd, stat_msg, pay_type, card_no, issuer_cd, issuer_nm, acquirer_cd, acquirer_nm,
             install_period, noint, sys_reg_dttm, sys_reg_id, sys_chg_dttm, sys_chg_id)
        VALUES
            (#{entity.poOrdNo}, #{entity.brandId}, #{entity.storeId}, #{entity.mallId},
             #{entity.tranType}, #{entity.resCd}, #{entity.resMsg}, #{entity.cno}, #{entity.amount},
             #{entity.authNo}, #{entity.tranDate}, #{entity.statCd}, #{entity.statMsg}, #{entity.payType},
             #{entity.cardNo}, #{entity.issuerCd}, #{entity.issuerNm}, #{entity.acquirerCd}, #{entity.acquirerNm},
             #{entity.installPeriod}, #{entity.noint},
             NOW(), #{userId}, NOW(), #{userId})
    </insert>

    <update id="updateLoanMgntBaseInfo4UnpaidPay" >
        /* UnpaidMngMapper.updateLoanMgntBaseInfo4UnpaidPay */
        UPDATE loan_mgnt_base_info SET
            use_amt_total = #{entity.useAmtTotal},        /* 사용금액합계 */
            sys_chg_dttm = NOW(),
            sys_chg_id = #{userId}
        WHERE loan_mgnt_unq_no = #{entity.loanMgntUnqNo}
    </update>

</mapper>
