package services

import (
	"encoding/json"
	"errors"
	"eta/eta_index_lib/utils"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// var syncTrialUrl = `http://127.0.0.1:8810/api/`  // 服务地址
var syncTrialUrl = `http://172.19.173.232:8810/api/` // 服务地址
var syncToken = `SF25sdsfwEW4fs53F4D.82SDdsooDg`     // 校验token（目前是写死的，后续可以根据用户配置）

//var syncTrialUrl = `http://127.0.0.1:8810/api/`

// BaseSyncTrialResp 基础返回
type BaseSyncTrialResp struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// SyncTrialEdbInfoResp 指标详情返回
type SyncTrialEdbInfoResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		EdbCode      string `json:"edb_code"`
		Source       int    `json:"source"`
		ServerUrl    string `json:"server_url"`
		TerminalCode string `json:"terminal_code"`
	} `json:"data"`
}

// GetHzWindUrl 获取wind的url
func GetHzWindUrl(edbCode string, source int) (windUrl string, terminalCode string, err error, errMsg string) {
	requestSyncTrialUrl := syncTrialUrl + `common/edb_info/edb_code?edb_code=%s&source=%d`
	requestSyncTrialUrl = fmt.Sprintf(requestSyncTrialUrl, edbCode, source)

	payload := strings.NewReader("-----011000010111000001101001--\r\n\r\n")

	req, _ := http.NewRequest("GET", requestSyncTrialUrl, payload)

	req.Header.Add("authorization", syncToken)
	req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		return
	}

	//fmt.Println("GetHzWindUrl body:")
	//fmt.Println(string(body))
	utils.FileLog.Info(fmt.Sprint("syncTrial result:", string(body)))

	item := new(SyncTrialEdbInfoResp)
	err = json.Unmarshal(body, &item)
	if err != nil {
		return
	}

	//异常的话，需要邮件通知
	if item.Code != 200 {
		errMsg = item.Msg
		err = errors.New(errMsg)
		return
	}
	windUrl = item.Data.ServerUrl
	terminalCode = item.Data.TerminalCode
	return
}
