package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"eta/eta_mini_crm_ht/services"
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

type MessageController struct {
	BaseAuthController
}

// ReportList
// @Title 研报列表
// @Description pdf研报列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyIds   query   string  true       "二级分类id,可多选用英文,隔开"
// @Param   KeyWord   query   string  true       "报告标题/创建人"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} models.ReportAuthorResp
// @router /reportList [get]
func (this *MessageController) ReportList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	permissionIds := this.GetString("PermissionIds")
	analystNames := this.GetString("AnalystNames")
	sortType := this.GetString("SortType")
	KeyWord := this.GetString("KeyWord")
	var permissionCondition string
	var condition string
	var pars []interface{}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	if KeyWord != "" {
		condition += " AND title like '%" + KeyWord + "%'"
	}
	var permissionPars []interface{}
	var classifyPars []interface{}
	if permissionIds != "" {
		permissionArr := strings.Split(permissionIds, ",")
		for _, permissionId := range permissionArr {
			perId, _ := strconv.Atoi(permissionId)
			permissionPars = append(permissionPars, perId)
		}
		permissionCondition += " AND chart_permission_id in (" + utils.GetOrmReplaceHolder(len(permissionPars)) + ")"
		classifyIds, err := models.GetClassifyIdsByPermissionIds(permissionCondition, permissionPars)
		if err != nil {
			br.Msg = "获取报告列表失败"
			br.ErrMsg = "eta获取品种信息失败，Err:" + err.Error()
			return
		}
		classifyCondition := " AND COALESCE(NULLIF(classify_id_third,0),NULLIF(classify_id_second,0),classify_id_first) in (" + utils.GetOrmReplaceHolder(len(classifyIds)) + ")"
		classifyPars = append(classifyPars, classifyIds)
		var ids []int
		ids, _ = models.GetETAReportIdsByCondition(classifyCondition, classifyPars)
		if err != nil {
			br.Msg = "获取报告列表失败"
			br.ErrMsg = "获取报告表ids失败，Err:" + err.Error()
			return
		}
		condition += " AND id in (" + utils.GetOrmReplaceHolder(len(ids)) + ")  And source ='ETA'"
		pars = append(pars, ids)
	}
	if analystNames != "" {
		analystNameArr := strings.Split(analystNames, ",")
		condition += " AND author in (" + utils.GetOrmReplaceHolder(len(analystNameArr)) + ")"
		pars = append(pars, analystNameArr)
	}

	sortCondition := " ORDER BY published_time "
	if sortType == "" {
		sortType = "DESC"
	}
	sortCondition = sortCondition + sortType
	total, err := models.GetReportCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "获取报告列表失败"
		br.ErrMsg = "获取报告列表统计失败，Err:" + err.Error()
		return
	}

	startSize := utils.StartIndex(currentIndex, pageSize)
	reportList, err := models.GetReportByCondition(condition, sortCondition, pars, startSize, pageSize)

	if err != nil {
		br.Msg = "获取报告列表失败"
		br.ErrMsg = "获取报告列表失败，Err:" + err.Error()
		return
	}
	var reportViewList []*models.ReportView
	for _, report := range reportList {
		reportView := report.ToView()
		reportViewList = append(reportViewList, reportView)
	}
	for _, report := range reportViewList {
		var classifyId int
		classifyId, err = models.GetETAReportById(report.OrgId)
		if err != nil {
			br.Msg = "获取报告列表失败"
			br.ErrMsg = "获取eta报告失败，Err:" + err.Error()
			return
		}
		var list []int
		list, err = models.GetByPermissionIdsByClassifyId(classifyId)
		if err != nil {
			br.Msg = "获取报告列表失败"
			br.ErrMsg = "获取eta品种信息失败，Err:" + err.Error()
			return
		}
		var names []string
		names, err = models.GetPermissionNames(list)
		if err != nil {
			br.Msg = "获取报告列表失败"
			br.ErrMsg = "获取eta品种信息失败，Err:" + err.Error()
			return
		}
		report.PermissionNames = strings.Join(names, ",")
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.ReportListResp)
	resp.List = reportViewList
	resp.Paging = page

	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "获取成功"
}

// AudioList
// @Title 研报列表
// @Description pdf研报列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyIds   query   string  true       "二级分类id,可多选用英文,隔开"
// @Param   KeyWord   query   string  true       "报告标题/创建人"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} models.ReportAuthorResp
// @router /audioList [get]
func (this *MessageController) AudioList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	permissionIds := this.GetString("PermissionIds")
	analystIds := this.GetString("AnalystIds")
	sortType := this.GetString("SortType")
	KeyWord := this.GetString("KeyWord")
	var permissionCondition string
	var condition string
	var pars []interface{}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	if KeyWord != "" {
		condition += " AND media_name like '%" + KeyWord + "%'"
	}
	var permissionPars []interface{}
	if permissionIds != "" {
		permissionArr := strings.Split(permissionIds, ",")
		for _, permissionId := range permissionArr {
			perId, _ := strconv.Atoi(permissionId)
			permissionPars = append(permissionPars, perId)
		}
		permissionCondition += " AND permission_id in (" + utils.GetOrmReplaceHolder(len(permissionPars)) + ")"
		ids, err := models.GetMappingsByCondition(permissionCondition, permissionPars)
		if err != nil {
			condition += " AND id in (" + utils.GetOrmReplaceHolder(len(ids)) + ")"
			pars = append(pars, ids)
		}
	}

	if analystIds != "" {
		analystIdArr := strings.Split(analystIds, ",")
		var authorIds []int
		for _, analystId := range analystIdArr {
			id, _ := strconv.Atoi(analystId)
			authorIds = append(authorIds, id)
		}
		condition += " AND author_id in (" + utils.GetOrmReplaceHolder(len(authorIds)) + ")"
		pars = append(pars, authorIds)
	}
	sortCondition := " ORDER BY published_time "
	if sortType == "" {
		sortType = "DESC"
	}
	sortCondition = sortCondition + sortType
	total, err := models.GetMediaCountByCondition(models.Audio, condition, pars)
	if err != nil {
		br.Msg = "获取研报列表失败"
		br.ErrMsg = "获取研报列表统计失败，Err:" + err.Error()
		return
	}

	startSize := utils.StartIndex(currentIndex, pageSize)
	reportList, err := models.GetMediaByCondition(models.Audio, condition, sortCondition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取研报列表失败"
		br.ErrMsg = "获取研报列表失败，Err:" + err.Error()
		return
	}
	var reportViewList []*models.MessageMedia
	for _, report := range reportList {
		reportView := report.ToMessageView()
		reportViewList = append(reportViewList, reportView)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.MessageMediaListResp)
	resp.List = reportViewList
	resp.Paging = page

	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "获取成功"
}

// VideoList
// @Title 研报列表
// @Description pdf研报列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyIds   query   string  true       "二级分类id,可多选用英文,隔开"
// @Param   KeyWord   query   string  true       "报告标题/创建人"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} models.ReportAuthorResp
// @router /videoList [get]
func (this *MessageController) VideoList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	permissionIds := this.GetString("PermissionIds")
	analystIds := this.GetString("AnalystIds")
	sortType := this.GetString("SortType")
	KeyWord := this.GetString("KeyWord")
	var permissionCondition string
	var condition string
	var pars []interface{}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	if KeyWord != "" {
		condition += " AND media_name like '%" + KeyWord + "%'"
	}
	var permissionPars []interface{}
	if permissionIds != "" {
		permissionArr := strings.Split(permissionIds, ",")
		for _, permissionId := range permissionArr {
			perId, _ := strconv.Atoi(permissionId)
			permissionPars = append(permissionPars, perId)
		}
		permissionCondition += " AND permission_id in (" + utils.GetOrmReplaceHolder(len(permissionPars)) + ")"
		ids, err := models.GetMappingsByCondition(permissionCondition, permissionPars)
		if err != nil {
			condition += " AND id in (" + utils.GetOrmReplaceHolder(len(ids)) + ")"
			pars = append(pars, ids)
		}
	}

	if analystIds != "" {
		analystIdArr := strings.Split(analystIds, ",")
		var authorIds []int
		for _, analystId := range analystIdArr {
			id, _ := strconv.Atoi(analystId)
			authorIds = append(authorIds, id)
		}
		condition += " AND author_id in (" + utils.GetOrmReplaceHolder(len(authorIds)) + ")"
		pars = append(pars, authorIds)
	}
	sortCondition := " ORDER BY published_time "
	if sortType == "" {
		sortType = "DESC"
	}
	sortCondition = sortCondition + sortType
	total, err := models.GetMediaCountByCondition(models.Video, condition, pars)
	if err != nil {
		br.Msg = "获取视频列表失败"
		br.ErrMsg = "获取视频列表统计失败，Err:" + err.Error()
		return
	}

	startSize := utils.StartIndex(currentIndex, pageSize)
	List, err := models.GetMediaByCondition(models.Video, condition, sortCondition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取视频列表失败"
		br.ErrMsg = "获取视频列表失败，Err:" + err.Error()
		return
	}
	var reportViewList []*models.MessageMedia
	for _, report := range List {
		reportView := report.ToMessageView()
		reportViewList = append(reportViewList, reportView)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.MessageMediaListResp)
	resp.List = reportViewList
	resp.Paging = page

	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "获取成功"
}

const (
	Report string = "report"
	Audio  string = "audio"
	Video  string = "video"
)

// SendTemplateMsg
// @Title 研报列表
// @Description pdf研报列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyIds   query   string  true       "二级分类id,可多选用英文,隔开"
// @Param   KeyWord   query   string  true       "报告标题/创建人"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} models.ReportAuthorResp
// @router /sendTemplateMsg [post]
func (this *MessageController) SendTemplateMsg() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.WxMessageReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if req.DataId <= 0 {
		br.Msg = "DataId为空"
		return
	}
	if req.DataType == "" {
		br.Msg = "DataType为空"
		return
	}
	sendData := make(map[string]interface{})
	if req.DataType == Report {
		var report *models.Report
		report, err = models.GetReportById(req.DataId)
		if err != nil {
			br.Msg = "发送模版消息失败"
			br.ErrMsg = "获取报告失败"
			return
		}

		switch report.Source {
		case "ETA":
			var classifyId int
			var ids []int
			var names []string
			classifyId, err = models.GetETAReportIdByClassifyId(report.OrgId)
			ids, err = models.GetByPermissionIdsByClassifyId(classifyId)
			if err != nil {
				br.Msg = "发送模版消息失败"
				br.ErrMsg = fmt.Sprintf("获取eta品种信息失败，Err:%v", err)
				return
			}
			names, err = models.GetPermissionNames(ids)
			if err != nil {
				br.Msg = "发送模版消息失败"
				br.ErrMsg = fmt.Sprintf("获取eta品种信息失败，Err:%v", err)
				return
			}
			sendData["keyword1"] = map[string]interface{}{"value": strings.Join(names, ","), "color": "#173177"}
		case "HT":
			sendData["keyword1"] = map[string]interface{}{"value": "ht", "color": "#173177"}
		default:
			sendData["keyword1"] = map[string]interface{}{"value": "", "color": "#173177"}
		}
		sendData["keyword2"] = map[string]interface{}{"value": report.Title, "color": "#173177"}
		sendData["keyword3"] = map[string]interface{}{"value": report.PublishedTime, "color": "#173177"}
		sendData["keyword4"] = map[string]interface{}{"value": report.Abstract, "color": "#173177"}
		err = report.UpdateSendStatus(models.SEND)
		if err != nil {
			br.Msg = "发送模版消息失败"
			br.ErrMsg = fmt.Sprintf("更新发送状态失败，Err:%v", err)
			return
		}
	}
	if req.DataType == Audio {
		var media *models.Media
		media, err = models.GetMediaById(models.Audio, req.DataId)
		if err != nil {
			br.Msg = "发送模版消息失败"
			br.ErrMsg = "获取音频失败"
			return
		}

		sendData["keyword1"] = map[string]interface{}{"value": "线上音频", "color": "#173177"}
		sendData["keyword2"] = map[string]interface{}{"value": media.MediaName, "color": "#173177"}
		sendData["keyword3"] = map[string]interface{}{"value": media.CreatedTime.Format(time.DateTime), "color": "#173177"}
		err = media.UpdateSendStatus(models.SEND)
		if err != nil {
			br.Msg = "发送模版消息失败"
			br.ErrMsg = fmt.Sprintf("更新发送状态失败，Err:%v", err)
			return
		}
	}
	if req.DataType == Video {
		var media *models.Media
		media, err = models.GetMediaById(models.Video, req.DataId)
		if err != nil {
			br.Msg = "发送模版消息失败"
			br.ErrMsg = "获取音频失败"
			return
		}

		sendData["keyword1"] = map[string]interface{}{"value": "线上视频", "color": "#173177"}
		sendData["keyword2"] = map[string]interface{}{"value": media.MediaName, "color": "#173177"}
		sendData["keyword3"] = map[string]interface{}{"value": media.CreatedTime.Format(time.DateTime), "color": "#173177"}
		err = media.UpdateSendStatus(models.SEND)
		if err != nil {
			br.Msg = "发送模版消息失败"
			br.ErrMsg = fmt.Sprintf("更新发送状态失败，Err:%v", err)
			return
		}
	}
	users, err := models.GetTemplateUserList()
	if err != nil {
		br.Msg = "发送模版消息失败"
		br.ErrMsg = "获取用户OPENID失败，Err:" + err.Error()
		return
	}
	var openIds []*services.OpenIdList
	for _, user := range users {
		openId := &services.OpenIdList{
			OpenId: user.OpenId,
			UserId: user.Id,
		}
		openIds = append(openIds, openId)
	}
	err = services.SendMultiTemplateMsg(sendData, openIds, req.DataId, req.DataType)
	if err != nil {
		if req.DataType == Report {
			var report *models.Report
			report, err = models.GetReportById(req.DataId)
			if err != nil {
				return
			}
			_ = report.UpdateSendStatus(models.UNSEND)
		}
		if req.DataType == Audio {
			var media *models.Media
			media, err = models.GetMediaById(models.Audio, req.DataId)
			if err != nil {
				return
			}
			_ = media.UpdateSendStatus(models.UNSEND)
		}
		if req.DataType == Video {
			var media *models.Media
			media, err = models.GetMediaById(models.Video, req.DataId)
			if err != nil {
				return
			}
			_ = media.UpdateSendStatus(models.SEND)
		}
		br.Msg = "发送模板消息失败"
		br.ErrMsg = "发送模板消息失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Data = nil
	br.Msg = "发送成功"
}
