package utils

import (
	"io/ioutil"
	"mime/multipart"
	"sort"
)

const LimitFileHeaderSize = 1024 * 1024

type ImportFile struct {
	FileName    string
	FileContent []byte
}

func ReadMultipartFormFile(mapFile map[string][]*multipart.FileHeader, sizeLimit int) []ImportFile {
	var rsp []ImportFile
	for _, k := range getSortFileKeys(mapFile) {
		v := mapFile[k]
		rsp = append(rsp, readFormFile(v, sizeLimit)...)
	}
	return rsp
}

func readFormFile(files []*multipart.FileHeader, sizeLimit int) []ImportFile {
	var rsp []ImportFile
	if sizeLimit == 0 {
		sizeLimit = LimitFileHeaderSize
	}
	for i := range files {
		if files[i].Size > int64(sizeLimit) {
			continue
		}
		f, _ := files[i].Open()
		data, _ := ioutil.ReadAll(f)
		f.Close()
		rsp = append(rsp, ImportFile{
			FileName:    files[i].Filename,
			FileContent: data,
		})
	}
	return rsp
}

//获取排序键值
func getSortFileKeys(files map[string][]*multipart.FileHeader) (keys []string) {
	for k, _ := range files {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return
}