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=Gate.Checkin&VName=&InTime=&Sign=&Data={"TagNFCID":"2186269","MemberID":"3_2"}
func (that *YuJingClient) NewYuJingCheckOutRequest() *YuJingCheckOutRequest {
	return &YuJingCheckOutRequest{
		YuJingClient: *that,
		apiAddress:   "/Interface/DataService.Third.Gate.ashx",
		ApiName:      "Gate.Checkout",
		Data:         map[string]string{},
	}
}

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

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

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

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

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

//Params ...
func (that *YuJingCheckOutRequest) 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 *YuJingCheckOutRequest) 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())
	}
	_yuJingCheckOutResponse := new(YuJingCheckOutResponse)
	if _err := that.ParseResponeMp(_yuJingCheckOutResponse, _mp); _err != nil {
		fmt.Println("request:", _response.Request)
		fmt.Println("response:", _mp)
		return false, errors.New("请求响应数据反射异常:" + _err.Error())
	}
	log.Println("==========预警系统返回值===========", _yuJingCheckOutResponse)
	if _yuJingCheckOutResponse.Code != "0000" {
		return false, errors.New("预警系统异常," + _yuJingCheckOutResponse.Code + _yuJingCheckOutResponse.Msg)
	}
	return true, nil
}
