package cn.ibizlab.util.domain;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;

import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Data
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("文件")
public class FileDto
{
	@ApiModelProperty(value = "文件标识", position = 1)
	private String id;
	@ApiModelProperty(value = "文件名", position = 2)
	private String name;
	@ApiModelProperty(value = "文件流/base64", position = 3)
	private byte[] content;


	@SneakyThrows
	@JsonIgnore
	@JSONField(serialize = false)
	public File getFile(String rootPath, boolean override) {
		if(ObjectUtils.isEmpty(id)&& ObjectUtils.isEmpty(content))
			return null;
		if(ObjectUtils.isEmpty(id))
			id= UUID.randomUUID().toString();
		if(ObjectUtils.isEmpty(name))
			name=id;
		Path path= Paths.get(rootPath,id,name);
		if(override && !ObjectUtils.isEmpty(content))
		{
			File dir=path.getParent().toFile();
			if(!dir.exists())
				dir.mkdirs();
			Files.write(path,content);
		}
		if(Files.exists(path))
			return path.toFile();
		return null;
	}

	@JsonIgnore
	@JSONField(serialize = false)
	protected Map<String,Object> extensionparams=new HashMap<String,Object>();

	@JsonIgnore
	@JSONField(serialize = false)
	public Object get(String field) {
		return this.extensionparams.get(field);
	}

	@JsonAnyGetter
	@JSONField(name = "_any", unwrapped = true, serialize = true, deserialize = false)
	public Map<String , Object> any() {
		return extensionparams;
	}

	@JsonAnySetter
	@JSONField(name = "_any", unwrapped = true, serialize = false, deserialize = true)
	public void set(String field, Object value) {
		this.extensionparams.put(field ,value);
	}

	@Override
	public String toString() {
		return getId();
	}
}