package eta_forum

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/utils"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// ChartSaveLib 上传图表信息
func ChartSaveLib(req string) (resp *ChartSaveLibResp, err error) {
	_, resultByte, err := post(req, "/v1/chart/save")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// ChartUpdateLib 更新图表信息
func ChartUpdateLib(req string) (resp *ChartSaveLibResp, err error) {
	_, resultByte, err := post(req, "/v1/chart/update")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// ChartDeleteLib 从社区撤回图表
func ChartDeleteLib(req string) (resp *models.BaseResponse, err error) {
	_, resultByte, err := post(req, "/v1/chart/delete")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// AdminSaveLib 上传管理员信息
func AdminSaveLib(req string) (resp *models.BaseResponse, err error) {
	_, resultByte, err := post(req, "/v1/admin/save")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// AdminDeleteLib 删除管理员信息
func AdminDeleteLib(req string) (resp *models.BaseResponse, err error) {
	_, resultByte, err := post(req, "/v1/admin/delete")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// ChartThemeSaveLib 上传图表主题信息
func ChartThemeSaveLib(req string) (resp *models.BaseResponse, err error) {
	_, resultByte, err := post(req, "/v1/chart/theme/save")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// ChartThemeTypeSaveLib 上传图表主题类型信息
func ChartThemeTypeSaveLib(req string) (resp *models.BaseResponse, err error) {
	_, resultByte, err := post(req, "/v1/chart/theme/type/save")
	err = json.Unmarshal(resultByte, &resp)
	if err != nil {
		return
	}
	return
}

// post
func post(paramStr string, urlStr string) (resp *models.BaseResponse, result []byte, err error) {
	if utils.ETA_FORUM_HUB_URL == "" {
		err = fmt.Errorf("ETA社区桥接服务地址为空")
		return
	}
	postUrl := utils.ETA_FORUM_HUB_URL + urlStr
	result, err = HttpPost(postUrl, paramStr, "application/json")
	if err != nil {
		err = fmt.Errorf("调用ETA社区桥接服务接口失败 error:%s", err.Error())
		return
	}
	err = json.Unmarshal(result, &resp)
	if err != nil {
		return
	}

	return
}

func HttpPost(url, postData string, params ...string) ([]byte, error) {
	body := ioutil.NopCloser(strings.NewReader(postData))
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	contentType := "application/x-www-form-urlencoded;charset=utf-8"
	if len(params) > 0 && params[0] != "" {
		contentType = params[0]
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("authorization", utils.MD5(utils.ETA_FORUM_HUB_NAME_EN+utils.ETA_FORUM_HUB_MD5_KEY))
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	utils.FileLog.Debug("HttpPost:" + string(b))
	return b, err
}
