package services

import (
	"bytes"
	"encoding/json"
	"fmt"
	"hongze/hongze_task/models"
	"hongze/hongze_task/utils"
	"io/ioutil"
	"net/http"
	"time"
)

func SendWxMsgWithFrequency(first, keyword1, keyword2, remark string, openIdList []*models.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info("发送模版消息失败,Err:%s", err.Error())
		}
		fmt.Println("line 21", err, msg)
	}()
	utils.FileLog.Info("%s", "services SendMsg")
	accessToken, err := models.GetWxAccessToken()
	if err != nil {
		msg = "GetWxAccessToken Err:" + err.Error()
		return
	}
	if accessToken == "" {
		msg = "accessToken is empty"
		return
	}

	sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
	templateId := utils.TemplateId
	//if true{
	sendMap := make(map[string]interface{})
	sendData := make(map[string]interface{})

	sendMap["template_id"] = templateId

	//redirectUrl:="report.hzinsights.com/#/allindex/"+strconv.Itoa(v.ResearchReportId)+"/"+v.ReportType;

	//sendMap["url"]=redirectUrl
	sendData["first"] = map[string]interface{}{"value": first, "color": "#173177"}
	sendData["keyword1"] = map[string]interface{}{"value": keyword1, "color": "#173177"}
	sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
	sendData["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
	sendMap["data"] = sendData
	WxSendTemplateMsg(sendUrl, sendMap, openIdList)
	return
}

func WxSendTemplateMsg(sendUrl string, sendMap map[string]interface{}, items []*models.OpenIdList) (err error) {
	for _, v := range items {
		sendMap["touser"] = v.OpenId
		data, err := json.Marshal(sendMap)
		if err != nil {
			fmt.Println("SendTemplateMsgOne Marshal Err:", err.Error())
			return err
		}
		utils.FileLog.Info("One SendData:%s", string(data))
		err = SendTemplateMsg(sendUrl, data)
		if err != nil {
			fmt.Println("send err:", err.Error())
			return err
		}
	}
	return
}

func SendTemplateMsg(sendUrl string, data []byte) (err error) {
	client := http.Client{}
	resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(data))
	if err != nil {
		return
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	utils.FileLog.Info("SendResult:%s", string(body))
	var templateResponse models.SendTemplateResponse
	err = json.Unmarshal(body, &templateResponse)
	if err != nil {
		return err
	}
	return
}


//到期提醒模板消息
func SendWxMsgWithCompanyRemind(first,keyword1,keyword2,remark string,openIdList []*models.OpenIdList)(err error) {
	var msg string
	defer func() {
		if err!=nil {
			go utils.SendEmail("发送模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			utils.FileLog.Info("发送模版消息失败,Err:%s",err.Error())
		}
	}()
	utils.FileLog.Info("%s","services SendMsg")
	accessToken,err:=models.GetWxAccessToken()
	if err!=nil {
		msg="GetWxAccessToken Err:"+err.Error()
		return
	}
	if accessToken ==""{
		msg="accessToken is empty"
		return
	}

	sendUrl:= "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken
	sendMap:=make(map[string]interface{})
	sendData:=make(map[string]interface{})

	sendMap["template_id"]=utils.RemindTemplateId
	sendData["first"]=map[string]interface{}{"value":first,"color":"#173177"}
	sendData["productname"]=map[string]interface{}{"value":keyword1,"color":"#173177"}
	sendData["date"]=map[string]interface{}{"value":keyword2,"color":"#173177"}
	sendData["remark"]=map[string]interface{}{"value":remark,"color":"#173177"}
	sendMap["data"]=sendData
	WxSendTemplateMsg(sendUrl,sendMap,openIdList)
	return
}
