package com.gci.boot.annotation.fileUrl.handle;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.gci.boot.common.util.SpringContextUtil;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.exception.GciBootException;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author 24642
 */
public class FileUrlHandle extends JsonDeserializer<String> {
    @Value("${minio.fileUrl}")
    private String fileUrl;
    @Value("${minio.minioUrl}")
    private String minioUrl;

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        String inFileUrl;
        HttpServletRequest request = SpringContextUtil.getHttpServletRequest();
        String header = request.getHeader(CommonConstant.IS_INNER);
        if (Convert.toBool(header,false)) {
            inFileUrl = minioUrl;
        } else {
            inFileUrl = fileUrl;
        }
        String text = jsonParser.getText();
        if (StrUtil.isBlank(text)) {
            return text;
        }
        List<String> split = StrUtil.split(text, StrUtil.COMMA);
        for (int i = 0; i < split.size(); i++) {
            String s = split.get(i);
            if (StrUtil.isBlank(s)) {
                throw new GciBootException("上传文件地址错误！");
            } else {
                boolean contains = StrUtil.contains(s, inFileUrl);
                if (!contains) {
                    throw new GciBootException("上传文件地址未包括域名和端口！");
                }
                split.set(i,StrUtil.removeAll(s,inFileUrl));
            }
        }
        return StrUtil.join(StrUtil.COMMA,split);
    }
}
