package voice_broadcast

import (
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/tables/voice_broadcast_img"
)

// AddVoiceBroadcast 新增记录
func (voiceBroadcast *VoiceBroadcast) AddVoiceBroadcast() (err error) {
	err = global.DEFAULT_MYSQL.Create(voiceBroadcast).Error
	return
}

// Update 更新语音播报
func (voiceBroadcast *VoiceBroadcast) Update(updateCols []string) (err error) {
	err = global.DEFAULT_MYSQL.Model(voiceBroadcast).Select(updateCols).Updates(*voiceBroadcast).Error
	return
}

// CreateVoiceBroadcastAndImgs 新增语音播报及图片
func CreateVoiceBroadcastAndImgs(item *VoiceBroadcast, imgs []*voice_broadcast_img.YbVoiceBroadcastImg) (err error) {
	tx := global.DEFAULT_MYSQL.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	if err = tx.Create(item).Error; err != nil {
		return
	}
	imgLen := len(imgs)
	if imgLen > 0 {
		for i := 0; i < imgLen; i++ {
			imgs[i].BroadcastId = item.BroadcastId
		}
		if err = tx.Model(voice_broadcast_img.YbVoiceBroadcastImg{}).CreateInBatches(imgs, len(imgs)).Error; err != nil {
			return
		}
	}
	return
}

// UpdateVoiceBroadcastAndImgs 更新语音播报及图片
func UpdateVoiceBroadcastAndImgs(item *VoiceBroadcast, updateCols []string, imgs []*voice_broadcast_img.YbVoiceBroadcastImg) (err error) {
	tx := global.DEFAULT_MYSQL.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	if err = tx.Model(item).Select(updateCols).Where("broadcast_id = ?", item.BroadcastId).Updates(*item).Error; err != nil {
		return
	}
	if err = tx.Where("broadcast_id = ?", item.BroadcastId).Delete(voice_broadcast_img.YbVoiceBroadcastImg{}).Error; err != nil {
		return
	}
	if len(imgs) > 0 {
		if err = tx.Model(voice_broadcast_img.YbVoiceBroadcastImg{}).CreateInBatches(imgs, len(imgs)).Error; err != nil {
			return
		}
	}
	return
}