package models

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

type MediaType string
type SendStatus string

const (
	Video  MediaType  = "video"
	Audio  MediaType  = "audio"
	UNSEND SendStatus = "UNSEND"
	SEND   SendStatus = "SEND"
)

func (m *Media) ToView() *ESMedia {
	return &ESMedia{
		MediaId:               m.Id,
		AuthorId:              m.AuthorId,
		AuthorName:            m.AuthorName,
		MediaType:             m.MediaType,
		CoverSrc:              m.CoverSrc,
		Src:                   m.Src,
		MediaName:             m.MediaName,
		SourceType:            m.SourceType,
		MediaPlayMilliseconds: m.MediaPlayMilliseconds,
		PermissionIds:         m.PermissionIds,
		PublishedTime:         m.PublishedTime.Format(time.DateTime),
	}
}

type ESMedia struct {
	MediaId               int       `json:"mediaId"`
	AuthorId              int       `json:"authorId"`
	AuthorName            string    `json:"authorName"`
	CoverSrc              string    `json:"coverSrc"`
	MediaType             MediaType `json:"mediaType"`
	Src                   string    `json:"src"`
	MediaName             string    `json:"mediaName"`
	SourceType            string    `json:"sourceType"`
	MediaPlayMilliseconds int       `json:"mediaPlayMilliseconds"`
	PermissionIds         string    `json:"permissionIds"`
	PublishedTime         string    `json:"publishedTime"`
}
type MediaView struct {
	MediaId               int       `json:"mediaId"`
	AuthorId              int       `json:"authorId"`
	AuthorName            string    `json:"authorName"`
	CoverSrc              string    `json:"coverSrc"`
	MediaType             MediaType `json:"mediaType"`
	Src                   string    `json:"src"`
	MediaName             string    `json:"mediaName"`
	SourceType            string    `json:"sourceType"`
	MediaPlayMilliseconds int       `json:"mediaPlayMilliseconds"`
	PermissionIds         string    `json:"permissionIds"`
	PermissionNames       string    `json:"permission_names"`
	PublishedTime         string    `json:"publishedTime"`
}

func (m *Media) ToMediaView() (message *MediaView) {
	message = &MediaView{
		MediaId:               m.Id,
		AuthorId:              m.AuthorId,
		AuthorName:            m.AuthorName,
		MediaType:             m.MediaType,
		Src:                   m.Src,
		CoverSrc:              m.CoverSrc,
		MediaName:             m.MediaName,
		SourceType:            m.SourceType,
		MediaPlayMilliseconds: m.MediaPlayMilliseconds,
		PermissionIds:         m.PermissionIds,
		PublishedTime:         m.PublishedTime.Format(time.DateTime),
	}
	//image, err := GetImageById(m.CoverSrc)
	//if err != nil || image == nil {
	//	message.CoverSrc = ""
	//} else {
	//	message.CoverSrc = image.SrcUrl
	//}
	ids := strings.Split(m.PermissionIds, ",")
	var idList []int
	for _, id := range ids {
		var idInt int
		idInt, err := strconv.Atoi(id)
		if err != nil {
			utils.FileLog.Error("转换品种名称失败：%v", err)
			break
		}
		idList = append(idList, idInt)
	}
	if len(idList) > 0 {
		names, err := GetPermissionNames(idList)
		if err != nil {
			utils.FileLog.Error("获取品种名称失败：%v", err)
		}
		message.PermissionNames = strings.Join(names, ",")
	}
	return
}
func (m *Media) ToMessageView() (message *MessageMedia) {
	message = &MessageMedia{
		MediaId:               m.Id,
		AuthorId:              m.AuthorId,
		AuthorName:            m.AuthorName,
		MediaType:             m.MediaType,
		Src:                   m.Src,
		CoverSrc:              m.CoverSrc,
		MediaName:             m.MediaName,
		SourceType:            m.SourceType,
		SendStatus:            m.SendStatus,
		MediaPlayMilliseconds: m.MediaPlayMilliseconds,
		PermissionIds:         m.PermissionIds,
		PublishedTime:         m.PublishedTime.Format(time.DateTime),
	}
	//image, err := GetImageById(m.CoverSrc)
	//if err != nil || image == nil {
	//	message.CoverSrc = ""
	//} else {
	//	message.CoverSrc = image.SrcUrl
	//}
	ids := strings.Split(m.PermissionIds, ",")
	var idList []int
	for _, id := range ids {
		var idInt int
		idInt, err := strconv.Atoi(id)
		if err != nil {
			utils.FileLog.Error("转换品种名称失败：%v", err)
			break
		}
		idList = append(idList, idInt)
	}
	if len(idList) > 0 {
		names, err := GetPermissionNames(idList)
		if err != nil {
			utils.FileLog.Error("获取品种名称失败：%v", err)
		}
		message.PermissionNames = strings.Join(names, ",")
	}
	return
}

type MessageMedia struct {
	MediaId               int        `json:"mediaId"`
	AuthorId              int        `json:"authorId"`
	AuthorName            string     `json:"authorName"`
	CoverSrc              string     `json:"coverSrc"`
	MediaType             MediaType  `json:"mediaType"`
	Src                   string     `json:"src"`
	MediaName             string     `json:"mediaName"`
	SourceType            string     `json:"sourceType"`
	SendStatus            SendStatus `json:"sendStatus"`
	MediaPlayMilliseconds int        `json:"mediaPlayMilliseconds"`
	PermissionIds         string     `json:"permissionIds"`
	PermissionNames       string     `description:"permission_names"`
	PublishedTime         string     `json:"publishedTime"`
}
type Media struct {
	Id                    int        `orm:"pk;auto" description:"id"`
	AuthorId              int        `description:"author_id"`
	AuthorName            string     `description:"author_name"`
	CoverSrc              string     `description:"cover_src"`
	MediaType             MediaType  `description:"media_type"`
	Src                   string     `description:"src"`
	MediaName             string     `description:"media_name"`
	SourceType            string     `description:"source_type"`
	MediaPlayMilliseconds int        `description:"media_play_milliseconds"`
	PermissionIds         string     `description:"permission_ids"`
	PublishedTime         time.Time  `description:"published_time"`
	SendStatus            SendStatus `json:"sendStatus"`
	Deleted               int        `description:"deleted"`
	CreatedTime           time.Time  `description:"created_time"`
	UpdatedTime           time.Time  `description:"updated_time"`
}

func GetMediaCountByCondition(media MediaType, condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(*) AS count FROM media WHERE 1 =1  AND media_type = ? `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, media, pars).QueryRow(&count)
	return
}
func (m *Media) UpdateSendStatus(statusType SendStatus) (err error) {
	o := orm.NewOrm()
	m.SendStatus = statusType
	_, err = o.Update(m, "send_status")
	return
}
func GetMediaById(media MediaType, id int) (item *Media, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM media WHERE 1 = 1 AND media_type = ?  and id =? AND deleted=0`
	err = o.Raw(sql, media, id).QueryRow(&item)
	return
}
func GetMediaByCondition(media MediaType, condition string, sortCondition string, pars []interface{}, startPage, pageSize int) (items []*Media, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM media WHERE 1 = 1 AND media_type = ? AND deleted=0`
	if condition != "" {
		sql += condition
	}
	if sortCondition != "" {
		sql += sortCondition // 排序
	}
	sql += ` LIMIT ?, ?`
	_, err = o.Raw(sql, media, pars, startPage, pageSize).QueryRows(&items)
	return
}
func InsertMedia(m *Media) (err error) {
	tx, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	if err != nil {
		fmt.Printf("%v", err)
		return
	}
	defer func() {
		if r := recover(); r != nil {
			_ = tx.Rollback()
			return
		}

		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()
	insertId, err := tx.Insert(m)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	m.Id = int(insertId)

	permissionMappingList := make([]*MediaPermissionMapping, 0)
	ids := strings.Split(m.PermissionIds, ",")
	for _, item := range ids {
		x, _ := strconv.Atoi(item)
		permissionMappingList = append(permissionMappingList, &MediaPermissionMapping{
			MediaId:      m.Id,
			MediaType:    m.MediaType,
			PermissionId: x,
			CreatedTime:  time.Now(),
		})
	}
	_, err = tx.InsertMulti(500, permissionMappingList)

	return
}
func DeleteMedia(m *Media) (err error) {
	o := orm.NewOrm()
	if err != nil {
		return err
	}
	tx, err := o.Begin()
	if err != nil {
		fmt.Printf("%v", err)
		return
	}
	defer func() {
		if r := recover(); r != nil {
			_ = tx.Rollback()
			return
		}
	}()
	err = DeleteMappingsById(m.Id)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	_, err = o.Update(m, "deleted")
	if err != nil {
		_ = tx.Rollback()
		return
	}
	_ = tx.Commit()
	return
}
func UpdateMedia(m *Media) (updateId int64, err error) {
	o := orm.NewOrm()
	if err != nil {
		return 0, err
	}
	tx, err := o.Begin()
	if err != nil {
		fmt.Printf("%v", err)
		return
	}
	defer func() {
		if r := recover(); r != nil {
			_ = tx.Rollback()
			return
		}
	}()
	err = DeleteMappingsById(m.Id)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	updateId, err = o.Update(m, "author_id", "author_name", "cover_src", "src", "media_play_milliseconds", "permission_ids")
	if err != nil {
		_ = tx.Rollback()
		return
	}
	ids := strings.Split(m.PermissionIds, ",")
	for _, item := range ids {
		x, _ := strconv.Atoi(item)
		mapping := &MediaPermissionMapping{
			MediaId:      m.Id,
			MediaType:    m.MediaType,
			PermissionId: x,
			CreatedTime:  time.Now(),
		}
		_, err = o.Insert(mapping)
		if err != nil {
			_ = tx.Rollback()
			return
		}
	}
	_ = tx.Commit()
	return
}
