package services

import (
	"errors"
	"eta/eta_api/models"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// GetEnglishVideoCoverList 封面库列表
func GetEnglishVideoCoverList(condition string, pars []interface{}, orderRule string, startSize, pageSize int) (total int, resp *models.EnglishVideoCoverListResp, err error) {
	resp = new(models.EnglishVideoCoverListResp)
	total, list, e := models.GetEnglishVideoCoverPageList(condition, pars, orderRule, startSize, pageSize)
	if e != nil {
		err = errors.New("获取封面库列表失败, Err:" + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}
	respList := make([]*models.EnglishVideoCoverItem, 0)
	for _, v := range list {
		item := &models.EnglishVideoCoverItem{
			Id:         v.Id,
			CoverName:  v.CoverName,
			CoverUrl:   v.CoverUrl,
			CreateTime: v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime: v.ModifyTime.Format(utils.FormatDateTime),
		}
		respList = append(respList, item)
	}
	resp.List = respList
	return
}

// SaveEnglishVideoCover 保存视频封面
func SaveEnglishVideoCover(coverId int, coverName, coverUrl string) (resp *models.EnglishVideoCoverItem, errMsg string, err error) {
	resp = new(models.EnglishVideoCoverItem)
	nowTime := time.Now().Local()
	// 更新
	if coverId > 0 {
		item, e := models.GetEnglishVideoCoverById(coverId)
		if e != nil {
			if e.Error() == utils.ErrNoRow() {
				errMsg = "封面不存在"
				err = errors.New(errMsg)
				return
			}
			errMsg = "封面信息有误"
			err = errors.New("获取封面图失败, Err:" + e.Error())
			return
		}
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "CoverName", "CoverUrl", "ModifyTime")
		item.CoverName = coverName
		item.CoverUrl = coverUrl
		item.ModifyTime = nowTime
		if e := item.Update(updateCols); e != nil {
			errMsg = "更新失败"
			err = errors.New("更新封面图失败, Err:" + e.Error())
		}
		resp = formatEnglishVideoCoverItem(item)
		return
	}
	// 新增
	newCover := &models.EnglishVideoCover{
		CoverName:  coverName,
		CoverUrl:   coverUrl,
		CreateTime: nowTime,
		ModifyTime: nowTime,
	}
	if e := newCover.Add(); e != nil {
		errMsg = "新增失败"
		err = errors.New("新增封面图失败, Err:" + e.Error())
	}
	resp = formatEnglishVideoCoverItem(newCover)
	return
}

func formatEnglishVideoCoverItem(item *models.EnglishVideoCover) (resp *models.EnglishVideoCoverItem) {
	resp = new(models.EnglishVideoCoverItem)
	if item != nil {
		resp.Id = item.Id
		resp.CoverName = item.CoverName
		resp.CoverUrl = item.CoverUrl
		resp.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
		resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
	}
	return
}

// SoftDeleteEnglishVideoCover 删除封面图
func SoftDeleteEnglishVideoCover(coverId int) (errMsg string, err error) {
	if _, e := models.GetEnglishVideoCoverById(coverId); e != nil {
		errMsg = "封面图信息有误"
		err = errors.New("获取封面图失败, Err:" + e.Error())
		return
	}
	if e := models.DeleteEnglishVideoCover(coverId); e != nil {
		errMsg = "删除失败"
		err = errors.New("删除封面图失败, Err:" + e.Error())
	}
	return
}

// SaveEnglishVideo 创建线上路演
func SaveEnglishVideo(req models.SaveEnglishVideoReq, adminInfo *system.Admin) (newReportId int, videoCode string, err error, errMsg string) {
	// 查询分类是否存在
	req.Overview = strings.Replace(req.Overview, "Powered by Froala Editor", "", -1)
	var classifyIds []int
	classifyIds = append(classifyIds, req.ClassifyIdFirst)
	if req.ClassifyIdSecond > 0 {
		classifyIds = append(classifyIds, req.ClassifyIdSecond)
	}
	classifyList, err := models.GetEnglishReportClassifyByIds(classifyIds)
	if err != nil {
		err = fmt.Errorf("查询线上路演分类出错")
		errMsg = fmt.Sprintf("查询线上路演分类出错, Err: %v", err)
		return
	}
	firstClassify := new(models.EnglishClassify)
	secondClassify := new(models.EnglishClassify)
	for _, v := range classifyList {
		if v.ParentId == v.RootId {
			firstClassify = v
		} else if v.ParentId > 0 {
			secondClassify = v
		}
	}
	if firstClassify == nil {
		err = fmt.Errorf("一级分类不存在")
		return
	}
	if req.ClassifyIdSecond > 0 && secondClassify == nil {
		err = fmt.Errorf("二级分类不存在")
		return
	}

	if req.ClassifyIdSecond > 0 && secondClassify.ParentId != firstClassify.Id {
		err = fmt.Errorf("二级分类错误")
		return
	}

	if req.Id > 0 {
		item, e := models.GetEnglishVideoItemById(req.Id)
		if e != nil {
			if e.Error() == utils.ErrNoRow() {
				err = fmt.Errorf("路演视频不存在")
				return
			}
			err = fmt.Errorf("查询线上路演出错")
			errMsg = fmt.Sprintf("查询线上路演出错, Err: %v", e)
			return
		}

		item.ClassifyIdFirst = req.ClassifyIdFirst
		item.ClassifyNameFirst = firstClassify.ClassifyName
		item.ClassifyIdSecond = req.ClassifyIdSecond
		if secondClassify != nil {
			item.ClassifyNameSecond = secondClassify.ClassifyName
		}
		item.Title = req.Title
		item.Abstract = req.Abstract
		//item.Author = req.Author
		item.State = req.State
		item.VideoUrl = req.VideoUrl
		item.VideoCoverUrl = req.VideoCoverUrl
		item.VideoSeconds = req.VideoSeconds
		item.Overview = req.Overview
		e = models.EditEnglishVideo(item, req.Id)
		if e != nil {
			err = errors.New("更新报告失败")
			errMsg = fmt.Sprintf("更新报告失败, Err: %v", e)
			return
		}
		newReportId = item.Id
		videoCode = item.VideoCode
		return
	}
	item := new(models.EnglishVideo)
	item.ClassifyIdFirst = req.ClassifyIdFirst
	item.ClassifyNameFirst = firstClassify.ClassifyName
	item.ClassifyIdSecond = req.ClassifyIdSecond
	if secondClassify != nil {
		item.ClassifyNameSecond = secondClassify.ClassifyName
	}
	item.VideoUrl = req.VideoUrl
	item.VideoCoverUrl = req.VideoCoverUrl
	item.VideoSeconds = req.VideoSeconds
	item.Title = req.Title
	item.Abstract = req.Abstract
	//item.Author = req.Author
	item.State = req.State
	if req.State == 2 {
		item.PublishTime = time.Now()
	}
	item.Overview = req.Overview
	item.AdminId = adminInfo.AdminId
	item.AdminRealName = adminInfo.RealName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	e := models.AddEnglishVideo(item)
	if e != nil {
		err = errors.New("新增路演视频失败")
		errMsg = fmt.Sprintf("新增路演视频失败, Err: %v", e)
		return
	}
	newReportId = item.Id
	videoCode = utils.MD5(strconv.Itoa(item.Id))
	//修改唯一编码
	{
		go models.ModifyEnglishVideoCode(item.Id, videoCode)
	}
	if req.State == 2 {
		go UpdateEnglishVideoEs(newReportId, 2)
	}
	return
}
