package com.ensign.crm.module.crm.service;

import com.ensign.crm.module.crm.exception.AllKingdeeException;
import com.ensign.crm.module.crm.model.FileStorage;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Date: 2024/9/27 15:09
 * @Created: by ZZSLL
 */


@Service
@Slf4j
public class KingdeeFileService {

    @Resource
    private RedisTemplate<String, FileStorage> redisTemplate;

    private final String CACHE_PREFIX = "kingdee:temp_file";

    public byte[] downloadFile(String imageUrl) throws IOException, AllKingdeeException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(imageUrl);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            throw new AllKingdeeException("下载文件失败！" + responseBody);
        }
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            response.getEntity().writeTo(outputStream);
            return outputStream.toByteArray();
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public void saveImage(String key, FileStorage imageData) {
        redisTemplate.opsForValue().set(CACHE_PREFIX + key, imageData, 2, TimeUnit.HOURS);
    }

    public FileStorage getImage(String key) {
        return redisTemplate.opsForValue().get(CACHE_PREFIX + key);
    }

    public FileStorage getFile(String key) {
        return redisTemplate.opsForValue().get(CACHE_PREFIX + key);
    }

    public void saveFile(String key, FileStorage fileData) {
        redisTemplate.opsForValue().set(CACHE_PREFIX + key, fileData, 2, TimeUnit.HOURS);
    }
}
