/**
  @author: yaoyuliang
  @date: 2023/8/1
**/
package saas_file

import (
	"errors"
	"gin-vue-admin/models"
	"gin-vue-admin/utils"
	"io/ioutil"
	"net/http"
	"net/url"
)

var LOCAL_SAAS_FILE *SaasFile

func init() {
	LOCAL_SAAS_FILE = new(SaasFile)
	LOCAL_SAAS_FILE.RootAddress = "https://sanswer.pet-dbc.cn"
	LOCAL_SAAS_FILE.GetTokenFile = "/api/user/login?info="
}

type SaasFile struct {
	XToken       string
	RootAddress  string
	GetTokenFile string
}

type Header struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

func (c *SaasFile) GetInfo(chainCode, hospitalCode, consumerId string) string {
	info := utils.GetEncryptDes(chainCode + "|" + hospitalCode + "|" + consumerId)
	return url.QueryEscape(info)
}

func (c *SaasFile) GetSaasFileToken(chainCode, hospitalCode, consumerId string) error {

	body, err := ToRequest(http.MethodGet, c.RootAddress+c.GetTokenFile+c.GetInfo(chainCode, hospitalCode, consumerId), nil)
	if err != nil {
		return err
	}

	reply := new(models.QuestionLogin)
	utils.UnserislizeJson(string(body), reply)

	if reply.Code == 0 {
		c.XToken = reply.Data.Token
	}
	return nil

}

func ToRequest(method, urlStr string, headers []*Header) ([]byte, error) {

	req, err := http.NewRequest(method, urlStr, nil)
	if err != nil {
		return nil, err
	}

	for _, v := range headers {
		req.Header.Add(v.Key, v.Value)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, errors.New(" unknown error ")
	}
	return body, nil
}

func (c *SaasFile) ToPreviewFile(chainCode, hospitalCode, consumerId, petId string) (interface{}, error) {

	err := c.GetSaasFileToken(chainCode, hospitalCode, consumerId)
	if err != nil {
		return nil, err
	}

	headers := make([]*Header, 0)
	headers = append(headers, &Header{Key: "xtoken", Value: c.XToken})

	body, err := ToRequest(http.MethodGet, c.RootAddress+"/api/file/preview?show=1&pet_id="+petId, headers)
	if err != nil {
		return nil, err
	}

	reply := new(models.SaasFileCurrency)
	utils.UnserislizeJson(string(body), reply)

	if reply.Code == 0 {
		return reply.Data, nil
	}

	return nil, nil

}