package skdYujing

import (
	"PPOSUtils/utils"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"strings"
)

//http://192.168.0.100/Interface/DataService.Third.Gate.ashx?API=Tags.WechatBind&VName=&InTime=&Sign=&Data={"TagNFCID":"2186269","MemberID":"3_2"}
func (that *YuJingClient) NewYuJingBindRequest() *YuJingBindRequest {
	return &YuJingBindRequest{
		YuJingClient: *that,
		apiAddress:   "/Interface/DataService.Third.Gate.ashx",
		ApiName:      "Tags.WechatBind",
		Data:         map[string]string{},
	}
}

//YuJingBindResponse ...
type YuJingBindResponse struct {
	Code    string `json:"Code"`    //错误码
	Msg     string `json:"Msg"`     //错误信息
	OutTime string `json:"OutTime" default:"0"` //时间
}

//YuJingBindRequest ...
type YuJingBindRequest struct {
	YuJingClient
	apiAddress string
	ApiName    string `json:"API"`   //接口地址
	VName      string `json:"VName"` //用户分组id
	Data       map[string]string
}

//SetVName...
func (that *YuJingBindRequest) SetVName(VName string) *YuJingBindRequest {
	that.VName = VName
	return that
}

//SetTagNFCID...
func (that *YuJingBindRequest) SetTagNFCID(tagNFCID string) *YuJingBindRequest {
	that.Data["TagNFCID"] = tagNFCID
	return that
}

func (that *YuJingBindRequest) SetMemberID(memberID string) *YuJingBindRequest {
	that.Data["MemberID"] = memberID
	return that
}

//Params ...
func (that *YuJingBindRequest) Params() (url.Values, error) {
	var m = make(url.Values)
	_inTime := utils.TimeStr("'y-m-d h:i:s")
	_data, _ := json.Marshal(that.Data)
	_dataStr := string(_data)
	_signSlice := []string{
		that.ApiName,
		that.VName,
		_inTime,
		_dataStr,
	}
	m.Set("API", that.ApiName)
	m.Set("VName", that.VName)
	m.Set("InTime", _inTime)
	m.Set("Data", _dataStr)
	m.Set("Sign", utils.GetMd5String(strings.Join(_signSlice, "")))
	return m, nil
}

//Do ...
func (that *YuJingBindRequest) Do() (bool, error) {
	//return true, nil
	//
	_response, _err := that.Get(that.apiAddress, that)
	if _err != nil {
		return false, errors.New("接口请求异常:" + _err.Error())
	}
	defer _response.Body.Close()
	_result, _err := ioutil.ReadAll(_response.Body)
	if _err != nil {
		fmt.Println("request:", _response.Request)
		return false, errors.New("接口请求响应异常:" + _err.Error())
	}
	_mp := map[string]interface{}{}
	if _err := json.Unmarshal(_result, &_mp); _err != nil {
		fmt.Println("request:", _response.Request)
		fmt.Println("response:", string(_result))
		return false, errors.New("请求响应格式化json异常:" + _err.Error())
	}
	_responseData := new(YuJingBindResponse)
	if _err := utils.MapToStruct(_mp,_responseData,true); _err != nil {
		fmt.Println("request:", _response.Request)
		fmt.Println("response:", _mp)
		return false, errors.New("请求响应数据反射异常:" + _err.Error())
	}
	log.Println("==========预警系统返回值===========", _responseData)
	if _responseData.Code != "0000" {
		return false, errors.New("预警系统异常," + _responseData.Code + _responseData.Msg)
	}
	return true, nil
}
