<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="link.at17.mid.tushare.dao.StockAdjustDao">

    <insert id="insertOrUpdateList" parameterType="list">
        INSERT INTO stock_adjust_factor_tushare
            (ts_code, trade_date, adj_factor)
        VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.ts_code}, 
             TO_DATE(#{item.trade_date}, 'YYYYMMDD'),
             #{item.adj_factor}
             )
        </foreach>
        ON CONFLICT (ts_code, trade_date) DO UPDATE SET
            ts_code = EXCLUDED.ts_code,
            trade_date = EXCLUDED.trade_date,
            adj_factor = EXCLUDED.adj_factor
    </insert>
    
    <select id="getLatestTradeDate" resultType="java.time.LocalDateTime">
        SELECT
            MAX(trade_date)
        FROM
            stock_adjust_factor_tushare
        WHERE
            1 = 1
	        <if test="stockInfo != null and stockInfo.getTsCode() != null and stockInfo.getTsCode() != ''">
	            AND ts_code = #{stockInfo.tsCode}
	        </if>
    </select>
    
    <select id="getAllTradeDates" resultType="java.time.LocalDateTime">
        SELECT
            DISTINCT trade_date
        FROM
            stock_adjust_factor_tushare
        WHERE
            1 = 1
	        <if test="stockInfo != null and stockInfo.getTsCode() != null and stockInfo.getTsCode() != ''">
	            AND ts_code = #{stockInfo.tsCode}
	        </if>
    </select>
    
    <select id="getAllMissingDates" resultType="java.time.LocalDateTime">
        SELECT DISTINCT date
        FROM   stock_calendar
        WHERE  stock_calendar.is_open = TRUE
        <if test="stockInfo != null and stockInfo.getTsCode() != null and stockInfo.getTsCode() != ''">
            <choose>
                <when test="stockInfo.getTsCode().endsWith('SZ')">
                    AND stock_calendar.exchange = 'SZSE'
                </when>
                <when test="stockInfo.getTsCode().endsWith('SH')">
                    AND stock_calendar.exchange = 'SSE'
                </when>
                <otherwise></otherwise>
            </choose>
        </if>
        AND date NOT IN (
            SELECT trade_date
            FROM   stock_adjust_factor_tushare
            WHERE  1 = 1
            <if test="stockInfo != null and stockInfo.getTsCode() != null and stockInfo.getTsCode() != ''">
                AND ts_code = #{stockInfo.tsCode}
	        </if>
        )
        <if test="stockInfo != null and stockInfo.getListDate() != null">
            AND date >= #{stockInfo.listDate}
        </if>
        AND date &lt; CURRENT_DATE + INTERVAL '1 DAY'
        ORDER BY date ASC
    </select>

</mapper>
