package models

import (
	"WorldEpcho/src/datasource"
	"encoding/json"
	"fmt"
	"log"
)

type DpConversations struct {
	Id          int64    `json:"id"`                          //会话Id
	Uid         int64    `json:"uid"`                         //用户id
	DpIds       []int64  `xorm:"'dp_ids' json" json:"dp_ids"` //数字人Id数组
	AppId       int64    `json:"app_id"`
	Title       string   `json:"title"`
	Description string   `json:"description"`
	IsliuIds    []string `xorm:"'isliu_ids' json" json:"isliu_ids"`
}

// CreateDpConversations 创建一条新的会话记录
func CreateDpConversations(conversation *DpConversations) error {

	_, err := datasource.Engine.Insert(conversation)
	if err != nil {
		return fmt.Errorf("Failed to insert DpConversations: %s", err)
	}
	return nil
}

// DeleteDpConversations 根据id删除会话记录
func DeleteDpConversations(id int64) error {
	_, err := datasource.Engine.ID(id).Delete(&DpConversations{})
	return err
}

//根据会话对象更新会话信息，不存在则插入
func UpdateOrInsertDpsConversations(conversation *DpConversations) error {
	// 尝试更新记录
	affected, err := datasource.Engine.ID(conversation.Id).Update(conversation)
	if err != nil {
		// 错误处理
		return err
	}
	if affected == 0 {
		// 没有更新任何记录，可能是因为记录不存在
		// 执行插入操作
		_, err = datasource.Engine.InsertOne(conversation)
		return err
	}
	// 更新成功，没有错误发生
	return nil
}

// UpdateDpConversations 更新会话信息
func UpdateDpConversations(conversation *DpConversations) error {
	_, err := datasource.Engine.ID(conversation.Id).Update(conversation)
	return err
}

// GetDpConversationsByID 根据id查询会话信息
func GetDpConversationsByID(id int64) (*DpConversations, error) {
	var conversation DpConversations
	_, err := datasource.Engine.ID(id).Get(&conversation)
	if err != nil {
		return nil, err
	}
	return &conversation, nil
}

// GetConversationsByUserIdAndDpId 通过用户id, 数字人id和appId来查询会话记录
func QueryConversationsByUserIdAndDpId(userId int64, dpIds []int64, appId int64) (*DpConversations, error) {
	conversation := DpConversations{Uid: userId, DpIds: dpIds, AppId: appId}

	// 将DpIds转换为JSON字符串
	dpIdsJson, err := json.Marshal(dpIds)
	if err != nil {
		log.Printf("Error marshalling dpIds: %v", err)
		return nil, err
	}
	dpIdsJsonStr := string(dpIdsJson)

	query := fmt.Sprintf("uid = ? AND JSON_CONTAINS(dp_ids, '%s') AND JSON_LENGTH(dp_ids) = JSON_LENGTH('%s') AND app_id = ?", dpIdsJsonStr, dpIdsJsonStr)

	has, err := datasource.Engine.Where(query, userId, appId).Get(&conversation)
	if err != nil {
		log.Printf("Failed to get conversation: %v", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return &conversation, nil
}

func QueryConversationsByUserIdAndDpId1(userId int64, dpIds []int64, appId int64) (*DpConversations, error) {
	conversation := DpConversations{Uid: userId, DpIds: dpIds, AppId: appId}

	//has, err := datasource.Engine.Id(conversation.Id).Get(&conversation)
	has, err := datasource.Engine.Get(&conversation)
	if err != nil {
		log.Printf("Failed to get conversation: %v", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return &conversation, nil
}

// findUniqueConversation 通过用户ID、应用ID和数字人ID数组查询唯一会话
func QueryConversationsByUserIdAndDpId2(uid int64, dpIds []string, appId int64) (*DpConversations, error) {
	var conversation DpConversations

	// 查询条件确保唯一性：用户ID、应用ID和数字人ID数组
	query := `dp_ids IN(?) AND uid = ? AND app_id = ?`
	has, err := datasource.Engine.Where(query, dpIds, uid, appId).Get(&conversation)
	if err != nil {
		return nil, fmt.Errorf("error querying database: %v", err)
	}
	if !has {
		return nil, nil
	}

	return &conversation, nil
}

//
func QueryConversationsByUserIdAndDpId3(uid int64, dpIds []int64, appId int64) (*DpConversations, error) {
	var conversation DpConversations

	// 将dpIds转换为JSON字符串以用于JSON_CONTAINS查询
	dpIdsJson, err := json.Marshal(dpIds)
	if err != nil {
		return nil, fmt.Errorf("error marshalling dpIds: %v", err)
	}

	query := `JSON_CONTAINS(dp_ids, ?) AND uid = ? AND app_id = ?`
	has, err := datasource.Engine.Where(query, dpIdsJson, uid, appId).Get(&conversation)
	if err != nil {
		return nil, fmt.Errorf("error querying database: %v", err)
	}
	if !has {
		return nil, nil
	}

	return &conversation, nil
}
