package com.ruoyi.monitorInterface.inserctpests.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.monitorInterface.inserctpests.service.PlantDiseasesAndInsectPestsService;
import com.ruoyi.monitorInterface.sennor.api.API;
import com.ruoyi.util.FileLoadClient;
import com.ruoyi.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.http.HttpClient;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class PlantDiseasesAndInsectPestsServiceImpl implements PlantDiseasesAndInsectPestsService {

    private static final Logger log = LoggerFactory.getLogger(PlantDiseasesAndInsectPestsServiceImpl.class);

    @Resource
    private ConfigService configService;

    private String secretKey;
    private String userName;

    private static String INSECT_PESTS_URL = "";
    // TODO 部署需修改成线上地址
    private static String FILE_URL = "";

    public AjaxResult plantDiseasesAndInsectPestsMessageReceiver(String deviceNumber) {
        if (FILE_URL.equals("")){
            FILE_URL = configService.getKey("centerMonitorURL") + "centerMonitorFeign/upload";
        }
        if (INSECT_PESTS_URL.equals("")){
            INSECT_PESTS_URL = configService.getKey("insectPestsUrl");
        }
        secretKey = configService.getKey("insectToken");
        userName = configService.getKey("insectName");
        //先请求
        StringBuffer URI = new StringBuffer(configService.getKey("sennorInsectURL") + API.getInsectNewCollectionResult);
        URI.append("?token=").append(secretKey);
        URI.append("&userName=").append(userName);
        URI.append("&deviceNumber=").append(deviceNumber);
        String result = HttpRequest.post(URI.toString())
                .header("Content-Type", "application/json")
                .execute().body();
        log.info("plantDiseasesAndInsectPestsMessageReceiver 收到数据 ==> {}", result);

        //后推送
        JSONObject object;
        String res;
        try {
            object = JSONObject.parseObject(result);
            String oldTaggingImgUrl = object.getJSONObject("data").getString("oldTaggingImgUrl");
            String taggingImgUrl = object.getJSONObject("data").getString("taggingImgUrl");

            JSONObject img = img(oldTaggingImgUrl);
            object.getJSONObject("data").put("oldTaggingImgUrl", img.getJSONObject("data").getString("url"));
            JSONObject img2 = img(taggingImgUrl);
            object.getJSONObject("data").put("taggingImgUrl", img2.getJSONObject("data").getString("url"));

            System.out.println("--------------------------图片-----------------------------");
            System.out.println("oldTaggingImgUrl:" + img.getJSONObject("data").getString("url"));
            System.out.println("taggingImgUrl:" + img2.getJSONObject("data").getString("url"));
            System.out.println("-------------------------------------------------------------");
            if (object.get("state") != null && object.getString("state").equals("success")) {
                res = HttpRequest.post(configService.getKey("centerMonitorURL") + "device/saveInsectPestsDeviceData")
                        .header("Content-Type", "application/json")
                        .body(object.toJSONString())
                        .execute().body();
                log.info("数据推送成功! data ===> {} , result ===> {}", result, res);
                return AjaxResult.success("数据推送成功!", res);
            }
            return AjaxResult.error("数据推送失败!", result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据推送失败! data ===> {} , result ===> {}", result, e.getMessage());
            return AjaxResult.error("数据推送失败!", result);
        }
    }

    private JSONObject img(String oldTggingImgUrl) {
        String fileload = "";
        try {
            //定义一个URL对象
            URL url = new URL(INSECT_PESTS_URL + oldTggingImgUrl);
            //打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为10秒
            conn.setConnectTimeout(10 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = readInputStream(inStream);
            //new一个文件对象用来保存图片，默认保存当前工程根目录
            File imageFile = new File("InputStreamInfo.jpg");
            //创建输出流
            FileOutputStream outStream = new FileOutputStream(imageFile);
            //写入数据
            outStream.write(data);
            //关闭输出流
            outStream.close();
            fileload = FileLoadClient.fileload(FILE_URL, imageFile);

        } catch (Exception e) {

        }
        JSONObject parseObject = JSONObject.parseObject(fileload);
        return parseObject;
    }

    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    @Override
    public JSONArray getDevideCodeMapByType(String types) {
        //先请求
        StringBuffer URI = new StringBuffer(configService.getKey("centerMonitorURL") + "device/getDevideCodeMapByTypes");
        URI.append("?types=").append(types);
        String result = HttpRequest.get(URI.toString())
                .header("Content-Type", "application/json")
                .execute().body();
        //后推送
        JSONObject object;
        try {
            object = JSONObject.parseObject(result);
            if (object.getInteger("code") == 200) {
                return object.getJSONArray("data");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("服务端数据校验失败! data ===> {} , result ===> {}", result, e.getMessage());
        }
        return new JSONArray();
    }
}
