/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ifish.helper;

import com.ifish.dto.JsonResult;
import com.ifish.enums.ResultEnum;
import com.ifish.util.IfishFilePath;
import com.ifish.validator.ValidateUtil;
import org.codehaus.plexus.util.StringUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * FastDFS分布式文件管理系统接口方法
 *
 * @author Administrator
 */
@Component
public class FastDFSClient implements FastDFSClientI {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    //使用StorageClient1进行上传
    private StorageClient1 storageClient1 = null;

    public FastDFSClient() throws Exception {
        //获取classpath路径下配置文件"fdfs_client.conf"的路径
        //conf直接写相对于classpath的位置，不需要写classpath:
        String conf = "";
        if (IfishFilePath.link_img_head.contains("ifish7")) {
            conf = "fdfs_client_ifish7.conf";
        } else {
            conf = "fdfs_client_zhangxinyanv5.conf";
        }

        String configPath = this.getClass().getClassLoader().getResource(conf).getFile();
        System.out.println(configPath);
        ClientGlobal.init(configPath);

        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = trackerClient.getStoreStorage(trackerServer);
        storageClient1 = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传一个字节型文件
     *
     * @param file_buff 字节数组
     * @param file_ext_name 文件后缀
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFile(byte[] file_buff, String file_ext_name) throws Exception {

        String result = "";

        try {
            result = storageClient1.upload_file1(file_buff, file_ext_name, null);
        } catch (Exception e) {
            try {
                result = storageClient1.upload_file1(file_buff, file_ext_name, null);
            } catch (Exception a) {
                return "";
            }
        }

        return result;
    }

    /**
     * 上传一个本地文件
     *
     * @param local_filename 本地文件名（路径+文件名+后缀）
     * @param file_ext_name 文件后缀
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFile(String local_filename, String file_ext_name) throws Exception {

        String result = storageClient1.upload_file1(local_filename, file_ext_name, null);

        return result;
    }

    /**
     * 上传一个文件
     *
     * @param group_name 指定位置
     * @param local_filename 本地文件名（路径+文件名+后缀）
     * @param file_ext_name 文件后缀
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFile(String group_name, String local_filename, String file_ext_name) throws Exception {

        String result = storageClient1.upload_file1(group_name, local_filename, file_ext_name, null);

        return result;
    }

    @Override
    public JsonResult<?> uploadFile(MultipartFile file) {
        try {
            String type = getFileType(file);
            if (StringUtils.isBlank(type)) {
                return null;
            }
            byte[] bt = file.getBytes();
            String url = uploadFile(bt, type);
            JsonResult<String> js = new JsonResult<String>(ResultEnum.success.getKey(), "http://139.196.24.156:8017/" + url);
            return js;
        } catch (Exception e) {
            JsonResult<String> js = new JsonResult<String>(ResultEnum.fail101.getKey());
            return js;
        }
    }

    public String getFileType(MultipartFile file) {
        String[] allowTypes = new String[]{".mp4", ".png", ".jpg", ".bmp"};
        String filename = file.getOriginalFilename();
        if (StringUtils.isNotBlank(filename)) {
            for (String allowType : allowTypes) {
                if (filename.contains(allowType)) {
                    return allowType.replace(".", "");
                }
            }
        }
        return "";
    }

    @Override
    public String uploadFileToFastDFS(MultipartFile file) {
        try {
            String type = getFileType(file);
            if (StringUtils.isBlank(type)) {
                return null;
            }
            byte[] bt = file.getBytes();
            String url = uploadFile(bt, type);
            if (url.contains("group1/M00/")) {
                url = url.replace("group1/M00/", "");
            } else {
                return "";
            }
            //本地返回测试环境fastfds,线上返回正式服务器部署的fastfds
            if (ValidateUtil.IsWinOrUnix()) {
                return IfishFilePath.fastDFS_url_app + url;
            } else {
                return IfishFilePath.link_img_head + url;
            }

        } catch (Exception e) {
            return "";
        }
    }
}
