package com.ywt.mg.web.common;

import com.google.protobuf.ByteString;
import com.ywt.gapi.base.file.*;
import com.ywt.gapi.user.DoctorInfo;
import com.ywt.gapi.user.DoctorServiceGrpc;
import com.ywt.gapi.user.GetDoctorAllRequest;
import com.ywt.gapi.user.GetDoctorAllResponse;
import com.ywt.mg.web.DataResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * @author daiyihua
 * @create 2022-08-23 下午3:52
 * @desc 文件相关的公共方法
 **/
@Service
public class FileSrv {

    private Logger logger = LoggerFactory.getLogger(FileSrv.class);

    @Autowired
    private FileServiceGrpc.FileServiceBlockingStub fileServiceBlockingStub;

    public void deleteFile(String fileName) {
        try {
            //创建一个文件对象
            File file = new File(fileName);
            // 删除文件
            boolean value = file.delete();
            if (value) {
                logger.info(fileName + "已成功删除.");
            } else {
                logger.info(fileName + "文件不存在");
            }
        } catch (Exception e) {
            logger.error("delete file error:{}", e, e.getMessage());
        }
    }


    /**
     * 上传本地文件到oss
     *
     * @param localPath 本地文件
     * @param filename  文件名
     * @param ossPath   oss文件路径
     * @return 文件路径
     */
    public DataResponse localFileUploadToOss(String localPath, String filename, String ossPath, OutputStream ba) {
        DataResponse response = new DataResponse();
        try {
//            File file = new File(localPath);
//            if (!file.exists()) {
//                response.parameterErrorFailed("文件不存在");
//                return response;
//            }
            ByteArrayInputStream bio = new ByteArrayInputStream(((ByteArrayOutputStream) ba).toByteArray());
//            byte[] bytes  =  ByteString.readFrom(bio);
//            byte[] bytes = Files.readAllBytes(file.toPath());
//            String fileUrl = uploadFile(filename, ossPath, bytes);
            String fileUrl = uploadFile(filename, ossPath, bio);
            response.setData(fileUrl);
            response.succeed();
        } catch (Exception e) {
            logger.error("FileSrv#localFileUploadToOss方法出错", e.getMessage(), e);
            e.printStackTrace();
            response.appExceptionFailed();
        }
        return response;
    }


    /**
     * 上传文件
     *
     * @param filename 文件名
     * @param path     文件路径
     * @param bytes    文件
     * @return 文件路径
     */
    public String uploadFile(String filename, String path,  ByteArrayInputStream bio) {
        try {
            UploadFileRequest rest = UploadFileRequest.newBuilder()
                    .setFilename(filename)
                    .setVpath(path)
//                    .setDatas(ByteString.copyFrom(bytes))
                    .setDatas(ByteString.readFrom(bio))
                    .build();
            UploadFileResponse resp = fileServiceBlockingStub.uploadFile(rest);
            return resp.getFileUrl();
        } catch (Exception e) {
            logger.error("调用fileServiceBlockingStub.uploadFile()方法出错", e.getMessage(), e);
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 读取文件
     *
     * @param key
     * @return
     */
    public byte[] readFile(String key) {
        ReadFileRequest req = ReadFileRequest.newBuilder().setFileUrl(key).build();
        ReadFileResponse res = fileServiceBlockingStub.readFile(req);

        if (res.getCode() == 0) {
            return res.getDatas().toByteArray();
        }

        return null;
    }

}
