package controllers

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"strings"
	"time"
)

// GroupSendMsgController 报告
type GroupSendMsgController struct {
	BaseAuthController
}

// @Title 新增群发消息接口
// @Description 新增群发消息
// @Param	request	body models.GroupSendMsgAddReq true "type json string"
// @Success 200 {object} 发送成功
// @router /add [post]
func (this *GroupSendMsgController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.GroupSendMsgAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	switch req.JumpType {
	case 1, 2:
		if req.LinkUrl == "" {
			br.Msg = "请填写推送链接"
			return
		}
		if req.Title == "" {
			br.Msg = "请填写推送标题"
			return
		}
	case 3:
		if req.Description == "" {
			br.Msg = "请填写描述"
			return
		}
		req.Title = "纯文字"
	case 4:
		if req.ImgUrl == "" {
			br.Msg = "请上传图片"
			return
		}
		req.Title = "纯图片"
		req.Description = "这是一张图片"
		req.LinkUrl = req.ImgUrl
		//req.ImgUrl = ""
	default:
		br.Msg = "跳转类型有误"
		br.ErrMsg = "跳转类型有误"
		return
	}
	if req.Label == "" {
		br.Msg = "请选择标签"
		return
	}

	item := &models.GroupSendMsg{
		JumpType:    req.JumpType,
		LinkUrl:     req.LinkUrl,
		ImgUrl:      req.ImgUrl,
		Title:       req.Title,
		Description: req.Description,
		Label:       req.Label,
		Status:      0,
		CreateTime:  time.Now(),
	}
	err = item.Add()
	if err != nil {
		br.Msg = "发送失败"
		br.ErrMsg = "发送失败,Err:" + err.Error()
		return
	}

	//向同花顺发送信息
	//err = services.SendMsgToThs(item)
	//if err != nil {
	//	item.Status = -1
	//	item.Remark = err.Error()
	//	_ = item.Update([]string{"Status", "Remark"})
	//	br.Msg = "发送失败"
	//	br.ErrMsg = "发送失败,Err:" + err.Error()
	//	return
	//}

	item.Status = 1
	_ = item.Update([]string{"Status"})

	br.Ret = 200
	br.Success = true
	br.Msg = "发送成功"
}

// GetLabelList
// @Title 获取标签
// @Description 获取标签接口
// @Success 200 {object} []string
// @router /label_list [get]
func (this *GroupSendMsgController) GetLabelList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	configName := `ths_send_label`
	conf, err := company.GetConfigDetailByCode(configName)
	if err != nil {
		fmt.Println("GetConfigDetailByCode Err:" + err.Error())
	}

	labelStr := conf.ConfigValue
	labelList := strings.Split(labelStr, ",")

	br.Ret = 200
	br.Success = true
	br.Msg = "发送成功"
	br.Data = labelList
}
