package response

import (
	"DataShare/util"
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

type ResponseXml struct {
	Code int         `xml:"code"`
	Data interface{} `xml:"data"`
	Msg  string      `xml:"msg"`
}

const (
	ERR_OK                 = 0
	ERR_INVALID_PARAM      = 1
	ERR_QUERY_DATABASE     = 2
	ERR_NOT_FOUND          = 3
	ERR_ALREADY_EXIST      = 4
	ERR_SYS_ERROR          = 5
	ERR_TRANS_ERROR        = 6
	ERR_HOSPITAL_ERROR     = 7
	ERR_FACE_DETECT_ERROR  = 8
	ERR_INVALID_DATA       = 9
	ERR_NOT_LOGIN          = 10
	ERR_LOGIN_EXPIRED      = 11
	ERR_INVALID_TOKEN      = 12
	ERR_CHANGE_STATUS      = 13
	ERR_UNSUPPORTED        = 14
	ERR_LOGIN_FAILED       = 15
	ERR_PERMISSION         = 16
	ERR_FAILED             = 99

)

type MyMap map[string]interface{}

func Result(code int, data interface{}, msg string, c *gin.Context, format string) {

	if format == "XML" {
		xmlResp := &ResponseXml{
			Code: code,
			Data: data,
			Msg:  msg,
		}
		dataByte,err :=json.Marshal(xmlResp)
		if err != nil {
			fmt.Println("Err:",err.Error())
		}
		//fmt.Println("jsondata:",string(dataByte))
		xmlByte := bytes.NewBuffer(make([]byte, 0))
		xmlWriter := bufio.NewWriter(xmlByte)
		err = util.ToXML(strings.NewReader(string(dataByte)),xmlWriter)
		if err != nil {
			fmt.Println("Err:",err.Error())
			c.JSON(http.StatusOK, Response{
				99,
				nil,
				msg,
			})
			return
		}
		//fmt.Println("xml:",xmlByte.String())

		c.XML(http.StatusOK, xmlByte.String())

	}else{
		c.JSON(http.StatusOK, Response{
			code,
			data,
			msg,
		})
	}

}

func Ok(c *gin.Context, format string) {
	Result(ERR_OK, map[string]interface{}{}, "操作成功", c,format)
}

func OkWithMessage(message string, c *gin.Context, format string) {
	Result(ERR_OK, map[string]interface{}{}, message, c,format)
}

func OkWithData(data interface{}, c *gin.Context, format string) {
	Result(ERR_OK, data, "操作成功", c,format)
}

func OkDetailed(data interface{}, message string, c *gin.Context, format string) {
	Result(ERR_OK, data, message, c,format)
}

func Fail(c *gin.Context, format string) {
	Result(ERR_FAILED, map[string]interface{}{}, "操作失败", c,format)
}

func FailWithMessage(message string, c *gin.Context, format string) {
	Result(ERR_FAILED, map[string]interface{}{}, message, c,format)
}

func FailWithDetailed(code int, data interface{}, message string, c *gin.Context, format string) {
	Result(code, data, message, c,format)
}
