package voice_broadcast

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/request"
	voiceResp "hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/voice_broadcast"
	"hongze/hongze_yb/models/tables/voice_section"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strconv"
	"strings"
)

// BroadcastList
// @Description 语音播报列表
// @Param page_index	query int false "页码"
// @Param page_size		query int false "每页数量"
// @Param broadcast_id	query int false "语音播报ID（分享进来的时候筛选用）"
// @Param section_id	query int false "板块ID"
// @Param author_id		query int false "作者ID（我的语音播报列表）"
// @Param mine_status	query int false "语音播报状态：0-未发布 1-已发布 2-全部（我的语音播报列表）"
// @Success 200 {object} []voiceResp.BroadcastListResp
// @failure 400 {string} string "获取失败"
// @Router /list [Post]
func BroadcastList(c *gin.Context) {
	var req request.BroadcastListReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.PageIndex == 0 {
		req.PageIndex = 1
	}
	if req.PageSize == 0 {
		req.PageSize = utils.PageSize20
	}

	userinfo := user.GetInfoByClaims(c)
	list, err := services.GetVoiceBroadcastList(req.PageIndex, req.PageSize, req.SectionId, req.BroadcastId, req.AuthorId, req.MineStatus, userinfo)
	if err != nil {
		response.FailMsg("获取语音播报列表失败，"+err.Error(), "QuestionList ErrMsg:"+err.Error(), c)
		return
	}
	isVoiceAdmin, _, err := services.GetVoiceAdminByUserInfo(userinfo)
	if err != nil && err != utils.ErrNoRow {
		response.FailMsg("获取语音管理员信息失败", "QuestionList ErrMsg:"+err.Error(), c)
		return
	}
	var resp voiceResp.BroadcastListResp
	resp.List = list
	resp.IsVoiceAdmin = isVoiceAdmin
	response.OkData("获取成功", resp, c)
}

// AddBroadcast
// @Description 新增语音播报
// @Param broadcast_name	query  string  	true  	"语音标题"
// @Param section_id		query  int  	true  	"板块ID"
// @Param section_name		query  string  	true  	"板块名称"
// @Param variety_id		query  int		true  	"品种ID"
// @Param variety_name		query  string	true  	"品种名称"
// @Param author_id			query  int		true  	"作者ID"
// @Param author			query  string  	true  	"作者名称"
// @Param Imgs				query  string  	false  	"图片,英文逗号拼接"
// @Param voice_seconds		query  string  	true	"音频时长"
// @Param voice_size		query  string  	true	"音频大小"
// @Param voice_url			query  string  	true	"音频文件地址"
// @Success 200 {string} string "发布成功"
// @failure 400 {string} string "发布失败"
// @Router /add [post]
func AddBroadcast(c *gin.Context) {
	var req request.SaveBroadcastReq
	if err := c.ShouldBind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	// 参数校验
	if req.BroadcastName == "" {
		response.Fail("请输入标题", c)
		return
	}
	if req.SectionId <= 0 || req.SectionName == "" {
		response.Fail("请选择品种", c)
		return
	}
	if req.SectionId <= 0 || req.SectionName == "" {
		response.Fail("请选择板块", c)
		return
	}
	if req.VoiceUrl == "" || req.VoiceSeconds == "" || req.VoiceSize == "" {
		response.Fail("请上传音频", c)
		return
	}
	if !strings.Contains(req.VoiceUrl, utils.ALIYUN_OSS_HOST) {
		response.Fail("音频地址有误, 请重新上传", c)
		return
	}
	if req.Imgs != "" {
		imgList := strings.Split(req.Imgs, ",")
		if len(imgList) > 5 {
			response.Fail("最多插入五张图片", c)
			return
		}
	}
	userInfo := user.GetInfoByClaims(c)
	// 新增
	resp, e := services.CreateVoiceBroadcast(req.SectionId, req.VarietyId, req.AuthorId, req.BroadcastName, req.SectionName, req.VarietyName,
		req.Author, req.VoiceSeconds, req.VoiceSize, req.VoiceUrl, req.Imgs, req.CentralArguments, userInfo)
	if e != nil {
		response.FailMsg("新增失败", e.Error(), c)
		return
	}
	response.OkData("操作成功", resp, c)
}

// EditBroadcast
// @Description 编辑语音播报
// @Param broadcast_id		query  int  	true  	"语音播报ID"
// @Param broadcast_name	query  string  	true  	"语音标题"
// @Param section_id		query  int  	true  	"板块ID"
// @Param section_name		query  string  	true  	"板块名称"
// @Param variety_id		query  int		true  	"品种ID"
// @Param variety_name		query  string	true  	"品种名称"
// @Param author_id			query  int		true  	"作者ID"
// @Param author			query  string  	true  	"作者名称"
// @Param Imgs				query  string  	false  	"图片,英文逗号拼接"
// @Param voice_seconds		query  string  	true	"音频时长"
// @Param voice_size		query  string  	true	"音频大小"
// @Param voice_url			query  string  	true	"音频文件地址"
// @Success 200 {string} string "发布成功"
// @failure 400 {string} string "发布失败"
// @Router /edit [post]
func EditBroadcast(c *gin.Context) {
	var req request.SaveBroadcastReq
	if err := c.ShouldBind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	// 参数校验
	if req.BroadcastId <= 0 {
		response.Fail("参数有误", c)
		return
	}
	if req.BroadcastName == "" {
		response.Fail("请输入标题", c)
		return
	}
	if req.SectionId <= 0 || req.SectionName == "" {
		response.Fail("请选择品种", c)
		return
	}
	if req.SectionId <= 0 || req.SectionName == "" {
		response.Fail("请选择板块", c)
		return
	}
	if req.VoiceUrl == "" || req.VoiceSeconds == "" || req.VoiceSize == "" {
		response.Fail("请上传音频", c)
		return
	}
	if !strings.Contains(req.VoiceUrl, utils.ALIYUN_OSS_HOST) {
		response.Fail("音频地址有误, 请重新上传", c)
		return
	}
	if req.Imgs != "" {
		imgList := strings.Split(req.Imgs, ",")
		if len(imgList) > 5 {
			response.Fail("最多插入五张图片", c)
			return
		}
	}
	userInfo := user.GetInfoByClaims(c)
	// 编辑
	resp, e := services.EditVoiceBroadcast(req.BroadcastId, req.SectionId, req.VarietyId, req.AuthorId, req.BroadcastName, req.SectionName, req.VarietyName,
		req.Author, req.VoiceSeconds, req.VoiceSize, req.VoiceUrl, req.Imgs, req.CentralArguments, userInfo)
	if e != nil {
		response.FailMsg("新增失败", e.Error(), c)
		return
	}
	response.OkData("操作成功", resp, c)
}

// PublishBroadcast
// @Description 发布语音播报
// @Param broadcast_id		query  int  	true  	"语音播报ID"
// @Param publish_type		query  int  	true  	"发布类型: 1-发布 2-定时发布"
// @Param pre_publish_time	query  string  	false  	"预发布时间"
// @Success 200 {string} string "发布成功"
// @failure 400 {string} string "发布失败"
// @Router /publish [post]
func PublishBroadcast(c *gin.Context) {
	var req request.PublishBroadcastReq
	if err := c.ShouldBind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	// 参数校验
	if req.BroadcastId <= 0 {
		response.Fail("参数有误", c)
		return
	}
	if req.PublishType <= 0 {
		response.Fail("请选择发布类型", c)
		return
	}
	if req.PublishType == 2 && req.PrePublishTime == "" {
		response.Fail("定时发布请选择发布时间", c)
		return
	}
	// 发布
	if e := services.PublishVoiceBroadcast(req.BroadcastId, req.PublishType, req.PrePublishTime); e != nil {
		fmt.Println("发布失败,err:" + e.Error())
		response.FailMsg("发布失败", e.Error(), c)
		return
	}
	response.Ok("操作成功", c)
}

// SectionList
// @Description 语音播报板块列表
// @Success 200 {object} []voiceResp.VarietyList
// @failure 400 {string} string "获取失败"
// @Router /section/list [get]
func SectionList(c *gin.Context) {
	sList, err := voice_section.GetVoiceSection()
	if err != nil {
		response.FailMsg("查询语音播报板块失败", "GetVoiceSection, Err:"+err.Error(), c)
	}
	vList, err := voice_section.GetVoiceVariety()
	if err != nil {
		response.FailMsg("查询语音播报板块失败", "GetVoiceSection, Err:"+err.Error(), c)
	}
	var sectionList []voiceResp.SectionList
	var varietyList []voiceResp.VarietyList
	var resp []voiceResp.VarietyList
	//var resp voiceResp.SectionListResp
	//for _, s := range sList {
	//	section := voiceResp.SectionList{
	//		SectionId:   s.SectionId,
	//		SectionName: s.SectionName,
	//		Status:      s.Status,
	//	}
	//	sectionList = append(sectionList, section)
	//}
	var newsList []*voice_section.VoiceSection
	//var bannedSectionList []*voice_section.VoiceSection

	//查找被禁用的板块ids
	var bannedIds []int
	for _, section := range sList {
		if section.Status == 0 {
			//bannedSectionList = append(bannedSectionList, section)
			bannedIds = append(bannedIds, section.SectionId)
		} else {
			newsList = append(newsList, section)
		}
	}

	//如果有被禁用的板块，去语音列表查找被禁用板块有没有语音
	var lists []*voice_broadcast.VoiceBroadcast
	if len(bannedIds) > 0 {
		lists, err = voice_section.GetVoiceSectionFromBroadcast(bannedIds)
		if err != nil {
			response.FailMsg("查询语音播报禁用板块失败", "GetVoiceSectionFromBroadcast, Err:"+err.Error(), c)
		}
	}

	//被禁用板块有语音，依然显示该板块
	if len(lists) > 0 {
		//清空切片,用新的
		newsList = newsList[0:0]
		bannedMap := make(map[int]int)
		for _, broadcast := range lists {
			bannedMap[broadcast.SectionId] = broadcast.SectionId
		}
		for _, section := range sList {
			_, ok := bannedMap[section.SectionId]
			if section.Status != 0 || ok {
				newsList = append(newsList, section)
			}
		}
	}

	for _, v := range vList {
		variety := voiceResp.VarietyList{
			VarietyId:   v.VarietyId,
			VarietyName: v.VarietyName,
		}
		varietyList = append(varietyList, variety)
	}

	for _, v := range varietyList {
		for _, s := range newsList {
			if v.VarietyId == s.VarietyId {
				section := voiceResp.SectionList{
					ImgUrl:      s.ImgUrl,
					SectionId:   s.SectionId,
					SectionName: s.SectionName,
					Status:      s.Status,
				}
				sectionList = append(sectionList, section)
			}
		}
		if len(sectionList) == 0 {
			continue
		}
		v.Children = sectionList
		resp = append(resp, v)
		sectionList = []voiceResp.SectionList{}
	}
	response.OkData("上传成功", resp, c)
}

// DelBroadcast
// @Description 删除语音播报
// @Param broadcast_id			query int false "语音播报id"
// @Success 200 {string} string "删除成功"
// @failure 400 {string} string "删除失败"
// @Router /delete [get]
func DelBroadcast(c *gin.Context) {
	sbroadcastId := c.DefaultQuery("broadcast_id", "0")
	broadcastId, err := strconv.Atoi(sbroadcastId)
	if err != nil {
		response.FailMsg("转换id失败，请输入正确的id", "strconv.Atoi, Err:"+err.Error(), c)
		return
	}
	if broadcastId <= 0 {
		response.FailMsg("参数错误", "参数有误", c)
		return
	}

	userInfo := user.GetInfoByClaims(c)
	// 是否为内部员工
	ok, _, err := user.GetAdminByUserInfo(userInfo)
	if err != nil {
		response.FailMsg("您无权操作", "获取系统用户信息失败"+err.Error(), c)
		return
	}
	if !ok {
		response.FailMsg("您无权操作", "非公司内部员工", c)
		return
	}
	var item voice_broadcast.VoiceBroadcast
	item.BroadcastId = broadcastId
	err = item.DelVoiceBroadcast()
	if err != nil {
		response.FailMsg("删除语音播报失败", "DelVoiceBroadcast, Err:"+err.Error(), c)
		return
	}

	response.Ok("删除成功", c)
}

// AddStatistics
// @Description 新增语音播报记录
// @Param file  query  string  true  "音频文件"
// @Success 200 {string} string "新增成功"
// @failure 400 {string} string "新增失败"
// @Router /statistics/add [post]
func AddStatistics(c *gin.Context) {
	var req request.AddBroadcastStatisticsReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}

	if req.BroadcastId <= 0 {
		response.Fail("参数有误", c)
	}
	userinfo := user.GetInfoByClaims(c)

	newId, err := services.AddBroadcastRecord(userinfo, req.Source, req.BroadcastId)
	if err != nil {
		response.FailMsg("新增播放记录失败", "AddStatistics ErrMsg:"+err.Error(), c)
		return
	}

	response.OkData("新增记录成功", newId, c)
}

// BroadcastDetail 获取语音播报详情
// @Tags 语音播报模块
// @Description 获取语音播报详情
// @Param broadcast_id  query  int  true  "语音播报ID"
// @Success 200 {object} voiceResp.Broadcast
// @failure 400 {string} string "获取失败"
// @Router /detail [get]
func BroadcastDetail(c *gin.Context) {
	var req request.BroadcastDetailReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.BroadcastId <= 0 {
		response.Fail("参数有误", c)
		return
	}
	userInfo := user.GetInfoByClaims(c)
	resp, e := services.GetVoiceBroadcastDetail(req.BroadcastId, userInfo)
	if e != nil {
		response.FailMsg("获取失败", "BroadcastDetail ErrMsg:"+e.Error(), c)
		return
	}
	response.OkData("获取成功", resp, c)
}

// MsgSend 语音播报消息推送
// @Tags 语音播报模块
// @Description 语音播报消息推送
// @Param broadcast_id	query  int  true  "语音播报ID"
// @Success 200 {string} string "操作成功"
// @failure 400 {string} string "操作失败"
// @Router /msg_send [post]
func MsgSend(c *gin.Context) {
	var req request.BroadcastMsgSendReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.BroadcastId <= 0 {
		response.Fail("参数有误", c)
		return
	}
	userInfo := user.GetInfoByClaims(c)
	errMsg, err := services.SendBroadcastMsg(req.BroadcastId, int(userInfo.UserID))
	if err != nil {
		response.FailMsg(errMsg, "MsgSend ErrMsg:"+err.Error(), c)
		fmt.Println("SendBroadcastMsg Err:" + err.Error())
		return
	}
	response.Ok("操作成功", c)
}

// BroadcastDetail 获取语音播报详情
// @Tags 语音播报模块
// @Description 获取语音播报详情
// @Param broadcast_id  query  int  true  "语音播报ID"
// @Success 200 {object} voiceResp.Broadcast
// @failure 400 {string} string "获取失败"
// @Router /detail [get]
func MyVoiceBroadcastListCount(c *gin.Context) {
	var req request.BroadcastListCountReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.AuthorId <= 0 {
		response.Fail("参数有误", c)
		return
	}
	resp, e := services.GetMyVoiceBroadcastListCount(req.AuthorId, req.SectionId)
	if e != nil {
		response.FailMsg("获取失败", "BroadcastDetail ErrMsg:"+e.Error(), c)
		return
	}
	response.OkData("获取成功", resp, c)
}
