package com.yizhi.application.accountUtil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.util.application.domain.EncryptParam;
import com.yizhi.util.application.sm2.SM2_NEW;

/**
 * @since 2025/05/29 11:51
 */
@RestController
@RequestMapping("/public/file")
public class FileReadController {

	private static Logger logger = LoggerFactory.getLogger(FileReadController.class);
	    
    @GetMapping("/read")
    public ResponseEntity<byte[]> getObject(@RequestParam("filePath") String filePath) {
    	logger.info("---------public file read start---------");
    	if(StringUtils.isEmpty(filePath)){
    		logger.info("---------public file read end filePath error---------");
    		return ResponseEntity.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(new byte[1]);
    	}
    	
    	EncryptParam param = JSON.parseObject(SM2_NEW.decrypt(filePath), EncryptParam.class);
    	if(param == null || StringUtils.isEmpty(param.getData()) || param.getKey() == null) {
    		logger.info("---------public file read end param error---------");
    		return ResponseEntity.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(new byte[1]);
    	}
    	logger.info("---------public file read start param---------{}", JSON.toJSONString(param));
    	RequestContext requestContext = ContextHolder.get();
    	if(requestContext == null || requestContext.getAccountId() == null){
    		logger.info("---------public file read end requestContext error---------");
    		return ResponseEntity.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(new byte[1]);
    	}
    	Long accountId = requestContext.getAccountId();
    	logger.info("---------public file read accountId:{}---------", accountId);
    	/*if(!accountId.equals(param.getKey())){
    		logger.info("---------public file read end accountId error---------accountId:{}, key:{}", accountId, param.getKey());
    		return ResponseEntity.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(new byte[1]);
    	}*/

		URL url = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        String fileName = "";
        byte[] bytes = null;
        try {
        	String strUrl = param.getData();
        	fileName = strUrl.substring(strUrl.lastIndexOf("prefix=") + 7);
        	logger.info("---------public file read start strUrl---------{}, fileName:{}", strUrl, fileName);
			url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
	        inputStream = conn.getInputStream();
	        baos = new ByteArrayOutputStream();
	        byte[] buff = new byte[1024];
	        int len;
	        while ((len = inputStream.read(buff)) != -1) {
	            baos.write(buff, 0, len);
	        }
	        bytes = baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(baos != null){
					baos.close();
				}
				if(inputStream != null){
					inputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
        if(bytes == null){
        	logger.info("---------public file read end bytes error---------");
        	return ResponseEntity.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(new byte[1]);
        }
        
        try {
			fileName = URLEncoder.encode(fileName, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(conn.getContentLengthLong());
        
        return ResponseEntity.ok().headers(headers).body(bytes);
    }
}
