
package com.example.ghjgpython.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.ghjgpython.dao.Photo;
import com.example.ghjgpython.dao.PhotoByType;
import com.example.ghjgpython.enu.TypeEnum;
import com.example.ghjgpython.mapper.ShipRecognitionMapper;
import com.example.ghjgpython.service.ShipRecognitionService;
import com.shanghaigeography.Util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@SuppressWarnings("DuplicatedCode")
@Service
@Slf4j
public class ShipRecognitionServiceImpl implements ShipRecognitionService {
    private static final String finalFilePathCover = "E:\\javaPyPhoto\\cover\\";
    private static final String finalFilePathCoverType = "E:\\javaPyPhoto\\type\\";
    private static final String finalFilePathType = "E:\\javaPyPhoto\\";
    private static final String finalFilePathLifeJacket = "E:\\javaPyPhoto\\lifeJacket\\";

    private static final String finalNewCoverResult = "E:\\javaPyPhoto\\newCover\\";

    private static final String pythonUrl = "http://192.168.213.205:5000/photo";
    private static final String pythonUrlNew = "http://192.168.213.205:5001/photo-test";
    private static final String pythonLifeJacketUrl = "172.16.58.199:5000/lifejacket";
    @Resource
    private ShipRecognitionMapper shipRecognitionMapper;

    public String getRecognitionByDates(Date startDate, Date endDate) {
        List photos = shipRecognitionMapper.getPhotos(null, startDate, endDate);
        analysisPhotoAndDownLoad(photos);
        return "success";
    }

    public String getRecognitionByDate(Date toDate) {
        List photos = shipRecognitionMapper.getPhotos(toDate, null, null);
        analysisPhotoAndDownLoad(photos);
        return "success";
    }

    @Override
    public String getCoverDatesAndType(Date startDate, Date endDate) {
        List<PhotoByType> photo = shipRecognitionMapper.getPhotoNew(startDate, endDate, null);
        analysisPhotoAndDownLoad2(photo);
        return "success";
    }

    private static final String lifeJacketDefaultPath = "D:\\LifeJacket\\";

    @Override
    public String getLifeJacket(String path, String dir) throws IOException {
        if (dir == null && path != null) {
            //只分析默认文件下特定图
            File file = new File(lifeJacketDefaultPath + path);
            if (!file.exists()) {
                return "默认文件夹下:" + lifeJacketDefaultPath + "文件不存在";
            }
            doLifeJacket(file);
            return "完成";
        }
        if (dir == null) {
            return "参数丢失";
        }
        if (path == null) {
            //分析文件夹下所有的图片
            File file = new File(dir);
            if (!file.exists()) {
                return "指定文件夹不存在";
            }
            getDirAllPic(file);
            return "完成";
        }
        //分析指定文件夹下指定图片
        File file = new File(dir + "\\" + path);
        if (!file.exists()) {
            return "指定文件夹下文件不存在";
        }
        doLifeJacket(file);
        return "完成";
    }

    @Override
    public String getCoverPictureByDatesOnDay(Date startDate, Date endDate) {
        List<PhotoByType> photos = shipRecognitionMapper.getDayPhoto(startDate, endDate);
        analysisPhotoAndDownLoad2(photos);
        return "success";
    }

    @Override
    public String getnewCoverByDates(Date startDate, Date endDate) throws Exception {
        List<PhotoByType> photos = shipRecognitionMapper.getDayPhoto(startDate, endDate);
        newCoverAnalysisAndDownLoad(photos);
        return "success";
    }

    @Override
    public String getPhoto(List<String> list) {
        List<PhotoByType> photoByTypes = new ArrayList<>();
        for (String string : list) {
            PhotoByType photo =   shipRecognitionMapper.getNeedPhoto(string);
            photoByTypes.add(photo);
        }
        analysisPhotoAndDownLoad2(photoByTypes);
        return "success";
    }

    private void newCoverAnalysisAndDownLoad(List<PhotoByType> photos) throws Exception {
        if (!photos.isEmpty()) {
            for (PhotoByType photo : photos) {
                String ori = "";
                for (String s : photo.getP0Picture().split(";")) {
                    if (s.contains("P1")) {
                        ori = s;
                        break;
                    }
                }
                if (StringUtils.isNotBlank(ori)) {
                    File file = new File(ori);
                    String encode = encodeBase64File(file);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("file", encode);
                    HttpResponse httpResponse = HttpUtil.createPost(pythonUrlNew).body(jsonObject.toString()).setConnectionTimeout(5000).setReadTimeout(50000).executeAsync();
                    if (httpResponse.isOk()) {
                        String body = httpResponse.body();
                        //System.out.println(body);
                        JSONObject response = JSONObject.parseObject(body);
                        if (response.get("image_data") != null && StringUtils.isNotBlank(response.get("image_data").toString())) {
                            HashMap result = JSONObject.parseArray(response.get("result").toString(),HashMap.class).get(0);
                            String resultClass = result.get("class").toString();
                            File targetDir = new File(finalNewCoverResult + resultClass + "\\" + photo.getTime());
                            if (!targetDir.exists()) {
                                targetDir.mkdirs();
                            }
                            FileOutputStream fileOutputStream = new FileOutputStream(targetDir + "\\" + UUID.randomUUID().toString().split("-")[0] + "-python" + ".jpg");
                            byte bytes[] = Base64.decode(response.get("image_data").toString());
                            if (bytes.length != 0) {
                                fileOutputStream.write(bytes, 0, bytes.length);
                                fileOutputStream.flush();
                                fileOutputStream.close();
                            }
                            FileUtils.copyFile(file, new File(targetDir + "\\" + UUID.randomUUID().toString().split("-")[0] + "-originType" + photo.getTypeClass() + ".jpg"));
                        }
                    }
                }
            }
        }
    }

    private void getDirAllPic(File file) throws IOException {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        getDirAllPic(file1);
                    } else {
                        doLifeJacket(file1);
                    }
                }
            }
        }
    }

    private static void doLifeJacket(File file) throws IOException {
        String fileEncode = Base64.encode(file);
        JSONObject object = new JSONObject();
        object.put("file", fileEncode);
        //log.warn(fileEncode);
        String body = HttpUtil.createPost(pythonLifeJacketUrl).body(object.toString()).setConnectionTimeout(30000).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.get("image_data") != null) {
            //正常了
            JSONArray result = JSONArray.parseArray(jsonObject.get("result").toString());
            JSONObject parsed = JSONObject.parseObject(result.get(0).toString());
            if (parsed.get("is_wear") != null) {
                //穿
                String path = finalFilePathLifeJacket + "common" + "//" + System.currentTimeMillis();
                File file1 = new File(path);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(path + "\\" + UUID.randomUUID().toString().split("-")[0] + "-python" + ".jpg");
                byte bytes[] = Base64.decode(jsonObject.get("image_data").toString());
                if (bytes.length != 0) {
                    fileOutputStream.write(bytes, 0, bytes.length);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                File fileO = new File(path + "\\" + UUID.randomUUID().toString().split("-")[0] + "-org.jpg");
                FileCopyUtils.copy(file, fileO);
            } else {
                //没有人
                String noPersonPath = finalFilePathLifeJacket + "\\noPeople";
                File file2 = new File(noPersonPath);
                if (!file2.exists()) {
                    file2.mkdirs();
                }
                File file3 = new File(noPersonPath + "\\" + UUID.randomUUID().toString().split("-")[0] + "-org.jpg");
                FileCopyUtils.copy(file, file3);
            }
        } else {
            //这里是异常情况
            String exceptionPath = finalFilePathLifeJacket + "\\exception";
            File file2 = new File(exceptionPath);
            if (!file2.exists()) {
                file2.mkdirs();
            }
            File file3 = new File(exceptionPath + "\\" + UUID.randomUUID().toString().split("-")[0] + "exception.jpg");
            FileCopyUtils.copy(file, file3);
        }


    }

    public String getTest() {
        return shipRecognitionMapper.getTest();
    }

    @Override
    public String downloadPicture(Date startDate, Date endDate, Integer type) {
        List<PhotoByType> flags = shipRecognitionMapper.getFlagPhoto(startDate, endDate, type);
        downLoadFlagPicture(flags, type);
        return "success";
    }

    @Override
    public String downLoadPic(String dir, String fileLike) throws IOException {
        File file = new File(finalFilePathType + "\\" + fileLike);
        if (!file.exists()) {
            file.mkdirs();
        }
        downLoad(dir, fileLike, file.getAbsolutePath());
        return null;
    }

    @Override
    public String getPicByDate(String dir, String fileLike, Date startDate, Date endDate, Integer startHour, Integer endHour) {
        String fDir = finalFilePathType + DateUtils.dateToString(new Date(), "yyyy-MM-dd-HH-mm-SS") + "\\" + fileLike;
        File file = new File(fDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        while (startDate.compareTo(endDate) <= 0) {
            for (int i = startHour; i <= endHour; i++) {
                String targetDir = dir + "\\" + DateUtils.dateToString(startDate, "yyyyMMdd") + "\\" + (i < 10 ? "0" + i : i);
                downLoad(targetDir, fileLike, file.getAbsolutePath());
            }
            startDate = DateUtils.dayAddNum(startDate, 1);
        }
        return "success";
    }

    private void downLoad(String dir, String fileLike, String targetDir) {
        File file = new File(dir);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    if (file1.isFile() && file1.getName().contains(fileLike)) {
                        File file2 = new File(targetDir + "\\" + UUID.randomUUID().toString().split("-")[0] + "." + file1.getPath().split("\\.")[file1.getPath().split("\\.").length - 1]);
                        try {
                            FileCopyUtils.copy(file1, file2);
                        } catch (IOException e) {
                            log.error("文件拷贝出现异常" + e.getMessage());
                        }
                    }
                    downLoad(file1.getAbsolutePath(), fileLike, targetDir);
                }
            }
        }
    }

    private void downLoadFlagPicture(List<PhotoByType> flags, Integer type) {
        for (PhotoByType flag : flags) {
            String dir = "";
            if (type == null) {
                dir = finalFilePathType + TypeEnum.ALL.getTypeName();
            } else {
                for (TypeEnum value : TypeEnum.values()) {
                    if (type.equals(value.getTypeCode())) {
                        dir = finalFilePathType + value.getTypeName();
                        break;
                    }
                }
            }
            File file = new File(dir);
            if (!file.exists())
                file.mkdirs();
            String[] split = flag.getPhotoName().split(";");
            for (String string : split) {
                if (string.contains("P1")) {
                    File originalPic = new File(string);
                    File newFile = new File(dir + "\\" + flag.getTime() + "-" + UUID.randomUUID().toString().split("-")[0] + "-" + flag.getCoverageRatio() + ".jpg");
                    try {
                        FileCopyUtils.copy(originalPic, newFile);
                    } catch (IOException e) {
                        log.error("exception    " + e.getMessage());
                    }
                    break;
                }
            }
        }
    }

    private void analysisPhotoAndDownLoad(List photos) {
        StringBuilder errorStr = new StringBuilder();
        for (Iterator iterator = photos.iterator(); iterator.hasNext(); ) {
            Photo photo = (Photo) iterator.next();
            File oldCogPhoto = new File(photo.getOldCogPicture());
            String dir = finalFilePathCover + photo.getTypeClass() + "\\" + photo.getName() + photo.getTime();
            File file = new File(dir);
            if (!file.exists())
                file.mkdirs();
            String p0Pic = "";
            String as[] = photo.getP0Picture().split(";");
            int i = as.length;
            int j = 0;
            do {
                if (j >= i)
                    break;
                String s = as[j];
                if (s.contains("P1")) {
                    p0Pic = s;
                    break;
                }
                j++;
            } while (true);
            if (StringUtils.isNotBlank(p0Pic)) {
                File p0Photo = new File(p0Pic);
                try {
                    String string = encodeBase64File(p0Photo);
                    //log.warn("base64编码后的内容---    " + string);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("file", string);
                    HttpResponse httpResponse = HttpUtil.createPost(pythonUrl).body(jsonObject.toString()).setConnectionTimeout(5000).setReadTimeout(50000).executeAsync();
                    if (httpResponse.isOk()) {
                        JSONObject object = JSONObject.parseObject(httpResponse.body());
                        if (StringUtils.isNotBlank(object.get("image_data").toString())) {
                            FileOutputStream fileOutputStream = new FileOutputStream(dir + "\\" + UUID.randomUUID().toString().split("-")[0] + "-python" + ".jpg");
                            byte bytes[] = Base64.decode(object.get("image_data").toString());
                            if (bytes.length != 0) {
                                fileOutputStream.write(bytes, 0, bytes.length);
                                fileOutputStream.flush();
                                fileOutputStream.close();
                            }
                        }
                    }
                } catch (Exception e) {
                    errorStr.append("||||").append(e.getMessage());
                }
                File p0Picture = new File(dir + "\\" + UUID.randomUUID().toString().split("-")[0] + "-ORIGINAL.jpg");
                try {
                    FileCopyUtils.copy(p0Photo, p0Picture);
                } catch (IOException e) {
                    errorStr.append("|||||").append(e.getMessage());
                }
            }
            File oldCPicture = new File(dir + "\\" + UUID.randomUUID().toString().split("-")[0] + "-OLD-" + "." + photo.getOldCogPicture().split("\\.")[1]);
            try {
                FileCopyUtils.copy(oldCogPhoto, oldCPicture);
            } catch (Exception e) {
                errorStr.append(e.getMessage());
            }
        }

        if (StringUtils.isNotBlank(errorStr.toString()))
            log.error(errorStr.toString());
    }


    private void analysisPhotoAndDownLoad2(List<PhotoByType> photos) {
        StringBuilder errorStr = new StringBuilder();
        for (Iterator iterator = photos.iterator(); iterator.hasNext(); ) {
            PhotoByType photo = (PhotoByType) iterator.next();
            String dir = finalFilePathCoverType + "\\" + photo.getTime();
            File file = new File(dir);
            if (!file.exists())
                file.mkdirs();
            String p0Pic = "";
            String[] as = photo.getP0Picture().split(";");
            int i = as.length;
            int j = 0;
            do {
                if (j >= i)
                    break;
                String s = as[j];
                if (s.contains("P1")) {
                    p0Pic = s;
                    break;
                }
                j++;
            } while (true);
            if (StringUtils.isNotBlank(p0Pic)) {
                File p0Photo = new File(p0Pic);
                try {
                    String string = encodeBase64File(p0Photo);
                    //log.warn("base64编码后的内容---    " + string);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("file", string);
                    HttpResponse httpResponse = HttpUtil.createPost(pythonUrl).body(jsonObject.toString()).setConnectionTimeout(5000).setReadTimeout(50000).executeAsync();
//                    if (httpResponse.isOk()) {
//
//                        JSONObject object = JSONObject.parseObject(httpResponse.body());
//                        if (StringUtils.isNotBlank(object.get("image_data").toString())) {
//                            FileOutputStream fileOutputStream = new FileOutputStream(dir + "\\" + UUID.randomUUID().toString().split("-")[0] + photo.getEventCode() + "-python" + ".jpg");
//                            byte bytes[] = Base64.decode(object.get("image_data").toString());
//                            if (bytes.length != 0) {
//                                fileOutputStream.write(bytes, 0, bytes.length);
//                                fileOutputStream.flush();
//                                fileOutputStream.close();
//                            }
//                        }
//                    }
                    log.error("httpResponse.body{}" + photo.getEventCode(),httpResponse.body());
                } catch (Exception e) {
                    errorStr.append("||||").append(e.getMessage());
                }
//                File p0Picture = new File(dir + "\\" + UUID.randomUUID().toString().split("-")[0] + "-ORIGINAL.jpg");
//                try {
//                    FileCopyUtils.copy(p0Photo, p0Picture);
//                } catch (IOException e) {
//                    errorStr.append("|||||").append(e.getMessage());
//                }
            }
        }

        if (StringUtils.isNotBlank(errorStr.toString()))
            log.error(errorStr.toString());
    }

    public static String encodeBase64File(File file)
            throws Exception {
        FileInputStream inputFile = new FileInputStream(file);
        byte buffer[] = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encode(buffer);
    }


}
