package com.inspect.ivs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.domain.Response;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.ivs.base.feign.view.SipbDeviceListView;
import com.inspect.ivs.constant.IvsConst;
import com.inspect.ivs.domain.Temp;
import com.inspect.ivs.domain.TempConfiguration;
import com.inspect.ivs.service.IvsCommonService;
import com.inspect.ivs.service.IvsResourceRetryableDelegate;
import com.inspect.ivs.util.UriUtils;
import com.inspect.ivs.view.IvsPlatformSnapshotView;
import com.inspect.ivs.view.IvsSnapshotView;
import com.inspect.ivs.vo.IvsChanSnapVo;
import com.inspect.ivs.vo.IvsDevChanListVo;
import com.inspect.ivs.vo.IvsDevChanSnapVo;

import java.io.*;
import java.util.*;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping({"/api/v1/device"})
public class IvsDeviceController {
    private static final Logger log = LoggerFactory.getLogger(IvsDeviceController.class);

    @Value("${spring.profiles.active}")
    private String activeProfile;
    @Value("${ivs.version:3800}")
    private String version;
    @Value("${ivs.address}")
    private String address;

    @Value("${task.test-mode:false}")
    private boolean testMode;

    private final IvsCommonService ivsCommonService;

    @Resource
    private IvsResourceRetryableDelegate ivsResourceRetryableDelegate;

    public IvsDeviceController(IvsCommonService ivsCommonService) {
        this.ivsCommonService = ivsCommonService;
    }


    /**
     * 设置红外规则
     */
    @PostMapping("/setHwConfig")
    public Response setHwConfig(@RequestBody TempConfiguration tempConfiguration) throws Exception {
        Temp temp = new Temp();
        temp.setCameraCode(tempConfiguration.getCameraCode());
        JSONObject config = getConfig(temp);

        JSONArray radiometryRuleExListOrginl = config.getJSONArray("radiometryRuleExList");
        JSONArray radiometryRuleListOrginl = config.getJSONArray("radiometryRuleList");


        log.info("[infra_1800] =======tempConfiguration: {}", tempConfiguration);
        JSONObject json = new JSONObject();
        JSONObject configItem = new JSONObject();
        List<Map<String, Object>> alarmSettingListEx = new ArrayList<>();
        Map<String, Object> alarmSettings = new HashMap<>();
        alarmSettings.put("preDuration", 0);
        alarmSettings.put("preThreshold", 22);
        alarmSettingListEx.add(alarmSettings);

        //设置blockBodyTemp
        List<Map<String, Object>> radiometryRuleExList = new ArrayList<>();
        Map<String, Object> ruleItem = new HashMap<>();
        ruleItem.put("blockBodyTemp", 0);//写死
        ruleItem.put("reflectedTemp", 0);//写死
        ruleItem.put("usefReflectedTemp", false);//写死
        ruleItem.put("alarmSettingList", alarmSettingListEx);//写死
        radiometryRuleExList.add(ruleItem);
        // 遍历 FastJSON 的 JSONArray
        if (StringUtils.isNotNull(radiometryRuleExListOrginl)) {
            for (Object obj : radiometryRuleExListOrginl) {
                if (obj instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) obj;
                    Map<String, Object> map = new HashMap<>();
                    // FastJSON 的 JSONObject 可以直接转换为 Map
                    map = jsonObject.getInnerMap(); // 直接获取内部 Map
                    // 或者逐个处理 key-value（更安全）
                    for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                        map.put(entry.getKey(), entry.getValue());
                    }
                    radiometryRuleExList.add(map);
                } else if (obj instanceof String) {
                    // 处理基本类型（如果 JSONArray 中包含字符串等）
                    Map<String, Object> map = Collections.singletonMap("value", obj);
                    radiometryRuleExList.add(map);
                }
            }
        }

        // 设置 configItem
        configItem.put("radiometryRuleExList", radiometryRuleExList);
        List<Map<String, Object>> radiometryRuleList = new ArrayList<>();
        JSONObject radiometryRule = new JSONObject();
        Map<String, Object> localParam = new HashMap<>();
        List<Map<String, Object>> alarmSettingList = new ArrayList<>();
        Map<String, Object> alarmSetting = new HashMap<>();
        radiometryRule.put("areaSubType", 1);//区域测温的子类型 1：矩形
        radiometryRule.put("enable", 1);//使能
        radiometryRule.put("meterType", 3);//区域
        radiometryRule.put("presetId", tempConfiguration.getPresetId());//传 预置位id
        radiometryRule.put("ruleId", tempConfiguration.getRuleId());//自己取最大没人用的
        radiometryRule.put("samplePeriod", 3);//
        radiometryRule.put("name", tempConfiguration.getName());//传 定义一个名字
        //设置localParam
        localParam.put("enable", 1);
        localParam.put("objectDistance", 4);
        localParam.put("objectEmissivity", 0.9700000286102295);
        localParam.put("refalectedTemp", 25);
        //设置alarmSettingList
        alarmSetting.put("alarmCondition", 1);
        alarmSetting.put("duration", 30);
        alarmSetting.put("enable", 1);
        alarmSetting.put("hysteresis", 0.10000000149011612);
        alarmSetting.put("id", 0);
        alarmSetting.put("resultType", 2);
        alarmSetting.put("threshold", 20.1);
        alarmSettingList.add(alarmSetting);
        radiometryRule.put("alarmSettingList", alarmSettingList);
        radiometryRule.put("localParam", localParam);
        radiometryRule.put("polygonList", tempConfiguration.getPolygonList());
        radiometryRuleList.add(radiometryRule);

        // 遍历 FastJSON 的 JSONArray
        if (StringUtils.isNotNull(radiometryRuleListOrginl)) {
            for (Object obj : radiometryRuleListOrginl) {
                if (obj instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) obj;
                    Map<String, Object> map = new HashMap<>();
                    // FastJSON 的 JSONObject 可以直接转换为 Map
                    map = jsonObject.getInnerMap(); // 直接获取内部 Map
                    // 或者逐个处理 key-value（更安全）
                    for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                        map.put(entry.getKey(), entry.getValue());
                    }
                    radiometryRuleList.add(map);
                } else if (obj instanceof String) {
                    // 处理基本类型（如果 JSONArray 中包含字符串等）
                    Map<String, Object> map = Collections.singletonMap("value", obj);
                    radiometryRuleList.add(map);
                }
            }
        }

        configItem.put("radiometryRuleList", radiometryRuleList);
        json.put("deviceCode", tempConfiguration.getCameraCode().split("#")[0]);//传
        json.put("configType", 500);//写死500
        json.put("configItem", configItem);
        System.out.println(json);
        String message = JSON.toJSONString(json);
        String resp = ivsCommonService.sendSSLPostString(address + "/device/setdeviceconfig", message);
        JSONObject jsonObject = JSON.parseObject(resp);
        String resultCode = jsonObject.getString("resultCode");
        if (resultCode.equals("0")) {
            return Response.ok();
        }
        return Response.fail();
    }


    /**
     * 获取红外数据
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/temper")
    public String temper(@RequestBody Temp temp) {
        log.info("[infrared_1800] 获取红外温度 temper param: {}", temp);
        String cameraCode = temp.getCameraCode().split("#")[0]; //cameraCode摄像机编码
        int presetId = temp.getPresetId();  //预设位ID
        int ruleId = temp.getRuleId(); //规则ID 暂时写死取12就行
//        int meterType = temp.getMeterType();
        String requestMsg = "presetId=" + presetId + "&" + "ruleId=" + ruleId + "&" + "meterType=" + 3;
        //发送请求
        String resp = ivsCommonService.sendsslGetCookie(address + "/device/radiometry-temper/" + cameraCode, requestMsg, "UTF-8");
        log.info("获取红外温度: {}", resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        String resultCode = jsonObject.getString("resultCode");
        String temperMax = "";
        if (resultCode.equals("0")) {
            JSONObject radiometryInfo = (JSONObject) jsonObject.get("radiometryInfo");
            temperMax = radiometryInfo.getString("temperMax");
            return temperMax;
        }
        return "0";
    }

    /**
     * 获取原始规则
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/getConfig")
    public JSONObject getConfig(@RequestBody Temp temp) {
        log.info("[infrared_1800] 获取红外温度 temper param: {}", temp);
        String cameraCode = temp.getCameraCode().split("#")[0];
        String nvrcode = temp.getCameraCode().split("#")[1];
        String requestMsg = "";
        //发送请求
        String resp = ivsCommonService.sendsslGetCookie(address + "/device/deviceconfig/500/" + cameraCode + "/" + nvrcode, requestMsg, "UTF-8");
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject configItem = jsonObject.getJSONObject("configItem");
        log.info("configItem: {}", configItem);
        return configItem;
//        JSONArray radiometryRuleExList = configItem.getJSONArray("radiometryRuleExList");
//        JSONArray radiometryRuleList = configItem.getJSONArray("radiometryRuleList");
//        return "0";
    }

//    @GetMapping({"channelsnap"})
//    public ResponseEntity<InputStreamResource> channelSnap(IvsDevChanSnapVo ivsDevChanSnapVo) throws Exception {
//        if (version.equals("1800")) {
//            byte[] bytes = Ivs1800channelSnap(ivsDevChanSnapVo);
////            String filePath = "/home/1.JPG"; // 替换为你想保存图片的本地路径
////            try (FileOutputStream fos = new FileOutputStream(filePath)) {
////                fos.write(bytes);
////                log.info("图片已成功保存到本地：" + filePath);
////            } catch (IOException e) {
////                e.printStackTrace();
////                log.info("保存图片时出现错误：" + e.getMessage());
////            }
////            byte[] bytes = readStream(content);
//            InputStream inputStream = new ByteArrayInputStream(bytes);
//            return ResponseEntity.ok().body(new InputStreamResource(inputStream));
//        } else {
//            int index = 0;
//
//            final int TRY_TIMES = 1;
//            final long mDelay = 3000;
//            while (index < TRY_TIMES) {
//                log.info(com.inspect.base.core.constant.Color.MAGENTA + "[IVS] SNAPSHOT: {}, TRY TIMES: {}" + com.inspect.base.core.constant.Color.END, ivsDevChanSnapVo.getCameraCode(), index);
//                try {
//                    IvsSnapshotView ivsSnapshotView = ivsCommonService.get(UriUtils.parse(IvsConst.URI_PLATFORM_SNAPSHOT, ivsDevChanSnapVo), IvsSnapshotView.class);
//                    IvsChanSnapVo ivsChanSnapVo = new IvsChanSnapVo(ivsDevChanSnapVo.getCameraCode(),
//                            ivsDevChanSnapVo.getDomainCode(),
//                            ivsSnapshotView.getTaskID()
//                    );
//
//                    //if ("prod".equals(activeProfile)) {
//                    if(!testMode) {
//                        log.info("[IVS] prod env get stream delay 9000ms");
//                        Thread.sleep(9000L);
//                    } else {
//                        Thread.sleep(2000L);
//                    }
//
//                    IvsPlatformSnapshotView snapShotView = ivsCommonService.postJson(
//                            ivsChanSnapVo,
//                            IvsConst.URI_SNAPSHOT_LIST,
//                            IvsPlatformSnapshotView.class);
//                    if (snapShotView != null && snapShotView.getSnapshotInfoList() != null
//                            && snapShotView.getSnapshotInfoList().getSnapshotInfos() != null
//                            && !snapShotView.getSnapshotInfoList().getSnapshotInfos().isEmpty()) {
//                        String cameraCode = snapShotView.getSnapshotInfoList().getSnapshotInfos().get(0).getCameraCode();
//                        String pictureUrl = snapShotView.getSnapshotInfoList().getSnapshotInfos().get(0).getPictureUrl();
//                        log.info(com.inspect.base.core.constant.Color.MAGENTA + "[IVS] TRYS: {}, SNAPSHOT cameraCode: {}, pictureUrl: {}" + com.inspect.base.core.constant.Color.END, index, cameraCode, pictureUrl);
//                        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//                            HttpResponse httpResponse = httpClient.execute(new HttpGet(pictureUrl));
//                            InputStream content = httpResponse.getEntity().getContent();
//                            byte[] bytes = readStream(content);
//                            InputStream inputStream = new ByteArrayInputStream(bytes);
//                            log.info(com.inspect.base.core.constant.Color.MAGENTA + "[IVS] tries: {}, pictureUrl: {}, size: {} END" + com.inspect.base.core.constant.Color.END, index, pictureUrl, bytes.length);
//
//                            if(bytes.length > 0) {
//                                return ResponseEntity.ok().body(new InputStreamResource(inputStream));
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                    log.warn(com.inspect.base.core.constant.Color.MAGENTA + "[IVS] SNAPSHOT EXCEPTION: {}" + com.inspect.base.core.constant.Color.END, e.getMessage());
//                }
//
//                index++;
//                Thread.sleep(mDelay);
//            }
//
//            log.info(com.inspect.base.core.constant.Color.RED + "[IVS] GET PIC FAIL cameraCode: {}, channel: {}, domainCode: {}" + com.inspect.base.core.constant.Color.END,
//                    ivsDevChanSnapVo.getCameraCode(),
//                    ivsDevChanSnapVo.getChannel(),
//                    ivsDevChanSnapVo.getDomainCode()
//            );
//            return ResponseEntity.ok().body(new InputStreamResource(generateErrorImage()));
//        }
//    }

    private void delayBeforeGetPicture() {
        if (!testMode) {
            log.info("[IVS] prod env get stream delay 9000ms");
            try {
                Thread.sleep(9000L);
            } catch (Exception e) {

            }
        } else {
            try {
                log.info("[IVS] test env get stream delay 2000ms");
                Thread.sleep(2000L);
            } catch (Exception e) {
            }
        }
    }

    @GetMapping({"channelsnap"})
    public ResponseEntity<InputStreamResource> channelSnap(IvsDevChanSnapVo ivsDevChanSnapVo) {
        if (version.equals("1800")) {
            try {
                byte[] bytes = getIvs1800ChannelSnapBuffer(ivsDevChanSnapVo);
                InputStream inputStream = new ByteArrayInputStream(bytes);
                return ResponseEntity.ok().body(new InputStreamResource(inputStream));
            } catch (Exception e) {
                return ResponseEntity.ok().body(new InputStreamResource(ivsResourceRetryableDelegate.generateErrorImage()));
            }
        } else {
            try {
                final String presetName = ivsDevChanSnapVo.getName();
                final String patrolPointId = ivsDevChanSnapVo.getId();
                final String uuid = ivsResourceRetryableDelegate.getLabel();
                log.info(com.inspect.base.core.constant.Color.MAGENTA + "[IVS] CHANNEL_SNAPSHOT: {}" + com.inspect.base.core.constant.Color.END, ivsDevChanSnapVo.getCameraCode());
                IvsSnapshotView ivsSnapshotView;
                ivsDevChanSnapVo.setUUID(uuid);
                ivsSnapshotView = ivsResourceRetryableDelegate.getSnapshotRetryable(ivsDevChanSnapVo);
                if (ivsSnapshotView == null) {
                    log.info("URI_PLATFORM_SNAPSHOT FROM RECOVER!!!");
                    return ResponseEntity.ok().body(new InputStreamResource(ivsResourceRetryableDelegate.generateErrorImage()));
                }

                // 上面刚刚向摄像机发送了拍照指令, 需要给摄像机留出拍照时间
                delayBeforeGetPicture();

                IvsPlatformSnapshotView snapShotView;
                IvsChanSnapVo ivsChanSnapVo = new IvsChanSnapVo();
                ivsChanSnapVo.setUUID(uuid);
                ivsChanSnapVo.setName(presetName);
                ivsChanSnapVo.setId(patrolPointId);
                ivsChanSnapVo.setCameraCode(ivsDevChanSnapVo.getCameraCode());
                ivsChanSnapVo.setDomainCode(ivsDevChanSnapVo.getDomainCode());
                ivsChanSnapVo.setTaskID(ivsSnapshotView.getTaskID());
                ivsChanSnapVo.setHost(ivsDevChanSnapVo.getHost());
                ivsChanSnapVo.setPort(ivsDevChanSnapVo.getPort());
                ivsChanSnapVo.setAddress(ivsDevChanSnapVo.getAddress());
                ivsChanSnapVo.setUsername(ivsDevChanSnapVo.getUsername());
                ivsChanSnapVo.setPassword(ivsDevChanSnapVo.getPassword());
                snapShotView = ivsResourceRetryableDelegate.getSnapshotListRetryable(ivsChanSnapVo);
                if (snapShotView == null) {
                    log.info("URI_SNAPSHOT_LIST FROM RECOVER!!!");
                    return ResponseEntity.ok().body(new InputStreamResource(ivsResourceRetryableDelegate.generateErrorImage()));
                }

                String cameraCode = snapShotView.getSnapshotInfoList().getSnapshotInfos().get(0).getCameraCode();
                String pictureUrl = snapShotView.getSnapshotInfoList().getSnapshotInfos().get(0).getPictureUrl();
                log.info(com.inspect.base.core.constant.Color.MAGENTA + "[IVS] SNAPSHOT cameraCode: {}, pictureUrl: {}" + com.inspect.base.core.constant.Color.END, cameraCode, pictureUrl);
                return ivsResourceRetryableDelegate.downloadPictureRetryable(uuid, pictureUrl);
            } catch (Exception e) {
                log.info("do not know where is the exception: ", e);
                return ResponseEntity.ok().body(new InputStreamResource(ivsResourceRetryableDelegate.generateErrorImage()));
            }
        }
    }

//    public byte[] readStream(InputStream inStream) throws Exception {
//        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len;
//        while ((len = inStream.read(buffer)) != -1) {
//            outStream.write(buffer, 0, len);
//        }
//        outStream.close();
//        inStream.close();
//        return outStream.toByteArray();
//    }


    public byte[] getIvs1800ChannelSnapBuffer(IvsDevChanSnapVo ivsDevChanSnapVo) throws Exception {
        log.info("++++++++++++++++++++++++执行1800channelsnap截图接口++++++++++++++++++++++++++++++");
        String url = address + "/snapshot/manualsnapshot";
        Map<String, Object> controlMap = new HashMap<>();
        controlMap.put("cameraCode", ivsDevChanSnapVo.getCameraCode());
        String requestMsg = JSON.toJSONString(controlMap);
//        byte[] bytes = ivsCommonService.sendSSLPost(url, requestMsg);
//        log.info("++++++++++++++++++++++++执行1800channelsnap截图接口++++++++++++++++++++++++++++++ :{}"+bytes);
        return ivsCommonService.sendSSLPost(url, requestMsg);
    }


//    @GetMapping({"channelsnap"})
//    public Response channelSnap(IvsDevChanSnapVo sipbDeviceChannelSnapVo, HttpServletResponse httpServletResponse) throws Exception {
//        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
//
//        try {
//            log.info("==================device-channelsnap-sipbDeviceChannelSnapVo:{}", sipbDeviceChannelSnapVo);
//            IvsSnapshotView ivsSnapshotView = (IvsSnapshotView)this.ivsCommonService.get(UriUtils.parse("/platform/platformSnapshot/{cameraCode}/{domainCode}", sipbDeviceChannelSnapVo), IvsSnapshotView.class);
//            IvsChanSnapVo ivsChannelSnapVo = new IvsChanSnapVo(sipbDeviceChannelSnapVo.getCameraCode(), sipbDeviceChannelSnapVo.getDomainCode(), ivsSnapshotView.getTaskID());
//            log.info("==================device-channelsnap-ivsChannelSnapVo:{}", ivsChannelSnapVo);
//            int index = 0;
//
//            while(index != 10) {
//                Thread.sleep(9000L);
//                ++index;
//                IvsPlatformSnapshotView ivsPlatformSnapshotView = null;
//
//                try {
//                    ivsPlatformSnapshotView = (IvsPlatformSnapshotView)this.ivsCommonService.postJson(ivsChannelSnapVo, "/platform/snapshotList", IvsPlatformSnapshotView.class);
//                } catch (Exception var17) {
//                    log.error("图片未获取到...");
//                }
//
//                log.info("==================device-channelsnap-ivsPlatformSnapshotView:{}", ivsPlatformSnapshotView);
//                if(ivsPlatformSnapshotView.getSnapshotInfoList().getSnapshotInfos().size() > 0) {
//                    String pictureUrl = ((IvsPlatformSnapshotView.SnapshotInfo)ivsPlatformSnapshotView.getSnapshotInfoList().getSnapshotInfos().get(0)).getPictureUrl();
//                    log.info("==================device-channelsnap-pictureUrl:{}", pictureUrl);
//                    CloseableHttpClient httpClient = HttpClients.createDefault();
//                    HttpGet httpGet = new HttpGet(pictureUrl);
//                    HttpResponse var10 = httpClient.execute(httpGet);
//                    InputStream content = var10.getEntity().getContent();
//                    byte[] bytes = new byte[1024];
//
//                    int i;
//                    while((i = content.read(bytes)) > -1) {
//                        outputStream.write(bytes, 0, i);
//                    }
//
//                    log.info("==================device-channelsnap-end");
//                    return Response.ok();
//                }
//            }
//
//            log.info("【快照】taskId:{}", ivsSnapshotView.getTaskID());
//            throw new ServiceException("快照失败！");
//        } finally {
//            outputStream.close();
//        }
//    }

    @GetMapping({"channellist"})
    public SipbDeviceListView channelList(IvsDevChanListVo ivsDevChanListVo) {
        if (version.equals("1800")) {
            ivsDevChanListVo.setDeviceType(2);
        }
        return ivsCommonService.get(ivsResourceRetryableDelegate.getLabel(), UriUtils.parse(IvsConst.URI_DEVICE_LIST, ivsDevChanListVo), SipbDeviceListView.class);
    }


    @GetMapping({"channellistJson"})
    public JSONObject channelListJson(IvsDevChanListVo ivsDevChanListVo) {
        if (version.equals("1800")) {
            ivsDevChanListVo.setDeviceType(2);
        }
        return ivsCommonService.getResultJson(ivsResourceRetryableDelegate.getLabel(), UriUtils.parse(IvsConst.URI_DEVICE_LIST, ivsDevChanListVo));
    }

    private static int calculateSum(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            System.out.println("i:" + i);
            sum += i;
        }
        return sum;
    }

//    public static void main(String[] args) {
//        Timer timer = new Timer();
//
//        // 创建一个Callable任务
//        Callable<Integer> task = new Callable<Integer>() {
//            @Override
//            public Integer call() throws Exception {
//                int sum = 0;
//                for (int i = 1; i <= 10; i++) {
//                    System.out.println("i:" + i);
//                    sum += i;
//                }
//                return sum;
//            }
//        };
//
//        // 将Callable任务包装成FutureTask
//        FutureTask<Integer> futureTask = new FutureTask<>(task);
//
//        // 设置定时任务
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                futureTask.run();
//            }
//        }, 1000);
//
//        try {
//            // 获取定时任务的返回结果
//            int result = futureTask.get();
//            System.out.println("定时任务的返回结果是：" + result);
//        } catch (InterruptedException | ExecutionException e) {
//            e.printStackTrace();
//        }
//
//        timer.cancel();
//        System.out.println("定时任务的返回结果是");
//    }
}
