package speech_recognition

import (
	"eta/eta_api/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

// SpeechRecognitionContent 语音识别-内容表
type SpeechRecognitionContent struct {
	SpeechRecognitionContentId int       `orm:"column(speech_recognition_content_id);pk"`
	SpeechRecognitionId        int       `description:"语音识别ID"`
	Sort                       int       `description:"段落排序"`
	Content                    string    `description:"段落内容"`
	StartMs                    int       `description:"单句开始时间（毫秒）"`
	EndMs                      int       `description:"单句结束时间（毫秒）"`
	IsUpdate                   int       `description:"是否手动修改过：0-否；1-是"`
	CreateTime                 time.Time `description:"创建时间"`
	ModifyTime                 time.Time `description:"修改时间"`
}

var SpeechRecognitionContentCols = struct {
	SpeechRecognitionContentId string
	SpeechRecognitionId        string
	Sort                       string
	Content                    string
	StartMs                    string
	EndMs                      string
	IsUpdate                   string
	CreateTime                 string
	ModifyTime                 string
}{
	SpeechRecognitionContentId: "speech_recognition_content_id",
	SpeechRecognitionId:        "speech_recognition_id",
	Sort:                       "sort",
	Content:                    "content",
	StartMs:                    "start_ms",
	EndMs:                      "end_ms",
	IsUpdate:                   "is_update",
	CreateTime:                 "create_time",
	ModifyTime:                 "modify_time",
}

func (m *SpeechRecognitionContent) TableName() string {
	return "speech_recognition_content"
}

func (m *SpeechRecognitionContent) PrimaryId() string {
	return SpeechRecognitionContentCols.SpeechRecognitionContentId
}

func (m *SpeechRecognitionContent) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.SpeechRecognitionContentId = int(id)
	return
}

func (m *SpeechRecognitionContent) CreateMulti(items []*SpeechRecognitionContent) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *SpeechRecognitionContent) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

func (m *SpeechRecognitionContent) Del() (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	_, err = o.Raw(sql, m.SpeechRecognitionContentId).Exec()
	return
}

func (m *SpeechRecognitionContent) MultiDel(menuIds []int) (err error) {
	if len(menuIds) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
	_, err = o.Raw(sql, menuIds).Exec()
	return
}

func (m *SpeechRecognitionContent) GetItemById(id int) (item *SpeechRecognitionContent, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *SpeechRecognitionContent) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *SpeechRecognitionContent, err error) {
	o := orm.NewOrm()
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *SpeechRecognitionContent) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *SpeechRecognitionContent) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*SpeechRecognitionContent, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *SpeechRecognitionContent) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*SpeechRecognitionContent, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type SpeechRecognitionContentItem struct {
	SpeechRecognitionContentId int
	SpeechRecognitionId        int    `description:"语音识别ID"`
	Sort                       int    `description:"段落排序"`
	Content                    string `description:"段落内容"`
	StartMs                    int    `description:"单句开始时间（毫秒）"`
	EndMs                      int    `description:"单句结束时间（毫秒）"`
	StartTime                  string `description:"开始时间, 格式HH:MM:SS"`
	CreateTime                 string `description:"创建时间"`
	ModifyTime                 string `description:"修改时间"`
	HideTimestamp              bool   `description:"前端用的, 默认false就行"`
	IsHover                    bool   `description:"前端用的, 默认false就行"`
}

func FormatSpeechRecognitionContent2Item(origin *SpeechRecognitionContent) (item *SpeechRecognitionContentItem) {
	if origin == nil {
		return
	}
	item = new(SpeechRecognitionContentItem)
	item.SpeechRecognitionContentId = origin.SpeechRecognitionContentId
	item.SpeechRecognitionId = origin.SpeechRecognitionId
	item.Sort = origin.Sort
	item.Content = origin.Content
	item.StartMs = origin.StartMs
	item.EndMs = origin.EndMs
	item.StartTime = utils.MillisecondsToHHMMSS(origin.StartMs)
	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, origin.CreateTime)
	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, origin.ModifyTime)
	return
}

// BatchUpdateContents 批量更新语音识别内容
func (m *SpeechRecognitionContent) BatchUpdateContents(contents []SpeechRecognitionSaveContentReq) (err error) {
	if len(contents) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := fmt.Sprintf(`UPDATE %s SET %s = ?, %s = 1, %s = NOW() WHERE %s = ?`, m.TableName(), SpeechRecognitionContentCols.Content, SpeechRecognitionContentCols.IsUpdate, SpeechRecognitionContentCols.ModifyTime, SpeechRecognitionContentCols.SpeechRecognitionContentId)
	p, err := o.Raw(sql).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close()
	}()
	for _, v := range contents {
		_, err = p.Exec(v.Content, v.SpeechRecognitionContentId)
		if err != nil {
			return
		}
	}
	return
}

// ClearContentBySpeechId 清除转写文件内容
func (m *SpeechRecognitionContent) ClearContentBySpeechId(speechId int) (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ?`, m.TableName(), SpeechRecognitionContentCols.SpeechRecognitionId)
	_, err = o.Raw(sql, speechId).Exec()
	return
}
