package public_api

import (
	"encoding/json"
	"errors"
	"fmt"
	"eta/eta_api/models"
	"eta/eta_api/services/alarm_msg"
	"eta/eta_api/utils"
	"io/ioutil"
	"net/http"
	"strings"
)

// SendTemplateMsg 发送微信模板消息
func SendTemplateMsg(postData string) (err error) {
	_, err = post(utils.SendWxTemplateMsgUrl, postData)
	if err != nil {
		alarm_msg.SendAlarmMsg("SendTemplateMsg http.NewRequest Err:"+err.Error(), 1)
		return
	}
	return
}

// ReportChapterReq 报告章节id
type ReportChapterReq struct {
	ReportChapterId int `description:"报告章节ID"`
}

// HandleVideoDecibel 处理音频
func HandleVideoDecibel(reportChapterId int) (err error) {
	if utils.HandleVideoDecibelUrl == `` {
		// 处理音频的地址未配置的话，直接返回
		return
	}
	postData := ReportChapterReq{
		ReportChapterId: reportChapterId,
	}
	postDataByte, err := json.Marshal(postData)
	if err != nil {
		alarm_msg.SendAlarmMsg("HandleVideoDecibel json.Marshal Err:"+err.Error(), 1)
		return err
	}
	_, err = post(utils.HandleVideoDecibelUrl, string(postDataByte))
	if err != nil {
		alarm_msg.SendAlarmMsg("HandleVideoDecibel json.Marshal Err:"+err.Error(), 1)
		return err
	}
	return
}

type BaseResponse struct {
	Ret         int
	Msg         string
	ErrMsg      string
	ErrCode     string
	Data        interface{}
	Success     bool `description:"true 执行成功，false 执行失败"`
	IsSendEmail bool `json:"-" description:"true 发送邮件，false 不发送邮件"`
	IsAddLog    bool `json:"-" description:"true 新增操作日志，false 不新增操作日志" `
}

func post(postUrl, postData string) (result *models.BaseResponse, err error) {
	body := ioutil.NopCloser(strings.NewReader(postData))
	client := &http.Client{}
	req, err := http.NewRequest("POST", postUrl, body)
	if err != nil {
		alarm_msg.SendAlarmMsg("post public_api http.NewRequest Err:"+err.Error(), 1)
		return
	}
	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", utils.SendTemplateMsgAuthorization)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("http client.Do Err:" + err.Error())
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	result = new(models.BaseResponse)
	err = json.Unmarshal(b, &result)
	if err != nil {
		return
	}
	if result.Ret != 200 {
		err = errors.New(string(b))
	}
	return
}
