package com.keystar.plane.inspection.utils;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keystar.plane.inspection.bo.Location;
import com.keystar.plane.inspection.bo.NewFileBo;
import com.keystar.plane.inspection.constant.LocationConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class FileUtil {

    public static Map<String, Map<String, List<Location>>> readCurrent(String mFilePath) {

        Map<String, Map<String, List<Location>>> mReMap = new HashMap<>();

        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;

        JSONObject mFeatureJSONObject = null;

        try {

            StringBuffer mStringBuffer = new StringBuffer();

//            fileInputStream = new FileInputStream(new File(mFilePath));
//            bufferedInputStream = new BufferedInputStream(fileInputStream);
            Resource resource = new ClassPathResource(mFilePath);
            bufferedInputStream = new BufferedInputStream(resource.getStream());

            byte[] bytes = new byte[1024];
            int mReadLength = -1;
            while ((mReadLength = bufferedInputStream.read(bytes, 0, 1024)) != -1) {
                if (mReadLength == 1024) {
                    mStringBuffer.append(new String(bytes));
                }else {
                    byte[] mBytes = new byte[mReadLength];
                    System.arraycopy(bytes, 0, mBytes, 0, mReadLength);
                    mStringBuffer.append(new String(mBytes));
                }
            }
            String mJSONStr = mStringBuffer.toString();
            JSONObject mJSONObject = JSONObject.parseObject(mJSONStr.replace("\t","").replace("\n", "")
                    .replace("\r", "").replace("\\s", ""));
            JSONArray mFeatureJSONArray = mJSONObject.getJSONArray("features");
            for (int index = 0; index < mFeatureJSONArray.size(); index++) {
                mFeatureJSONObject = mFeatureJSONArray.getJSONObject(index);
                JSONObject mPropertieJSONObject = mFeatureJSONObject.getJSONObject("properties");
                String mCurrentName = mPropertieJSONObject.getString("Name");
                JSONObject mGeometryJSONObject = mFeatureJSONObject.getJSONObject("geometry");
                JSONArray mCoordinateJSONArray = mGeometryJSONObject.getJSONArray("coordinates");
                JSONArray mCoordinateLLJSONArray = mCoordinateJSONArray.getJSONArray(0);
                List<Location> mLocationList = new ArrayList<>();
                for (int mIndex = 0; mIndex < 4; mIndex++) {
                    JSONArray mCoordinateLLValueJSONArray = mCoordinateLLJSONArray.getJSONArray(mIndex);
                    Location mLocation = new Location();
                    mLocation.setLon(mCoordinateLLValueJSONArray.getDouble(0));
                    mLocation.setLat(mCoordinateLLValueJSONArray.getDouble(1));
                    mLocationList.add(mLocation);
                }
                String[] mCurrentNameArray = mCurrentName.split("\\|");
                String mFZKey = mCurrentNameArray[0].split("HL")[0];
                if (!mReMap.containsKey(mFZKey)) {
                    mReMap.put(mFZKey, new HashMap<>());
                }
                mReMap.get(mFZKey).put(mCurrentName, mLocationList);
            }
        }catch (Exception e) {

        }finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                }catch (Exception e) {

                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }catch (Exception e) {

                }
            }
        }

        return mReMap;

    }

    public static Map<String, List<Location>> readFZLatLng(String mFilePath) {

        Map<String, List<Location>> mReMap = new HashMap<>();

        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;

        JSONObject mFeatureJSONObject = null;

        try {
            StringBuffer mStringBuffer = new StringBuffer();

//            fileInputStream = new FileInputStream(new File(mFilePath));
//            bufferedInputStream = new BufferedInputStream(fileInputStream);
            Resource resource = new ClassPathResource(mFilePath);
            bufferedInputStream = new BufferedInputStream(resource.getStream());

            byte[] bytes = new byte[1024];
            int mReadLength = -1;
            while ((mReadLength = bufferedInputStream.read(bytes, 0, 1024)) != -1) {
                if (mReadLength == 1024) {
                    mStringBuffer.append(new String(bytes));
                }else {
                    byte[] mBytes = new byte[mReadLength];
                    System.arraycopy(bytes, 0, mBytes, 0, mReadLength);
                    mStringBuffer.append(new String(mBytes));
                }
            }
            String mJSONStr = mStringBuffer.toString();
            JSONObject mJSONObject = JSONObject.parseObject(mJSONStr.replace("\t","").replace("\n", "")
                    .replace("\r", "").replace("\\s", ""));
            JSONArray mFeatureJSONArray = mJSONObject.getJSONArray("features");
            for (int index = 0; index < mFeatureJSONArray.size(); index++) {
                mFeatureJSONObject = mFeatureJSONArray.getJSONObject(index);
                JSONObject mPropertieJSONObject = mFeatureJSONObject.getJSONObject("properties");
                String mCurrentName = mPropertieJSONObject.getString("Name");
                JSONObject mGeometryJSONObject = mFeatureJSONObject.getJSONObject("geometry");
                JSONArray mCoordinateJSONArray = mGeometryJSONObject.getJSONArray("coordinates");
                JSONArray mCoordinateLLJSONArray = mCoordinateJSONArray.getJSONArray(0);
                List<Location> mLocationList = new ArrayList<>();
                for (int mIndex = 0; mIndex < mCoordinateLLJSONArray.size() - 1; mIndex++) {
                    JSONArray mCoordinateLLValueJSONArray = mCoordinateLLJSONArray.getJSONArray(mIndex);
                    Location mLocation = new Location();
                    mLocation.setLon(mCoordinateLLValueJSONArray.getDouble(0));
                    mLocation.setLat(mCoordinateLLValueJSONArray.getDouble(1));
                    mLocationList.add(mLocation);
                }
                mReMap.put(mCurrentName, mLocationList);
            }
        }catch (Exception e) {

        }finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                }catch (Exception e) {

                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }catch (Exception e) {

                }
            }
        }

        return mReMap;

    }


    /**
     *  获取每个光伏板四角的经纬度坐标，存入Map中
     **/
    public static Map<String, Map<String, List<Location>>> ReadFileByIO(String mFilePath) {

        Map<String, Map<String, List<Location>>> mReMap = new HashMap<>();

        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;

        JSONObject mFeatureJSONObject = null;

        try {

            StringBuffer mStringBuffer = new StringBuffer();

            fileInputStream = new FileInputStream(new File(mFilePath));
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            byte[] bytes = new byte[1024];
            int mReadLength = -1;
            while ((mReadLength = bufferedInputStream.read(bytes, 0, 1024)) != -1) {
                if (mReadLength == 1024) {
                    mStringBuffer.append(new String(bytes));
                }else {
                    byte[] mBytes = new byte[mReadLength];
                    System.arraycopy(bytes, 0, mBytes, 0, mReadLength);
                    mStringBuffer.append(new String(mBytes));
                }
            }
            String mJSONStr = mStringBuffer.toString();
            JSONObject mJSONObject = JSONObject.parseObject(mJSONStr.replace("\t","").replace("\n", "")
                    .replace("\r", "").replace("\\s", ""));
            JSONArray mFeatureJSONArray = mJSONObject.getJSONArray("features");
            for (int index = 0; index < mFeatureJSONArray.size(); index++) {
                mFeatureJSONObject = mFeatureJSONArray.getJSONObject(index);
                JSONObject mPropertieJSONObject = mFeatureJSONObject.getJSONObject("properties");
                String mCurrentName = mPropertieJSONObject.getString("Name");
                JSONObject mGeometryJSONObject = mFeatureJSONObject.getJSONObject("geometry");
                JSONArray mCoordinateJSONArray = mGeometryJSONObject.getJSONArray("coordinates");
                JSONArray mCoordinateLLJSONArray = mCoordinateJSONArray.getJSONArray(0);
                List<Location> mLocationList = new ArrayList<>();
                for (int mIndex = 0; mIndex < 4; mIndex++) {
                    JSONArray mCoordinateLLValueJSONArray = mCoordinateLLJSONArray.getJSONArray(mIndex);
                    Location mLocation = new Location();
                    mLocation.setLon(mCoordinateLLValueJSONArray.getDouble(1));
                    mLocation.setLat(mCoordinateLLValueJSONArray.getDouble(0));
                    mLocationList.add(mLocation);
                }
                String[] mCurrentNameArray = mCurrentName.split("\\|");
                String mFZKey = mCurrentNameArray[0].split("HL")[0];
                if (!mReMap.containsKey(mFZKey)) {
                    mReMap.put(mFZKey, new HashMap<>());
                }
                mReMap.get(mFZKey).put(mCurrentName, mLocationList);
            }
        }catch (Exception e) {

        }finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                }catch (Exception e) {

                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }catch (Exception e) {

                }
            }
        }
        return mReMap;
    }

    /**
     *  获取每个光伏区多边形的经纬度坐标，存入Map中
     **/
    public static Map<String, List<Location>> ReadFZFileByIO(String mFilePath) {

        Map<String, List<Location>> mReMap = new HashMap<>();

        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;

        JSONObject mFeatureJSONObject = null;

        try {

            StringBuffer mStringBuffer = new StringBuffer();

            fileInputStream = new FileInputStream(new File(mFilePath));
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            byte[] bytes = new byte[1024];
            int mReadLength = -1;
            while ((mReadLength = bufferedInputStream.read(bytes, 0, 1024)) != -1) {
                if (mReadLength == 1024) {
                    mStringBuffer.append(new String(bytes));
                }else {
                    byte[] mBytes = new byte[mReadLength];
                    System.arraycopy(bytes, 0, mBytes, 0, mReadLength);
                    mStringBuffer.append(new String(mBytes));
                }
            }
            String mJSONStr = mStringBuffer.toString();
            JSONObject mJSONObject = JSONObject.parseObject(mJSONStr.replace("\t","").replace("\n", "")
                    .replace("\r", "").replace("\\s", ""));
            JSONArray mFeatureJSONArray = mJSONObject.getJSONArray("features");
            for (int index = 0; index < mFeatureJSONArray.size(); index++) {
                mFeatureJSONObject = mFeatureJSONArray.getJSONObject(index);
                JSONObject mPropertieJSONObject = mFeatureJSONObject.getJSONObject("properties");
                String mCurrentName = mPropertieJSONObject.getString("Name");
                JSONObject mGeometryJSONObject = mFeatureJSONObject.getJSONObject("geometry");
                JSONArray mCoordinateJSONArray = mGeometryJSONObject.getJSONArray("coordinates");
                JSONArray mCoordinateLLJSONArray = mCoordinateJSONArray.getJSONArray(0);
                List<Location> mLocationList = new ArrayList<>();
                for (int mIndex = 0; mIndex < mCoordinateLLJSONArray.size(); mIndex++) {
                    JSONArray mCoordinateLLValueJSONArray = mCoordinateLLJSONArray.getJSONArray(mIndex);
                    Location mLocation = new Location();
                    mLocation.setLon(mCoordinateLLValueJSONArray.getDouble(0));
                    mLocation.setLat(mCoordinateLLValueJSONArray.getDouble(1));
                    mLocationList.add(mLocation);
                }
                String mFZKey = mCurrentName.split("FZ")[1];
                mReMap.put(mFZKey, mLocationList);
            }
        }catch (Exception e) {

        }finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                }catch (Exception e) {

                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }catch (Exception e) {

                }
            }
        }
        return mReMap;
    }

    /**
     * 获取最新任务的红外图片地址
     **/
    public static List<String> getNewPhoto(String photoPath){
        // 获取最新修改的航线
//        File path = new File("/data/autoUpload/photo/");
//        File path = new File("C:\\Users\\KR0282\\Desktop\\photo");
        File path = new File(photoPath);
        File[] files = path.listFiles();
        File[] sort = fileSort(files);
        String missionName = sort[0].getName();
        log.info("最新修改的航线是：" + missionName);

        // 获取最新的架次
//        File record = new File("/data/autoUpload/photo/" + missionName);
        File record = new File(path.getPath() +"\\"+ missionName);
        File[] records = record.listFiles();
        File[] sort1 = fileSort(records);
        String recordName = sort1[0].getName();
        log.info("最新的架次是：" + recordName);

        // 获取最新架次里面的红外图片
        File photoFile = new File(record.getPath() + "\\" + recordName);
        File[] photos = photoFile.listFiles();
        List<String> photoList = new ArrayList<>();
        if (photos != null){
            for (File file : photos){
                String name = file.getName();
                if (name.contains("THRM.jpg") || name.contains("T.jpg")){
                    photoList.add("/nest/autoUpload/photo"+ "/" + missionName + "/" + recordName + "/" + name);
                }
            }
        }

        return photoList;
    }


    /**
     *  将文件按时间排序，最新的在前
     **/
    public static File[] fileSort(File[] files){
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File file1, File file2) {
                return (int)(file2.lastModified()-file1.lastModified());
            }
        });
        return files;
    }

    /**
     *  查询minio中最新目录
     **/
    public static NewFileBo getNewFilePath(){
        // 获取最新修改的航线
        File path = new File("/data/autoUpload/photo/");
//        File path = new File("C:\\Users\\KR0282\\Desktop\\photo");
//        File path = new File(photoPath);
        File[] files = path.listFiles();
        File[] sort = fileSort(files);
        String missionName = sort[0].getName();
        log.info("最新修改的航线是：" + missionName);

        // 获取最新的架次
//        File record = new File("/data/autoUpload/photo/" + missionName);
        File record = new File(path.getPath() +"/"+ missionName);
        File[] records = record.listFiles();
        String recordName ;
        // 文件大于一个才进行排序
        if (records.length > 1){
            File[] sort1 = fileSort(records);
            recordName = sort1[0].getName();
        }else {
            recordName = records[0].getName();
        }
        log.info("最新的架次是：" + recordName);
        NewFileBo newFileBo = new NewFileBo();
        newFileBo.setMissionId(Integer.valueOf(missionName));
        newFileBo.setRecordId(Integer.valueOf(recordName));
        newFileBo.setPath("/data/autoUpload/photo/"+ missionName + "/" + recordName);
//        newFileBo.setPath("C:\\Users\\KR0282\\Desktop\\photo\\"+ missionName + "\\" + recordName);
        return newFileBo;
    }

    /**
     *  读取读取resources目录下的文件
     **/
    public static String getContent(String filePath){
        String res = "";
        if(StringUtils.isEmpty(filePath)){
            log.info("文件路径不能为空");
            return res;
        }
        try {
            Resource resource = new ClassPathResource(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(resource.getStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String str = "";
            while((str=br.readLine())!=null) {
                sb.append(str);
            }
            res = sb.toString();
        } catch (Exception e) {
            log.info("读取文件{}时发生异常",filePath);
            e.printStackTrace();
        }
        return res;

    }

    // String Content = FileUtil.getContent("pv.json");

}
