package com.gyee.frame.util.excel;

import com.gyee.frame.common.conf.ExportConfig;
import com.gyee.frame.common.exception.QiNiuException;
import com.gyee.frame.model.auto.Windpowerstation;
import com.gyee.frame.model.auto.WindpowerstationExample;
import com.gyee.frame.service.WindpowerstationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Service
public class FileUtils {




    @Autowired
    private ExportConfig exportConfig;


    @Autowired
    private WindpowerstationService windpowerstationService;


    private final Path fileStorageLocation; // 文件在本地存储的地址


    @Autowired
    public FileUtils() {
        this.fileStorageLocation = Paths.get(System.getProperty("user.dir")).toAbsolutePath().normalize();
    }


    /**
     * 加载文件
     * @param fileName 文件名
     * @return 文件
     */
    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new QiNiuException("File not found " + fileName);
            }
        } catch (MalformedURLException ex) {
            throw new QiNiuException("File not found " + fileName);
        }
    }


    /**
     * 获取文件路径
     * @param station
     * @param templateId
     * @param month
     * @param interval
     * @return
     */
    public String getFilePath(String station,String templateId,String month,int interval) {

        StringBuilder sb = new StringBuilder();
        try {
            String val = Integer.valueOf(interval / 60) + "";
            WindpowerstationExample example = new WindpowerstationExample();
            example.createCriteria().andIdLike("%"+station+"%");
            List<Windpowerstation> lists = windpowerstationService.selectByExample(example);
            String uploadDir =  exportConfig.getExportpath();
            sb.append(uploadDir).append(File.separator);
            sb.append(month).append(File.separator);
            sb.append(val).append("分钟").append(File.separator);
            if ("1".equals(templateId)){
                sb.append(lists.get(0).getAddress()).append("单机").append(".zip");
            }else if ("2".equals(templateId)){
                sb.append(lists.get(0).getAddress()).append("测风塔").append(".xls");
            } else {
                throw new QiNiuException("请求错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    /**
     * 获取文件路径
     * @param tag
     * @param month
     * @param interval
     * @return
     */
    public String getFilePath2(HttpServletRequest request, String tag, String month, int interval) {
        String val = Integer.valueOf(interval / 60) + "";
        StringBuilder sb = new StringBuilder();
        if ("path".equals(tag)){
            sb.append(exportConfig.getExportpath()).append(File.separator);
        }else {
            sb.append(getUrl())
                    .append(File.separator)
                    .append("zhfx")
                    .append(File.separator)
                    .append("excel")
                    .append(File.separator);
        }

        sb.append(month).append(File.separator);
        sb.append(val).append("分钟");
        return sb.toString();
    }


    public  String getFilePathNoEx(String filePath) {
        if ((filePath != null) && (filePath.length() > 0)) {
            int dot = filePath.lastIndexOf('.');
            if ((dot >-1) && (dot < (filePath.length()))) {
                return filePath.substring(0, dot);
            }
        }
        return filePath;
    }


    public static String getUrl() {
        String localIP = "127.0.0.1";
        try {
            OK:
            for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet4Address) {
                        localIP = address.getHostAddress();
                        System.out.println("本机IP: " + localIP);
                        break OK;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = "http:\\"+localIP+":"+8070;
        return url;
    }

}
