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

    <insert id="insertOrUpdateList" parameterType="list">
        INSERT INTO stock_ths_member
            (ts_code, con_code, con_name, weight, in_date, out_date, is_new)
        VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.ts_code},
            #{item.con_code},
            #{item.con_name},
            #{item.weight},
            TO_DATE(#{item.in_date}, 'YYYYMMDD'),
            TO_DATE(#{item.out_date}, 'YYYYMMDD'),
            #{item.is_new}
             )
        </foreach>
        ON CONFLICT (ts_code, con_code, con_name) DO UPDATE SET
			ts_code = EXCLUDED.ts_code,
			con_code = EXCLUDED.con_code,
			con_name = EXCLUDED.con_name,
			weight = EXCLUDED.weight,
			in_date = EXCLUDED.in_date,
            out_date = EXCLUDED.out_date,
            is_new = EXCLUDED.is_new
    </insert>
    
    <select id="getThsMembers" resultType="StockInfo">
        SELECT con_code AS ts_code, name FROM stock_ths_member WHERE ts_code = #{tsCode}
    </select>
    
    <select id="getBelongings" resultType="java.lang.String">
        SELECT STRING_AGG(list."name", ', ') FROM stock_ths_list list 
        WHERE list.ts_code IN (
            SELECT 
                m.ts_code
            FROM "stock_ths_member" m 
            WHERE m.con_code = #{tsCode}
        )
    </select>
</mapper>
