package live_title_record_service

import (
	"bwallet/models"
	"time"
)

type LiveTitleRecord struct {
	Id           int
	LiveId       int
	CurrentTitle string
	NewTitle     string
	Status       uint8
	PlatformId   int64

	PageNum  int
	PageSize int
}

func (r *LiveTitleRecord) GetRecord() (*models.LiveTitleRecord, error) {
	record, err := models.GetRecord(r.Id)
	if err != nil {
		return nil, err
	}

	return record, nil
}

func (l *LiveTitleRecord) GetAll() ([]*models.LiveTitleRecord, error) {
	var live []*models.LiveTitleRecord
	live, err := models.GetLiveTitleRecord(l.PageNum, l.PageSize, l.getMaps())
	if err != nil {
		return nil, err
	}

	var records []*models.LiveTitleRecord
	for _, value := range live {
		record := &models.LiveTitleRecord{}
		record.ID = value.ID
		record.CurrentTitle = value.CurrentTitle
		record.NewTitle = value.NewTitle
		record.Status = value.Status
		record.LiveId = value.LiveId
		record.CreatedTime = time.Unix(value.CreateTime, 0).Format("2006-01-02 15:04:05")
		record.ApplyId = value.LiveInfo.ApplyId

		records = append(records, record)
	}

	return records, nil
}

func (l *LiveTitleRecord) Add() error {
	live := map[string]interface{}{
		"live_id":       l.LiveId,
		"current_title": l.CurrentTitle,
		"new_title":     l.NewTitle,
		"platform_id":   l.PlatformId,
	}

	if err := models.AddLiveTitleRecord(live); err != nil {
		return err
	}

	return nil
}

func (l *LiveTitleRecord) Verify() error {
	return models.EditLiveTitleRecord(l.Id, map[string]interface{}{
		"status": l.Status,
	})
}

func (l *LiveTitleRecord) Edit() error {
	return models.EditLiveTitleRecord(l.Id, map[string]interface{}{
		"new_title": l.NewTitle,
	})
}

func (l *LiveTitleRecord) ExistById() (bool, error) {
	return models.ExistLiveTitleRecordById(l.Id)
}

func (l *LiveTitleRecord) Count() (int, error) {
	return models.GetLiveTitleRecordTotal(l.getMaps())
}

func (l *LiveTitleRecord) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if l.Id != 0 {
		maps["id"] = l.Id
	}

	if l.PlatformId != 0 {
		maps["platform_id"] = l.PlatformId
	}

	maps["status"] = l.Status

	return maps
}
