<?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.market.mapper.SpotKlineMapper">

    <resultMap id="BaseResultMap" type="com.market.entity.Kline">
        <id     column="id"        property="id"        jdbcType="BIGINT"/>
        <result column="period"    property="period"    jdbcType="VARCHAR"/>
        <result column="open"      property="open"      jdbcType="DECIMAL"/>
        <result column="close"     property="close"     jdbcType="DECIMAL"/>
        <result column="high"      property="high"      jdbcType="DECIMAL"/>
        <result column="low"       property="low"       jdbcType="DECIMAL"/>
        <result column="volume"    property="volume"    jdbcType="DECIMAL"/>
        <result column="turnover"  property="turnover"  jdbcType="DECIMAL"/>
        <result column="beginTime" property="beginTime" jdbcType="BIGINT"/>
        <result column="endTime"   property="endTime"   jdbcType="BIGINT"/>
    </resultMap>

    <!-- 查询指定周期和时间范围的 K 线数据 -->
    <select id="selectByPeriodAndTimeRange" resultMap="BaseResultMap">
        SELECT * FROM ${tableName}
        WHERE period = #{period}
        <if test="startTime != null">
            AND beginTime &gt;= #{startTime}
        </if>
        <if test="endTime != null">
            AND beginTime &lt;= #{endTime}
        </if>
        ORDER BY beginTime DESC
        <if test="limit != null">
            LIMIT #{limit}
        </if>
    </select>

    <!-- 按周期和开始时间查询单条（去重用） -->
    <select id="selectByPeriodAndBeginTime" resultMap="BaseResultMap">
        SELECT * FROM ${tableName}
        WHERE period = #{period} AND beginTime = #{beginTime}
        LIMIT 1
    </select>

    <!-- 插入 K 线 -->
    <insert id="insertKline" useGeneratedKeys="true" keyProperty="kline.id">
        INSERT INTO ${tableName} (period, open, close, high, low, volume, turnover, beginTime, endTime)
        VALUES (#{kline.period}, #{kline.open}, #{kline.close}, #{kline.high}, #{kline.low},
                #{kline.volume}, #{kline.turnover}, #{kline.beginTime}, #{kline.endTime})
    </insert>

    <!-- 更新 K 线 -->
    <update id="updateKline">
        UPDATE ${tableName}
        SET open      = #{kline.open},
            close     = #{kline.close},
            high      = #{kline.high},
            low       = #{kline.low},
            volume    = #{kline.volume},
            turnover  = #{kline.turnover},
            endTime   = #{kline.endTime}
        WHERE id = #{kline.id}
    </update>

    <!-- 检查表是否存在 -->
    <select id="checkTableExists" resultType="int">
        SELECT COUNT(*) FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = #{tableName}
    </select>

    <!-- 创建 K 线表 -->
    <update id="createKlineTable">
        CREATE TABLE IF NOT EXISTS ${tableName} (
            `id`        bigint        NOT NULL AUTO_INCREMENT,
            `period`    varchar(20)   NOT NULL,
            `open`      decimal(20,8) NOT NULL,
            `close`     decimal(20,8) NOT NULL,
            `high`      decimal(20,8) NOT NULL,
            `low`       decimal(20,8) NOT NULL,
            `volume`    decimal(20,8) NOT NULL,
            `turnover`  decimal(20,8) NOT NULL,
            `beginTime` bigint        NOT NULL,
            `endTime`   bigint        NOT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uk_period_beginTime` (`period`, `beginTime`),
            KEY `idx_beginTime` (`beginTime`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    </update>

    <!-- 按 beginTimes 批量查询（同步去重） -->
    <select id="selectByBeginTimes" resultMap="BaseResultMap">
        SELECT * FROM ${tableName}
        WHERE period = #{period}
        AND beginTime IN
        <foreach collection="beginTimes" item="t" open="(" separator="," close=")">
            #{t}
        </foreach>
    </select>

    <!-- 批量插入 K 线 -->
    <insert id="batchInsertKline">
        INSERT INTO ${tableName} (period, open, close, high, low, volume, turnover, beginTime, endTime)
        VALUES
        <foreach collection="klines" item="k" separator=",">
            (#{k.period}, #{k.open}, #{k.close}, #{k.high}, #{k.low},
             #{k.volume}, #{k.turnover}, #{k.beginTime}, #{k.endTime})
        </foreach>
    </insert>

    <!-- 按 period + beginTime 直接更新单条 K 线（实时同周期写库，无需 id） -->
    <update id="updateKlineByTime">
        UPDATE ${tableName}
        SET open     = #{kline.open},
            close    = #{kline.close},
            high     = #{kline.high},
            low      = #{kline.low},
            volume   = #{kline.volume},
            turnover = #{kline.turnover},
            endTime  = #{kline.endTime}
        WHERE period = #{kline.period} AND beginTime = #{kline.beginTime}
    </update>

    <!-- 批量更新 K 线（按 period + beginTime 匹配） -->
    <update id="batchUpdateKline">
        <foreach collection="klines" item="k" separator=";">
            UPDATE ${tableName}
            SET open     = #{k.open},
                close    = #{k.close},
                high     = #{k.high},
                low      = #{k.low},
                volume   = #{k.volume},
                turnover = #{k.turnover},
                endTime  = #{k.endTime}
            WHERE period = #{k.period} AND beginTime = #{k.beginTime}
        </foreach>
    </update>

</mapper>
