query_result.go 3.0 KB
package k3cloud

import (
	"encoding/json"
	"strings"

	"github.com/tidwall/gjson"
)

//QueryError 单据查询错误信息
type QueryError struct {
	Result struct {
		ResponseStatus struct {
			ErrorCode int  `json:"ErrorCode"`
			IsSuccess bool `json:"IsSuccess"`
			Errors    []struct {
				FieldName interface{} `json:"FieldName"`
				Message   string      `json:"Message"`
				DIndex    int         `json:"DIndex"`
			} `json:"Errors"`
		} `json:"ResponseStatus"`
	} `json:"Result"`
}

func (qe QueryError) Error() string {
	str := ""
	for _, errMsg := range qe.Result.ResponseStatus.Errors {
		str += errMsg.Message + ";"
	}
	return str
}

/*BillQueryResult 单据查询结果
当接口调用失败时得到的json 结构对应[][]QueryError,如:
[[{"Result":{"ResponseStatus":{"Errors":[{"Message":"元数据中标识为FUseOrg的字段不存在"}]}}}]]
当接口调用成功的得到的json结构对应[][]interface{},如:
[["xxx","abc",2345]]
*/
type BillQueryResult struct {
	FieldKeys []string //对应的键名 ,注意数据的顺序
	Buf       []byte   //原始的数据byte
}

func newBillQueryResult(buf []byte, keys string) *BillQueryResult {
	return &BillQueryResult{
		Buf:       buf,
		FieldKeys: strings.Split(keys, ","),
	}
}

func (result *BillQueryResult) ToMapString() []map[string]string {
	if result.IsError() {
		return nil
	}
	jResult := gjson.ParseBytes(result.Buf)
	mapResult := []map[string]string{}
	var mapTemp map[string]string
	for _, arr1 := range jResult.Array() {
		mapTemp = make(map[string]string)
		for index2, item := range arr1.Array() {
			if index2 > len(result.FieldKeys) {
				continue
			}
			keyName := result.FieldKeys[index2]
			mapTemp[keyName] = item.String()
		}
		mapResult = append(mapResult, mapTemp)
	}
	return mapResult
}

func (result *BillQueryResult) ToMap() []map[string]interface{} {
	if result.IsError() {
		return nil
	}
	jResult := gjson.ParseBytes(result.Buf)
	mapResult := []map[string]interface{}{}
	var mapTemp map[string]interface{}
	for _, arr1 := range jResult.Array() {
		mapTemp = make(map[string]interface{})
		for index2, item := range arr1.Array() {
			if index2 > len(result.FieldKeys) {
				continue
			}
			keyName := result.FieldKeys[index2]
			mapTemp[keyName] = item.Value()
		}
		mapResult = append(mapResult, mapTemp)
	}
	return mapResult
}

func (result *BillQueryResult) Error() error {
	var (
		err error
	)
	jResult := gjson.ParseBytes(result.Buf)
	for _, arr1 := range jResult.Array() {
		for _, item := range arr1.Array() {
			if !item.IsObject() {
				return nil
			}
			var errMsg QueryError
			err = json.Unmarshal([]byte(item.Raw), &errMsg)
			if err != nil {
				return err
			}
			err = errMsg
		}
	}
	return err
}

//TODO 将结果解析为结构体
// func (result *BillQueryResult) ToStruct(v interface{}) error {
// return nil
// }

func (result *BillQueryResult) IsError() bool {
	jResult := gjson.ParseBytes(result.Buf)
	for _, arr1 := range jResult.Array() {
		for _, item := range arr1.Array() {
			if item.IsObject() {
				return true
			}
		}
	}
	return false
}