package fm

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"

	"ems.agt/lib/dborm"
	"ems.agt/lib/log"
	"ems.agt/restagent/config"
)

func AlarmForwardBySMS(alarmData *Alarm) error {
	log.Info("AlarmForwardBySMS processing... ")

	SMSFforwardconfig := config.GetYamlConfig().Alarm.SMS
	// 阿里云短信API的请求地址
	apiURL := SMSFforwardconfig.ApiURL

	// 阿里云短信API的AccessKey ID和AccessKey Secret
	//accessKeyID := SMSFforwardconfig.AccessKeyID
	accessKeySecret := SMSFforwardconfig.AccessKeySecret

	toUsers, err := dborm.XormGetAlarmForward("SMS")
	if err != nil {
		log.Error("Failed to XormGetAlarmForward:", err)
		return err
	} else if toUsers == nil {
		err := errors.New("not found forward phone number")
		log.Error(err)
		return err
	}

	for _, toUser := range *toUsers {
		// 短信相关参数
		params := url.Values{}
		params.Set("PhoneNumbers", toUser)
		params.Set("SignName", SMSFforwardconfig.SignName)
		params.Set("TemplateCode", SMSFforwardconfig.TemplateCode)
		params.Set("TemplateParam", `{"message":"alarm"}`)

		// 构建请求URL
		reqURL := apiURL + "?Action=SendSms&" + params.Encode()

		// 创建HTTP请求
		req, err := http.NewRequest("GET", reqURL, nil)
		if err != nil {
			log.Error("Failed to create request:", err)
			return err
		}

		// 添加请求头部
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Authorization", "APPCODE "+accessKeySecret)

		forwardLog := &dborm.AlarmForwardLog{
			NeType:     alarmData.NeType,
			NeID:       alarmData.NeId,
			AlarmID:    alarmData.AlarmId,
			AlarmTitle: alarmData.AlarmTitle,
			AlarmSeq:   alarmData.AlarmSeq,
			EventTime:  alarmData.EventTime,
			ToUser:     toUser,
		}
		// 发送请求
		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			operResult := fmt.Sprintf("Failed to send request:%v", err)
			log.Error(operResult)
			forwardLog.OperResult = operResult
			affected, err := dborm.XormInsertAlarmForwardLog(forwardLog)
			if err != nil && affected <= 0 {
				log.Error("Failed to insert data:", err)
			}
			continue
		}
		defer resp.Body.Close()

		// 解析响应
		if resp.StatusCode == http.StatusOK {
			log.Info("SMS sent successfully!")
			operResult := fmt.Sprintf("SMS sent successfully!")
			forwardLog.OperResult = operResult
			affected, err := dborm.XormInsertAlarmForwardLog(forwardLog)
			if err != nil && affected <= 0 {
				log.Error("Failed to insert data:", err)
				continue
			}
		} else {
			operResult := fmt.Sprintf("Failed to send SMS, StatusCode=%d", resp.StatusCode)
			log.Error(operResult)
			forwardLog.OperResult = operResult
			affected, err := dborm.XormInsertAlarmForwardLog(forwardLog)
			if err != nil && affected <= 0 {
				log.Error("Failed to insert data:", err)
				continue
			}
		}
	}
	return nil
}
