package com.gree.mall.manager.logic.ums;

import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.utils.StringUtil;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Service
@Slf4j
public class FileSftpUploaderLogic {

    // 粤焕新平台上传接口地址
    @Value("${yue.huan.xin.sftp}")
    private String sftpUpload;
    @Value("${yue.huan.xin.sftp.port}")
    private String sftpPort;

    @Resource
    RestTemplate restTemplate;

    private static final String TMP_DIR = "tmp"; // 指定临时目录名称

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000);    // 5秒连接超时
        factory.setReadTimeout(10000);      // 10秒读取超时
        return new RestTemplate(factory);
    }

    /**
     * 从下载地址获取文件并上传
     * @param downloadUrl 文件下载地址
     * @param platformId 平台id
     * @param username 上传账号
     * @param password 上传密码
     * @return 上传结果
     */
    public String uploadFromUrl(String downloadUrl, String platformId, String username, String password) throws IOException {
        File downloadedFile = null;
        try {
            // 1. 下载文件到临时目录
            downloadedFile = downloadFile(downloadUrl);
            if (Objects.isNull(downloadedFile)) {
                throw new RemoteServiceException("文件下载失败");
            }

            // 2. 验证文件大小
            if (downloadedFile.length() > 1024 * 1024) {
                Files.deleteIfExists(downloadedFile.toPath());
                throw new RemoteServiceException("文件大小超过1MB限制");
            }

            // 3. 生成符合规范的文件名
            String fileName = generateFileName(downloadedFile.getName(), platformId);

            // 4. 上传文件
//            boolean uploadSuccess = uploadFile(downloadedFile, fileName, username, password);
            // SFTP上传
            boolean uploadSuccess = sftpUpload(downloadedFile, fileName, username, password);

            if (!uploadSuccess) {
                throw new RemoteServiceException("上传失败");
            }

            return fileName;
        } catch (IOException e) {
            throw new RemoteServiceException("上传处理异常: " + e.getMessage());
        } finally {
            // 5. 清理临时文件
            if (Objects.nonNull(downloadedFile)) {
                Files.deleteIfExists(downloadedFile.toPath());
            }
        }
    }

    /**
     * 下载文件到本地临时目录
     */
    private File downloadFile(String fileUrl) throws IOException {
        log.info("yuehuanxin补贴图片开始下载文件: {}", fileUrl);
        // 1. 检查并创建临时目录
        Path tmpDirPath = Paths.get(TMP_DIR);
        if (!Files.exists(tmpDirPath)) {
            Files.createDirectories(tmpDirPath); // 创建目录（包含父目录）
        }
        String extension = fileUrl.contains(".") ?
                fileUrl.substring(fileUrl.lastIndexOf(".")) : "";

        if (StringUtils.isBlank(extension)
                || !StringUtil.containsIgnoreCase(".JPG|.PNG", extension)) {
            throw new RemoteException("下载文件格式异常");
        }

        // 2. 生成唯一文件名（避免覆盖）
        String fileName = "download_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8) + extension;
        Path targetPath = tmpDirPath.resolve(fileName);

        // 3. 下载文件到指定目录
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);

        try (InputStream inputStream = connection.getInputStream()) {
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } finally {
            connection.disconnect();
        }

        return targetPath.toFile();
    }

    /**
     * 生成符合规范的文件名
     */
    private String generateFileName(String originalName, String platformId) {
        String extension = originalName.contains(".") ?
                originalName.substring(originalName.lastIndexOf(".")) : "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String uploadDate = dateFormat.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return String.format("%s_%s_%s%s", platformId, uploadDate, uuid, extension);
    }

    /**
     * 以http方式上传文件到粤焕新平台
     */
//    private boolean uploadFile(File file, String fileName, String username, String password) {
//        try {
//            log.info("yuehuanxin开始上传文件，生成的文件名: {}", fileName);
//            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
//
//            // 关键修改：覆盖 FileSystemResource 的 getFilename() 方法
//            body.add("file", new FileSystemResource(file) {
//                @Override
//                public String getFilename() {
//                    return fileName; // 返回生成的规范文件名
//                }
//            });
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//            headers.setBasicAuth(username, password);
//
//            HttpEntity<MultiValueMap<String, Object>> requestEntity =
//                    new HttpEntity<>(body, headers);
//
//            ResponseEntity<String> response = restTemplate.exchange(
//                    uploadUrl,
//                    HttpMethod.POST,
//                    requestEntity,
//                    String.class
//            );
//
//            return response.getStatusCode() == HttpStatus.OK;
//        } catch (Exception e) {
//            log.error("yuehuanxin文件上传失败: {}", e.getMessage());
//            return false;
//        }
//    }

    public boolean sftpUpload(File localFile, String fileName, String username, String password) {
        Session session = null;
        ChannelSftp channel = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, sftpUpload, Integer.parseInt(sftpPort));
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            // 保持原有文件名逻辑不变
            channel.put(localFile.getAbsolutePath(), fileName);

            return true;
        } catch (JSchException | SftpException e) {
            throw new RemoteServiceException("yuehuanxin文件上传失败: " + e.getMessage());
        } finally {
            if (channel != null && channel.isConnected()) {
                channel.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}
