package pwc.taxtech.atms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import pwc.taxtech.atms.common.config.FileServiceConfig;
import pwc.taxtech.atms.common.util.DateUtils;
import pwc.taxtech.atms.dto.ApiResultDto;
import pwc.taxtech.atms.dto.FileDto;
import pwc.taxtech.atms.exception.ServiceException;

import java.io.IOException;
import java.io.InputStream;

/**
  * version 2.0
 * author kevin
 */
@Service
public class HttpFileService extends BaseService {
    @Autowired
    private FileServiceConfig config;
    private static final String USER_TEMPLATE_PATH = "pwc/userTemplate/";
    private static final String HTTP_HEADER = "application/json;charset=UTF-8";

    /**
     * 上传模板
     *
     * @param fileName 文件名
     * @param file     MultipartFile
     * @param  fullPath 是否返回全路径 默认false ,如果为true返回的路径直接可以用于下载
     * @return Boolean
     */
    public String uploadTemplate(String fileName, MultipartFile file, boolean fullPath) throws ServiceException {
        if (StringUtils.isBlank(fileName) || null == file) {
            throw new IllegalArgumentException("上传参数为空");
        }
        CloseableHttpClient httpClient = null;
        String filePath = USER_TEMPLATE_PATH + fileName;
        try {
            String serverPath = config.getServerUrl() + config.getUploadUrl();
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(serverPath);
            httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

            JSONObject param = new JSONObject();
            param.put("path", filePath);
            param.put("file", file.getBytes());

            HttpEntity httpEntity = new StringEntity(param.toJSONString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(httpEntity);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            ApiResultDto resultDto = JSON.parseObject(IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"), ApiResultDto.class);
            if (resultDto.getCode() == ApiResultDto.SUCCESS) {
                if(fullPath){
                    return config.getServerUrl() + "/" + filePath;
                }
                return filePath;
            }
        } catch (Exception e) {
            logger.error("uploadTemplate error.", e);
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("close httpClient error.", e);
                }
            }
        }
        throw new ServiceException("uploadTemplate error.");
    }


    public String uploadTemplate(String fileName, MultipartFile file) throws ServiceException{
        return  uploadTemplate(fileName, file, false);
    }

    /**
     * 下载模板
     *
     * @param filePath 模板路径
     * @return InputStream
     */
    public InputStream getUserTemplate(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        if (StringUtils.isNotBlank(config.getServerUrl())) {
            CloseableHttpClient client = HttpClients.createDefault();
            //先判断下是否是全域名 全域名代表是didi服务器url
            String url;
            if(filePath.indexOf("http")>=0){
                url = filePath;
            }else{
                url = StringUtils.appendIfMissing(config.getServerUrl(), "/") + filePath;
            }
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = null;
            try {
                response = client.execute(httpGet);
                if (response.getStatusLine().getStatusCode() == 200) {
                    return IOUtils.toBufferedInputStream(response.getEntity().getContent());
                }
            } catch (Exception e) {
                logger.error("getUserTemplate error.", e);
            } finally {
                if (null != client) {
                    try {
                        client.close();
                    } catch (IOException e) {
                        logger.error("close httpClient error.", e);
                    }
                }
            }
        }
        return null;
    }



    //上传
    public FileDto upload(MultipartFile file, String remarks){
        FileDto fileDto = new FileDto();
        int i = file.getOriginalFilename().lastIndexOf(".");
        fileDto.setFileName(file.getOriginalFilename());
        if(remarks != null){
            fileDto.setRemarks(remarks);
        }

        fileDto.setFileUrl(uploadTemplate(file.getOriginalFilename(), file, true));
        //绑定
        fileDto.setSize(String.valueOf(file.getSize()/1024));
        fileDto.setUploadUser(authUserHelper.getCurrentAuditor().get());
        fileDto.setCreateTime(DateUtils.getNowDate());
        return fileDto;
    }
}