/*
C# version of join_text:

public class TabletItem
{
    public int num { get; set; }
    public string fam_name { get; set; }
    public object fam_gender { get; set; }
    public object deceased { get; set; }
    public bool option_break { get; set; }
}

public class TabletJson
{
    public List<TabletItem> mid_items { get; set; }
    public List<TabletItem> left_items { get; set; }
}

public string JoinText(List<TabletItem> items)
{
    if (items == null || items.Count == 0)
        return string.Empty;

    StringBuilder result = new StringBuilder();
    
    for (int i = 0; i < items.Count; i++)
    {
        result.Append(items[i].fam_name);
        
        // Add break if option_break is true and not the last item
        if (items[i].option_break && i < items.Count - 1)
        {
            result.Append("<br>");
        }
        // Add space between names if not the last item and no break
        else if (i < items.Count - 1)
        {
            result.Append(" ");
        }
    }
    
    return result.ToString();
}

// Usage example:
public string[] ProcessTabletJson(string jsonString)
{
    string[] ret = new string[2];
    
    // Deserialize JSON string to TabletJson object
    TabletJson tabletJsonObj = JsonConvert.DeserializeObject<TabletJson>(jsonString);
    
    // Process mid_items and left_items
    ret[0] = JoinText(tabletJsonObj.mid_items);
    ret[1] = JoinText(tabletJsonObj.left_items);
    
    return ret;
}
*/

-- {"mid_items":[
--     {"num":0,"fam_name":" ","fam_gender":null,"deceased":null,"option_break":true},
--     {"num":0,"fam_name":"無始劫以來累世冤親債主1 ","fam_gender":null,"deceased":null,"option_break":true},
--     {"num":0,"fam_name":"無始劫以來累世冤親債主2 ","fam_gender":null,"deceased":null,"option_break":true},
--     {"num":0,"fam_name":" ","fam_gender":null,"deceased":null,"option_break":true}],
-- "left_items":[
--     {"num":0,"fam_name":" ","fam_gender":null,"deceased":null,"option_break":true},
--     {"num":0,"fam_name":"祁哲榮1 ","fam_gender":null,"deceased":null,"option_break":true},
--     {"num":0,"fam_name":"祁哲榮2","fam_gender":null,"deceased":null,"option_break":true}
-- ]}

-- 轉換牌位文本為 JSON 格式
DECLARE @InputText NVARCHAR(MAX)
DECLARE @Result NVARCHAR(MAX)
DECLARE @MidText NVARCHAR(MAX)
DECLARE @LeftText NVARCHAR(MAX)
DECLARE @StartPos INT
DECLARE @EndPos INT
DECLARE @Line NVARCHAR(1000)
DECLARE @First BIT
DECLARE @MidStart INT
DECLARE @LeftStart INT

-- 宣告游標變數
DECLARE @num INT
DECLARE @f_num_tablet NVARCHAR(MAX)
DECLARE @from_id_tablet NVARCHAR(MAX)

-- 宣告游標
DECLARE tablet_cursor CURSOR FOR
SELECT num, f_num_tablet, from_id_tablet
FROM pro_order_detail

-- 打開游標
OPEN tablet_cursor

-- 讀取第一筆資料
FETCH NEXT FROM tablet_cursor INTO @num, @f_num_tablet, @from_id_tablet

-- 開始處理每一筆資料
WHILE @@FETCH_STATUS = 0
BEGIN
    -- 設置輸入文本
    SET @InputText = @from_id_tablet
    
    -- 找到 #牌位 和 #陽上 的位置
    SET @MidStart = CHARINDEX('#牌位', @InputText) + 3
    SET @LeftStart = CHARINDEX('#陽上', @InputText)
    
    -- 如果找到正確的格式
    IF @MidStart > 3 AND @LeftStart > 0
    BEGIN
        -- 取得兩段文字
        SET @MidText = SUBSTRING(@InputText, @MidStart, @LeftStart - @MidStart)
        SET @LeftText = SUBSTRING(@InputText, @LeftStart + 3, LEN(@InputText))
        
        -- 建立 JSON
        SET @Result = '{"mid_items":['
        
        -- 處理 mid_items
        SET @StartPos = 1
        SET @EndPos = CHARINDEX(CHAR(10), @MidText, @StartPos)
        SET @First = 1
        
        WHILE @EndPos > 0
        BEGIN
            SET @Line = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(
                SUBSTRING(@MidText, @StartPos, @EndPos - @StartPos),
                CHAR(13), ''), CHAR(10), ''), CHAR(9), '')))
            IF LEN(@Line) > 0
            BEGIN
                IF @First = 0
                    SET @Result = @Result + ','
                SET @Result = @Result + '{"num":0,"fam_name":"' + @Line + 
                             '","fam_gender":null,"deceased":null,"option_break":true}'
                SET @First = 0
            END
            SET @StartPos = @EndPos + 1
            SET @EndPos = CHARINDEX(CHAR(10), @MidText, @StartPos)
        END
        
        SET @Line = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(
            SUBSTRING(@MidText, @StartPos, LEN(@MidText)),
            CHAR(13), ''), CHAR(10), ''), CHAR(9), '')))
        IF LEN(@Line) > 0
        BEGIN
            IF @First = 0
                SET @Result = @Result + ','
            SET @Result = @Result + '{"num":0,"fam_name":"' + @Line + 
                         '","fam_gender":null,"deceased":null,"option_break":true}'
        END
        
        SET @Result = @Result + '],"left_items":['
        
        -- 處理 left_items
        SET @StartPos = 1
        SET @EndPos = CHARINDEX(CHAR(10), @LeftText, @StartPos)
        SET @First = 1
        
        WHILE @EndPos > 0
        BEGIN
            SET @Line = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(
                SUBSTRING(@LeftText, @StartPos, @EndPos - @StartPos),
                CHAR(13), ''), CHAR(10), ''), CHAR(9), '')))
            IF LEN(@Line) > 0
            BEGIN
                IF @First = 0
                    SET @Result = @Result + ','
                SET @Result = @Result + '{"num":0,"fam_name":"' + @Line + 
                             '","fam_gender":null,"deceased":null,"option_break":true}'
                SET @First = 0
            END
            SET @StartPos = @EndPos + 1
            SET @EndPos = CHARINDEX(CHAR(10), @LeftText, @StartPos)
        END
        
        SET @Line = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(
            SUBSTRING(@LeftText, @StartPos, LEN(@LeftText)),
            CHAR(13), ''), CHAR(10), ''), CHAR(9), '')))
        IF LEN(@Line) > 0
        BEGIN
            IF @First = 0
                SET @Result = @Result + ','
            SET @Result = @Result + '{"num":0,"fam_name":"' + @Line + 
                         '","fam_gender":null,"deceased":null,"option_break":true}'
        END
        
        SET @Result = @Result + ']}'
        
        -- 更新資料庫
        UPDATE pro_order_detail
        SET f_num_tablet = @Result
        WHERE num = @num
    END
    
    -- 讀取下一筆資料
    FETCH NEXT FROM tablet_cursor INTO @num, @f_num_tablet, @from_id_tablet
END

-- 關閉並釋放游標
CLOSE tablet_cursor
DEALLOCATE tablet_cursor