package controllers

import (
	"archive/zip"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/file"
	"github.com/rdlucklib/rdluck_tools/http"
	"eta/eta_api/models"
	"eta/eta_api/services"
	"eta/eta_api/utils"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

// VoiceController 音频
type VoiceController struct {
	BaseAuthController
}

// Upload
// @Title 音频上传
// @Description 音频上传接口
// @Param   file   query   file  true       "文件"
// @Param   ReportId   query   int  true       "报告ID"
// @Success Ret=200 上传成功
// @router /upload [post]
func (this *VoiceController) Upload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	f, h, err := this.GetFile("file")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	reportId, err := this.GetInt("ReportId")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	report, err := models.GetReportItemById(reportId)
	if err != nil {
		br.Msg = "获取报告信息失败"
		br.ErrMsg = "获取报告信息失败,Err:" + err.Error()
		return
	}

	ext := path.Ext(h.Filename)
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
	err = os.MkdirAll(uploadDir, 777)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ext
	fpath := uploadDir + "/" + fileName
	defer f.Close() //关闭上传文件
	err = this.SaveToFile("file", fpath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}
	//上传到阿里云
	resourceUrl, err := services.UploadAudioAliyun(fileName, fpath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}
	defer func() {
		os.Remove(fpath)
	}()
	item := new(models.Resource)
	item.ResourceUrl = resourceUrl
	item.ResourceType = 2
	item.CreateTime = time.Now()
	newId, err := models.AddResource(item)
	if err != nil {
		br.Msg = "资源上传失败"
		br.ErrMsg = "资源上传失败,Err:" + err.Error()
		return
	}
	playSeconds, err := utils.GetVideoPlaySeconds(fpath)
	if err != nil {
		br.Msg = "获取音频时间失败"
		br.ErrMsg = "获取音频时间失败,Err:" + err.Error()
		return
	}
	createTime := report.CreateTime.Format("0102")
	videoName := report.Title + "(" + createTime + ")"

	fileBody, err := ioutil.ReadFile(fpath)
	videoSize := len(fileBody)
	sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
	sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)

	err = models.ModifyReportVideo(reportId, resourceUrl, videoName, sizeStr, playSeconds)
	if err != nil {
		br.Msg = "上传失败"
		br.ErrMsg = "上传失败，Err:" + err.Error()
		return
	}
	resp := new(models.ResourceResp)
	resp.Id = newId
	resp.ResourceUrl = resourceUrl
	br.Msg = "上传成功"
	br.Ret = 200
	br.Success = true
	br.Data = resp
	return
}

// VoiceCommonController 音频
type VoiceCommonController struct {
	BaseCommonController
}

// Download
// @Title 音频下载
// @Description 音频下载接口
// @Param   ReportId   query   int  true       "报告ID"
// @Success Ret=200 下载成功
// @router /download [get]
func (this *VoiceCommonController) Download() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	reportId, err := this.GetInt("ReportId")
	if err != nil {
		br.Msg = "参数错误"
		br.ErrMsg = "获取，ReportId，Err:" + err.Error()
		return
	}
	report, err := models.GetReportById(reportId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		return
	}
	savePath := time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandString(5) + ".mp3"
	fileBody, err := http.Get(report.VideoUrl)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		return
	}
	err = file.SaveFile(fileBody, savePath)
	if err != nil {
		br.Msg = "保存信息失败"
		br.ErrMsg = "保存信息失败，Err:" + err.Error()
		return
	}
	fileName := report.VideoName + ".mp3"
	this.Ctx.Output.Download(savePath, fileName)
	defer func() {
		os.Remove(savePath)
	}()
	br.Ret = 200
	br.Msg = "下载成功"
	br.Success = true
	return
}

// ReportChapterDownload
// @Title 报告章节列表音频下载
// @Description 音频下载接口
// @Param   ChapterIds  query  string  true  "章节IDs"
// @Success Ret=200 下载成功
// @router /report/download [get]
func (this *VoiceCommonController) ReportChapterDownload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	strChapterIds := this.GetString("ChapterIds")
	if strChapterIds == "" {
		br.Msg = "参数错误"
		return
	}
	chapterIds := make([]int, 0)
	chapterIdArr := strings.Split(strChapterIds, ",")
	for _, v := range chapterIdArr {
		id, e := strconv.Atoi(v)
		if e != nil {
			br.Msg = "参数有误"
			br.ErrMsg = "章节ID有误, Err: " + e.Error()
			return
		}
		chapterIds = append(chapterIds, id)
	}
	if len(chapterIds) == 0 {
		br.Msg = "参数有误"
		return
	}

	videoList, err := models.GetReportChapterVideoListByChapterIds(chapterIds)
	if err != nil {
		br.Msg = "获取音频列表失败"
		br.ErrMsg = "获取音频列表失败, Err: " + err.Error()
		return
	}

	if len(videoList) > 0 {
		reportId := videoList[0].ReportId
		reportInfo, err := models.GetReportById(reportId)
		if err != nil {
			br.Msg = "报告信息有误"
			br.ErrMsg = "获取报告信息失败, Err: " + err.Error()
			return
		}

		// 创建zip
		zipName := time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandString(5) + ".zip"
		savePath := zipName
		zipFile, err := os.Create(zipName)
		if err != nil {
			return
		}
		zipWriter := zip.NewWriter(zipFile)
		// 生成zip过程中报错关闭
		defer func() {
			if err != nil {
				zipWriter.Close()
				zipFile.Close()
			}
			os.Remove(savePath)
		}()

		// 获取音频,写入zip
		for i := 0; i < len(videoList); i++ {
			item := videoList[i]
			if item.VideoName == "" || item.VideoUrl == "" {
				continue
			}
			// 音频文件后缀
			ext := path.Ext(item.VideoUrl)
			ioWriter, err := zipWriter.Create(fmt.Sprintf("%s%s", item.VideoName, ext))
			if err != nil {
				if os.IsPermission(err) {
					fmt.Println("权限不足: ", err)
					return
				}
				return
			}

			var content []byte
			content, err = http.Get(item.VideoUrl)
			if err != nil {
				content = []byte("")
			}

			ioWriter.Write(content)
		}
		// 生成zip后关闭,否则下载文件会损坏
		zipWriter.Close()
		zipFile.Close()

		this.Ctx.Output.Download(savePath, fmt.Sprintf("%s.zip", reportInfo.Title))
	}

	br.Ret = 200
	br.Msg = "下载成功"
	br.Success = true
	return
}
