package yb

import (
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
)

// 音频播报板块
type VoiceBroadcastController struct {
	controllers.BaseAuthController
}

// VoiceBroadcastList
// @Title 获取语音播报统计列表
// @Description 获取语音播报统计列表
// @Param   SectionId	query  int  false  "板块ID"
// @Param   VarietyId	query  int  false  "品种ID"
// @Param   AdminId		query  int  false  "管理员ID"
// @Param   ClickSort   query  int  false  "点击量排序:1-升序 2-降序"
// @Param   Title		query  string  false  "标题"
// @Success 200 {object} response.BroadcastStatisticsResp
// @router /voice/broadcast/list [get]
func (this *VoiceBroadcastController) VoiceBroadcastList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 筛选项-板块/品种/管理员/标题/点击量排序
	sectionId, _ := this.GetInt("SectionId")
	varietyId, _ := this.GetInt("VarietyId")
	adminId, _ := this.GetInt("AdminId")
	title := this.GetString("Title")
	clickSort, _ := this.GetInt("ClickSort")

	var pars []interface{}
	condition := ``
	if sectionId > 0 {
		condition += ` AND section_id = ?`
		pars = append(pars, sectionId)
	}
	if varietyId > 0 {
		condition += ` AND variety_id = ?`
		pars = append(pars, varietyId)
	}
	if adminId > 0 {
		// 获取对应管理员的微信用户信息
		wxUser, e := models.GetWxUserByAdminId(utils.USER_RECORD_PLATFORM_YB, adminId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取管理员微信信息失败, Err: " + e.Error()
			return
		}
		if wxUser != nil && wxUser.UserId > 0 {
			condition += ` AND author_id = ?`
			pars = append(pars, wxUser.UserId)
		} else {
			condition += ` AND author_id = 0`
		}
	}
	if title != "" {
		keywords := "%" + title + "%"
		condition += ` AND broadcast_name LIKE ?`
		pars = append(pars, keywords)
	}
	// 点击量排序: 0-发布时间降序(默认) 1-升序 2-降序
	orderRule := `publish_time DESC`
	if clickSort == 1 {
		orderRule = `visit_count ASC`
	}
	if clickSort == 2 {
		orderRule = `visit_count DESC`
	}

	// 分页
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, list, err := yb.GetVoiceBroadcastCensusPageList(startSize, pageSize, condition, orderRule, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err: " + err.Error()
		return
	}
	// 管理员信息
	listLen := len(list)
	userIdArr := make([]int, 0)
	for i := 0; i < listLen; i++ {
		userIdArr = append(userIdArr, list[i].AuthorId)
	}
	userAdminNameMap := make(map[int]string, 0)
	if len(userIdArr) > 0 {
		relationList, e := system.GetAdminWxUserRelationByWxUserIds(utils.USER_RECORD_PLATFORM_YB, userIdArr)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取管理员信息失败, Err: " + e.Error()
			return
		}
		for _, r := range relationList {
			userAdminNameMap[r.UserId] = r.RealName
		}
	}
	for _, v := range list {
		v.Author = userAdminNameMap[v.AuthorId]
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.BroadcastStatisticsResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// VoiceBroadcastDetail
// @Title 获取语音播报统计详情
// @Description 获取语音播报统计详情
// @Param   BroadcastId  query  int  true  "语音ID"
// @Success 200 {object} response.BroadcastStatisticsResp
// @router /voice/broadcast/deatil [get]
func (this *VoiceBroadcastController) VoiceBroadcastDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	broadcastId, _ := this.GetInt("BroadcastId")
	// 分页
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, list, err := yb.GetVoiceBroadcastDetailBySource(broadcastId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err: " + err.Error()
		return
	}
	// 查询用户相关的客户信息
	listLen := len(list)
	userIdArr := make([]string, 0)
	for i := 0; i < listLen; i++ {
		userIdArr = append(userIdArr, strconv.Itoa(list[i].UserId))
	}
	userIds := strings.Join(userIdArr, ",")
	userCompanyMap := make(map[int]*company.CompanyUser)
	if userIds != "" {
		companyUserList, e := company.GetFiccCompanyUserByUserIds(userIds)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取客户信息失败, Err: " + e.Error()
			return
		}
		for _, v := range companyUserList {
			userCompanyMap[int(v.UserId)] = v
		}
	}

	respList := make([]*yb.VoiceBroadcastTotal, 0)
	for _, v := range list {
		item := new(yb.VoiceBroadcastTotal)
		if u, ok := userCompanyMap[v.UserId]; ok {
			item.RealName = u.RealName
			item.CompanyName = u.CompanyName
			item.CompanyStatus = u.Status
		}
		item.VisitCount = v.VisitCount
		item.Source = v.NewSource
		item.CreateTime = v.CreateTime
		respList = append(respList, item)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.BroadcastStatisticsResp{
		List:   respList,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}