package com.eitc.manage.controller.helper;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.utils.CommonUtils;
import com.eitc.common.utils.MinioUtils;
import com.eitc.framework.config.RedisDistributedLock;
import com.eitc.manage.domain.SysClinicInfo;
import com.eitc.manage.service.ISysClinicInfoService;
import io.minio.ObjectWriteResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;










/**
 * 系统诊所信息控制层帮助类 为了简介控制成的逻辑
 */
@Component
public class SysClinicInfoHelper {

    @Autowired
    private ISysClinicInfoService sysClinicInfoService;
    @Autowired
    private RedisDistributedLock redisDistributedLock;
    @Autowired

    private MinioUtils minioUtils;
    @Autowired
    private HttpServletRequest request;



    /**
     * 上传升级文件逻辑 添加md5 完整性校验
     * @param file
     * @param id
     * @param version
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public void upgradeFileUpload(MultipartFile file, String id, String version) throws IOException, NoSuchAlgorithmException {
        String md5Str = CommonUtils.calculateMD5(file.getInputStream());
        String fileName = "server_"+md5Str + version + ".tar";
        SysClinicInfo byId = sysClinicInfoService.getById(id);
        if (byId == null)
            throw new RuntimeException("数据出错了，请联系管理员！");
        ObjectWriteResponse eitc = minioUtils.uploadFile("eitc", file, fileName, file.getContentType());
        if (eitc != null) {
            System.out.println("url");
        }
    }

    /**
     * 文件下载
     * @param response
     * @param clinicInfo
     * @param version
     */
    public void fileStream(HttpServletResponse response, SysClinicInfo clinicInfo, Integer version) {
        // 获取锁
        if (redisDistributedLock.tryGetDistributedLock("downloadLocal","123", 60*3)){


            String versionString = clinicInfo.getVersionRepair();
            if (version != null && version == 1){
                versionString = clinicInfo.getVersionInfo();
            }
//          String path = "/data/server_" + versionString + ".tar"; // 文件的URL地址
          String path = "/home/upgrade/server_" + versionString + ".tar"; // 服务器存升级包的路径
//          String path = "/home/uppackage/server_" + versionString + ".tar"; // 文件的URL地址
//            String path = "F:\\Desktop\\fsdownload\\serverback.tar"; // 文件的URL地址
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 下载文件要在minio

            // 用缓存流做通道，不占用多的内存
            try (
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(Files.newInputStream(file.toPath()));
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
                response.addHeader("Content-Disposition", "attachment;filename=" + "");
//            response.addHeader("Content-Length", "" + object.available());
                response.addHeader("Content-Length", "" + file.length());
                response.addHeader("vCode", clinicInfo.getVCode());
                response.addHeader("repairCode", clinicInfo.getRepairCode());
                response.setContentType("application/octet-stream");

                FileCopyUtils.copy(bufferedInputStream, bufferedOutputStream);

            } catch (Exception e) {
                // 处理异常，比如文件找不到或读写错误
                System.err.println("文件下载失败: " + e.getMessage());
                throw new RuntimeException("文件下载失败" + e.getMessage());
            }finally {
                redisDistributedLock.releaseDistributedLock("downloadLocal","123");
            }
        }else{
            throw new RuntimeException("未能获取到锁,请重试！");
        }
    }

    public String getSysClinicInfoCode() {
        List<SysClinicInfo> list = sysClinicInfoService.list(Wrappers.<SysClinicInfo>lambdaQuery().select(SysClinicInfo::getClinicCode));
        List<String> collect = list.stream().map(SysClinicInfo::getClinicCode).collect(Collectors.toList());
        String max = Collections.max(collect);
        return String.format("%04d",Integer.parseInt(max)+1);
    }


}
