package report

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/models/eta"
	"eta/eta_mini_ht_api/models/ht"
	"fmt"
	"html"
	"sync"
	"time"
)

const (
	SmartReport = 2
)

type ETAReportDTO struct {
	Title            string             `json:"title"`
	Abstract         string             `json:"abstract"`
	Author           string             `json:"author"`
	PublishTime      string             `json:"publishTime"`
	Content          string             `json:"content"`
	ReportLayout     int                `json:"reportLayout"`
	VideoUrl         string             `json:"videoUrl"`
	VideoName        string             `json:"videoName"`
	VideoPlaySeconds string             `json:"videoPlaySeconds"`
	HeadResource     SmartResourceDTO   `json:"headResource"`
	EndResource      SmartResourceDTO   `json:"endResource"`
	HasChapter       bool               `json:"hasChapter"`
	NeedSplice       bool               `json:"needSplice"`
	SmartReport      bool               `json:"smartReport"`
	Chapters         []ReportChapterDTO `json:"chapters"`
}

type ReportChapterDTO struct {
	Title            string `json:"title"`
	Content          string `json:"content"`
	VideoURL         string `json:"videoURL"`
	VideoName        string `json:"videoName"`
	VideoPlaySeconds string `json:"videoPlaySeconds"`
	VideoSize        string `json:"videoSize"`
}

type SmartResourceDTO struct {
	ImgURL string `json:"imgURL"`
	Style  string `json:"style"`
}

func GetETAReportIdsByPermissionIds(permissionIds []int) (ids []int, err error) {
	classifyIds, err := GetClassifyIdsByPermissionIds(permissionIds)
	if err != nil {
		logger.Error("品种获取研报分类列表失败:%v", err)
		return
	}
	return eta.GetETAReportIdsByClassifyIds(classifyIds)
}

func GetHtReport(id int) (pdf string, err error) {
	return ht.GetPDFUrl(id)
}
func GetETAReport(id int) (detail ETAReportDTO, err error) {
	report, err := eta.GetETAReportById(id)
	if err != nil {
		logger.Error("获取ETA研报信息失败:%v", err)
	}
	var wg sync.WaitGroup
	detail = convertToETAReportDTO(report)
	errChan := make(chan error, 3)
	if report.HasChapter {
		wg.Add(1)
		go func(detail *ETAReportDTO) {
			defer wg.Done()
			list, chapterErr := eta.GetChaptersByReportId(report.ID)
			if chapterErr != nil {
				errChan <- fmt.Errorf("获取章节信息失败:%v", chapterErr)
			}
			detail.Chapters = convertToReportChapterDTO(list)
		}(&detail)
	}
	if report.ReportLayout == SmartReport {
		if report.HeadResourceId != 0 {
			wg.Add(1)
			go func(id int, detail *ETAReportDTO) {
				defer wg.Done()
				resource, resourceErr := eta.GetSmartReportResource(id)
				if resourceErr != nil {
					errChan <- fmt.Errorf("获取智能研报资源失败:%v", resourceErr)
				}
				detail.HeadResource = convertToSmartResourceDTO(resource)
			}(report.HeadResourceId, &detail)
		}
		if report.EndResourceId != 0 {
			wg.Add(1)
			go func(id int, detail *ETAReportDTO) {
				defer wg.Done()
				resource, resourceErr := eta.GetSmartReportResource(id)
				if resourceErr != nil {
					errChan <- fmt.Errorf("获取智能研报资源失败:%v", resourceErr)
				}
				detail.EndResource = convertToSmartResourceDTO(resource)
			}(report.EndResourceId, &detail)
		}
	}
	wg.Wait()
	close(errChan)
	for err = range errChan {
		logger.Error("%v", err)
	}
	return
}
func convertToSmartResourceDTO(resource eta.SmartReportResource) (dto SmartResourceDTO) {
	return SmartResourceDTO{
		ImgURL: resource.ImgURL,
		Style:  resource.Style,
	}
}
func convertToETAReportDTO(report eta.ETAReport) (dto ETAReportDTO) {
	dto = ETAReportDTO{
		Title:            report.Title,
		Abstract:         report.Abstract,
		Author:           report.Author,
		PublishTime:      report.PublishTime.Format(time.DateTime),
		Content:          html.UnescapeString(report.Content),
		ReportLayout:     report.ReportLayout,
		VideoUrl:         report.VideoUrl,
		VideoName:        report.VideoName,
		VideoPlaySeconds: report.VideoPlaySeconds,
		HasChapter:       report.HasChapter,
		NeedSplice:       report.NeedSplice,
		SmartReport:      report.ReportLayout == SmartReport,
	}
	//if dto.SmartReport {
	//	dto.Content = ""
	//}
	//publishDate, err := time.Parse(time.DateTime, dto.PublishTime)
	//if err == nil {
	//	dto.PublishTime = publishDate.Format(time.DateOnly)
	//}
	return
}
func convertToReportChapterDTO(chapters []eta.ReportChapter) (dtoList []ReportChapterDTO) {
	for _, chapter := range chapters {
		dto := ReportChapterDTO{
			Title:            chapter.Title,
			Content:          html.UnescapeString(chapter.Content),
			VideoURL:         chapter.VideoURL,
			VideoName:        chapter.VideoName,
			VideoPlaySeconds: chapter.VideoPlaySeconds,
			VideoSize:        chapter.VideoSize,
		}
		dtoList = append(dtoList, dto)
	}
	return
}
