package services

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// 访谈申请
func SendInterviewApplyTemplateMsg(realName, companyName, mobile, articleTitle string, itemOpenid *models.OpenIdList) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendEmail("发送模版消息失败"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
			go utils.SendAlarmMsg(fmt.Sprint("访谈申请模板消息推送消息失败,手机号", mobile, "公司：", companyName, "手机号：", mobile), 2)
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()

	keyword1 := realName + "【" + companyName + "】"
	first := "您有一条新的访谈申请，请及时处理。"
	keyword2 := mobile
	keyword3 := time.Now().Format(utils.FormatDateTime)
	keyword4 := articleTitle

	openIdArr := make([]string, 0)
	openIdArr = append(openIdArr, itemOpenid.OpenId)

	redirectUrl := ""
	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.TemplateId = utils.WxMsgTemplateIdApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	//sendInfo.Resource =
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	fmt.Println("send end")
	return
}

// 访谈申请取消
func SendInterviewApplyCancelTemplateMsg(realName, companyName, mobile, articleTitle string, itemOpenid *models.OpenIdList) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("访谈申请取消模板消息推送消息失败,手机号", mobile, "公司：", companyName, "手机号：", mobile, ";Err:"+err.Error()), 2)
		}
	}()

	keyword1 := articleTitle
	keyword2 := time.Now().Format(utils.FormatDateTime)

	openIdArr := make([]string, 0)
	openIdArr = append(openIdArr, itemOpenid.OpenId)
	redirectUrl := ""
	sendInfo := new(SendWxTemplate)

	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2

	sendInfo.TemplateId = utils.WxMsgTemplateIdApplyCancelXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	//sendInfo.Resource =
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

// 权限申请
func SendPermissionApplyTemplateMsg(realName, companyName, mobile, applyMethod, redirectUrl string, user *models.WxUserItem) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("权限申请模板消息推送消息失败,手机号", mobile, "公司：", companyName, ";Err:"+err.Error()), 2)
		}
	}()
	companyId := user.CompanyId
	//权益客户
	raiCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil {
		err = errors.New("GetCompanyProductCount, Err: " + e.Error())
		return
	}
	var mobileOpenid string
	if raiCount == 0 {
		mobileOpenid = utils.WxMsgTemplateIdAskMsgMobilePublic
	} else {
		sealldetail, e := models.GetRaiSellerByCompanyId(companyId)
		if e != nil {
			err = errors.New("GetRaiSellerByCompanyId, Err: " + e.Error())
			return
		}

		//如果有共享销售给共享销售也推模版消息
		if sealldetail.ShareSellerId > 0 {
			adminShare, e := models.GetSellerByAdminId(sealldetail.ShareSellerId)
			if e != nil {
				err = errors.New("GetSellerByAdminId, Err: " + e.Error())
				return
			}
			listSellerMobile, e := models.GetCygxSellerMobileMap()
			if e != nil {
				err = errors.New("GetCygxSellerMobileMap, Err: " + e.Error())
				return
			}
			//mapMobile := make(map[string]string)
			for _, vm := range listSellerMobile {
				if adminShare.Mobile == vm.ServerMobile {
					adminShare.Mobile = vm.Mobile
				}
			}
			mobileOpenid = sealldetail.Mobile + "," + adminShare.Mobile
		} else {
			mobileOpenid = sealldetail.Mobile
		}
	}

	openIdList, e := models.GetWxOpenIdByMobileList(mobileOpenid)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, 0)

	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//var redirectUrl string
	detail, e := models.GetCygxApplyRecordByMobile(mobile)
	if e != nil {
		err = errors.New("GetCygxApplyRecordByMobile" + e.Error())
		return
	}
	//如果是潜在客户就推送可查看详情的模版消息
	if detail.ApplyMethod == 2 {
		redirectUrl = utils.WX_MSG_PATH_APPLY_DETAIL + strconv.Itoa(detail.ApplyRecordId)
	}
	keyword1 = "权限申请：" + realName + "【" + companyName + "】"
	keyword2 = mobile
	keyword3 = time.Now().Format(utils.FormatDateTime)
	keyword4 = applyMethod

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = mobile
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_APPLY
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	return
}

func sendTemplateMsg(sendUrl string, sendMap map[string]interface{}, itemOpenid *models.OpenIdList, resource string, sendType int) (err error) {
	sendMap["touser"] = itemOpenid.OpenId
	data, err := json.Marshal(sendMap)
	if err != nil {
		fmt.Println("SendTemplateMsgOne Marshal Err:", err.Error())
		return err
	}
	err = toSendTemplateMsg(sendUrl, data, resource, sendType, itemOpenid)
	if err != nil {
		fmt.Println("send err:", err.Error())
	}
	return
}

func toSendTemplateMsg(sendUrl string, data []byte, resource string, sendType int, dataItem *models.OpenIdList) (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)
	var templateResponse SendTemplateResponse
	err = json.Unmarshal(body, &templateResponse)
	fmt.Println(templateResponse)
	utils.FileLog.Info("SendResult %s:", string(body))
	if err != nil {
		utils.FileLog.Info("SendResult Unmarshal Err:%s", err.Error())
		return err
	}
	//新增模板消息推送记录
	{
		tr := new(models.UserTemplateRecord)
		tr.UserId = dataItem.UserId
		tr.OpenId = dataItem.OpenId
		tr.Resource = resource
		tr.SendData = string(data)
		tr.Result = string(body)
		tr.CreateDate = time.Now().Format(utils.FormatDate)
		tr.CreateTime = time.Now().Format(utils.FormatDateTime)
		if templateResponse.Errcode == 0 {
			tr.SendStatus = 1
		} else {
			tr.SendStatus = 0
		}
		tr.SendType = sendType
		go func() {
			err = models.AddUserTemplateRecord(tr)
			if err != nil {
				utils.FileLog.Info(fmt.Sprintf("AddUserTemplateRecord Err:%s", err.Error()))
			}
		}()
	}
	return
}

type SendTemplateResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	MsgID   int    `json:"msgid"`
}

type SendWxTemplate struct {
	WxAppId        string   `description:"公众号appId"`
	First          string   `description:"模板消息first字段"`
	Keyword1       string   `description:"模板消息keyword1字段"`
	Keyword2       string   `description:"模板消息keyword2字段"`
	Keyword3       string   `description:"模板消息keyword3字段"`
	Keyword4       string   `description:"模板消息keyword4字段"`
	Remark         string   `description:"模板消息remark字段"`
	TemplateId     string   `description:"模板id"`
	RedirectUrl    string   `description:"跳转地址"`
	RedirectTarget int      `description:"小程序跳转目标:1:弘则研报小程序,2:随手办公小程序"`
	Resource       string   `description:"资源唯一标识"`
	SendType       int      `description:"发送的消息类型:1:报告,2:指标更新提醒,3:审批通知,4:销售领取客户通知,5:活动取消通知,6活动更改时间通知,7:关注的作者发布报告通知,8:发送日报（周报、双周报、月报）模板消息,9:活动预约/报名时间通知"`
	OpenIdArr      []string `description:"消息接收者openid"`
}

// 推送模板消息
func PublicSendTemplateMsg(sendInfo *SendWxTemplate) (err error) {
	postData, err := json.Marshal(sendInfo)
	if err != nil {
		utils.SendAlarmMsg("SendTemplateMsg json.Marshal Err:"+err.Error(), 1)
		return err
	}
	body := ioutil.NopCloser(strings.NewReader(string(postData)))
	client := &http.Client{}
	req, err := http.NewRequest("POST", utils.SendWxTemplateMsgUrl, body)
	if err != nil {
		utils.SendAlarmMsg("SendTemplateMsg http.NewRequest Err:"+err.Error(), 1)
		return err
	}
	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 err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	result := new(models.BaseResponse)
	err = json.Unmarshal(b, &result)
	if err != nil {
		return err
	}
	if result.Ret != 200 {
		err = errors.New(string(b))
		return err
	}
	return
}
