package upload

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"strings"
)

const (
	BaseUrl   = "http://file-upload-test.mangguonews.com/upload"
	ImgSuffix = "jpg,jpeg,png,gif,tif,tiff,bmp,"
	Type      = "graph,video,doc,"
)

type Response struct {
	Data struct {
		File           string `json:"file"`
		Hash           string `json:"hash"`
		ScaleImage     string `json:"scaleImage"`
		UploadFileName string `json:"uploadFileName"`
		BaseUrl        string `json:"baseUrl"` //给前端返回另加的参数
	} `json:"data"`
	Message struct {
		Desc  string      `json:"desc"`
		Error interface{} `json:"error"`
	} `json:"message"`
	Status bool `json:"status"`
}

type ParamsUpload struct {
	File *multipart.FileHeader `form:"file"` //文件
	Type string                `form:"type"` //类型 img:图片
	ParamsGet
}

type ParamsGet struct {
	Width  string `form:"width"`
	Height string `form:"height"`
	Scale  string `form:"scale"`
}

func createMgNewsUploadRequest(file multipart.File, params map[string]string, fileName string) (*http.Request, error) {
	var (
		err         error
		body        *bytes.Buffer
		w           *multipart.Writer
		writer      io.Writer
		req         *http.Request
		contentType string
	)
	body = &bytes.Buffer{}
	w = multipart.NewWriter(body)
	contentType = w.FormDataContentType()
	for key, val := range params {
		_ = w.WriteField(key, val)
	}
	if file != nil {
		writer, err = w.CreateFormFile("file", fileName)
		_, err = io.Copy(writer, file)
		if err != nil {
			return nil, err
		}
	}
	w.Close()
	req, err = http.NewRequest(http.MethodPost, BaseUrl, body)
	req.Header.Set("Content-Type", contentType)
	return req, err
}

func MgNewsUpload(file multipart.File, pm map[string]string, fileName string) (respData Response, err error) {
	var (
		client  *http.Client
		req     *http.Request
		resp    *http.Response
		resBody []byte
	)
	client = &http.Client{}
	req, err = createMgNewsUploadRequest(file, pm, fileName)
	if err != nil {
		return
	}
	resp, _ = client.Do(req)
	defer resp.Body.Close()
	resBody, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	if resp.StatusCode != 200 {
		err = errors.New("上传失败")
		return
	}
	//fmt.Println(string(resBody))
	err = json.Unmarshal(resBody, &respData)
	if err != nil {
		return
	}
	return
}

func CheckType(t string) bool {
	if strings.Index(Type, strings.ToLower(t)+",") >= 0 {
		return true
	}
	return false
}

func CheckFileSuffix(fileName string, t string) bool {
	var suffix string
	suffix = fileName[(strings.LastIndex(fileName, "."))+1:]
	if t == "graph" {
		if strings.Index(ImgSuffix, strings.ToLower(suffix)+",") >= 0 {
			return true
		}
	} else {
		return false
	}
	return false
}