package com.mvc.controller;

import com.mvc.forwarmana.ForwarderThread;
import com.mvc.forwarmana.ZHYForwarder;
import com.mvc.interceptor.Debounce;
import com.mvc.iot.aep.AepApiHelper;
import com.mvc.iot.onenet.OneNetApiHelper;
import com.mvc.model.*;
import com.mvc.service.aiiden.TaskReviewService;
import com.mvc.service.alarm.AlarmNoticeMana;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.external.ZbdxDataService;
import com.mvc.service.forwarding.TForwarderRecordsService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.service.taizhang.TaskRemoteCfgService;
import com.mvc.service.test.ServerIdenTest;
import com.mvc.service.test.TaiZhangTest;
import com.mvc.utils.DateUtil;
import com.mvc.utils.NotifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

@Api(tags = "测试专用接口")
@RequestMapping("/TestAction")
@Controller
public class TestAction {
    @Resource
    private ServerIdenTest serverIdenTest;

    @Resource
    private NotifyUtil notifyUtil;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private AlarmNoticeMana alarmNoticeMana;

    @Resource
    private ZbdxDataService zbdxDataService;

    @Resource
    private TAireadService aireadService;

    @Resource
    private TaiZhangTest taiZhangTest;

    @Resource
    private TForwarderRecordsService forwarderRecordsService;
    @Resource
    private TaskReviewService taskReviewService;

    @Resource
    private ZHYForwarder zhyForwarder;

    @ApiOperation("识别服务测试")
    @RequestMapping(value = "/testServerIden", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> testServerIden() {
        try {
            serverIdenTest.test();
            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", 1);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    @ApiOperation("邮件发送测试")
    @RequestMapping(value = "/sendEMail/{toUser}/{subject}/{content}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> sendEMail(@PathVariable("toUser") String toUser, @PathVariable("subject") String subject, @PathVariable("content") String content) {
        try {
            //String fileName = "E:/shangchuan/14.png";
            notifyUtil.sendEMail(toUser, subject, content);
            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", 1);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    @ApiOperation("燃气表数据缺失报警测试")
    @RequestMapping(value = "/handleDataMissing/{stationCode}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> handleDataMissing(@PathVariable("stationCode") String stationCode) {
        try {
            if (stationCode.length() == 10) {
                StationAccModel accModel = stationAccService.findStationAccByStationCode(stationCode);
                if (accModel != null) {
                    alarmNoticeMana.checkDataMissing(accModel);
                }
            } else {
                alarmNoticeMana.handleDataMissing();
            }

            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", 1);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    @ApiOperation("燃气表动态报警测试")
    @RequestMapping(value = "/handleDynamicRange/{stationCode}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> handleDynamicRange(@PathVariable("stationCode") String stationCode) {
        try {
            TAireadModel aireadModel = new TAireadModel();
            aireadModel.setResultValue(BigDecimal.valueOf(280224.84000));
            aireadModel.setStationCode(stationCode);
            aireadModel.setSampleTime(DateUtil.parseTimeStr("20240408000000", DateUtil.PATTERN_DATA_UNSIGNED));
            alarmNoticeMana.handleDynamicRange(aireadModel);

            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", 1);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @ApiOperation("根据ID打印远程配置下行报文")
    @RequestMapping(value = "/printTaskRemoteCfgMessage/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> printTaskRemoteCfgMessage(@PathVariable("id") Integer id) {
        try {
            TaskRemoteCfgModel model = taskRemoteCfgService.findTaskRemoteCfgById(id);
            String hex = taskRemoteCfgService.getHexaskRemoteCfg(model);
            System.out.println(hex);
            Object object = hex;

            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", object);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    /** 微信小程序使用WebView跳转至外部URL(根据取水可证号查询遥测编码),由于微信限制,必须配置业务域名才可正常访问,因此尝试跳转方式 -- 开始 */
    //经过尝试,在PC小程序中可以打开,在手机中仍无法打开  2024-05-13 guozhao
    /*@GetMapping("/redirect-to-external")
    public RedirectView redirectToExternalUrl() {
        // 使用RedirectView来重定向到外部URL
        // 注意：在某些情况下，你可能需要使用HttpServletResponse来设置重定向
        // 但RedirectView更适用于返回视图的情况
        return new RedirectView("https://smart.swj.beijing.gov.cn/iotapp/waterMeter/index.html#/login", true);
    }

    // 如果你不能使用RedirectView（例如，在RESTful API中）
    // 你可以使用HttpServletResponse来设置重定向
    @GetMapping("/api/redirect-to-external")
    public void redirectToExternalUrlApi(HttpServletResponse response){
        // 设置HTTP响应状态为302（Found）来实现重定向
        response.setStatus(HttpServletResponse.SC_FOUND);
        // 设置Location头来指示浏览器重定向到的URL
        response.setHeader("Location", "https://smart.swj.beijing.gov.cn/iotapp/waterMeter/index.html#/login");
    }*/
    /** 微信小程序使用WebView跳转至外部URL(根据取水可证号查询遥测编码),由于微信限制,必须配置业务域名才可正常访问,因此尝试跳转方式 -- 结束 */

    /**
     * 导出单表数据
     * @param response HttpServletResponse
     */
    @ApiOperation("导出中北大学格式数据")
    @RequestMapping(value = "/exportZbdxExcel/{unitCode}/{date}", method = RequestMethod.GET)
    @ResponseBody
    public void exportZbdxExcel(HttpServletResponse response,@PathVariable("unitCode") String unitCode,@PathVariable("date") String date) {
        zbdxDataService.exportZbdxExcel(response, unitCode, date);
    }

    @Resource
    private OneNetApiHelper oneNetApiHelper;

    @Resource
    private AepApiHelper aepApiHelper;

    @ApiOperation("测试转发记录入库")
    @RequestMapping(value = "/ForwarderRecord/{stationCode}", method = RequestMethod.GET)
    @ResponseBody
    public String testForwarderRecord(@PathVariable("stationCode") String stationCode) {
        try {
            /*TAireadModel aireadModel = aireadService.findLatesTAireadByStationCode(stationCode);
            aireadModel.setSmallRawData(taskReviewService.getPicRawData(null));
            StoreBlockingQueue.sysReviewQueue.put(aireadModel);*/

            //OneNet创建/删除设备
            /*OneNetDeviceApiModel model = new OneNetDeviceApiModel();
            AepAppDataModel model = new AepAppDataModel();
            model.setImei("864606065659897");
            model.setDevice_name("0000001849");
            model.setImsi("864606065659897");
            model.setProduct_id("U163RT0ok5");
            //oneNetApi.createDevice(model);
            oneNetApi.deleteDevice(model);*/

            //OneNet下发指令
            /*String message = "7E7E0000000000162020E08013020002241014000111BD0800D10801D5080105AB98";
            oneNetApiHelper.sendCommand("861999061568318",message);*/

            //OneNet取消指令
            /*String uuid = "ac954d4e-fc9c-5776-9a01-4d64a4f7508d";
            oneNetApiHelper.cancelCommand(uuid,"861999061568318");*/

            //AEP创建设备
            /*AepDeviceApiModel model = new AepDeviceApiModel();
            model.setDeviceName("0000001849");
            model.setImei("864606065659897");
            model.setOperator("GZ");
            model.setProductId(17154609);
            AepDeviceApiOtherModel other = new AepDeviceApiOtherModel();
            other.setAutoObserver(1);
            model.setOther(other);
            aepApi.createDevice(model);*/

            //AEP批量删除设备
            /*List<String> imeiList = new ArrayList<>();
            imeiList.add("864606065659897");
            imeiList.add("864606065659898");
            aepApiHelper.deleteDevice(imeiList);*/

            //AEP下发指令
            /*AepCommandBodyModel body = new AepCommandBodyModel("31e663633bbf47ccb953a2b355a66a49",
                    "GZ",17154609
                    ,"7E7E0000000000162020E08013020002241014000111BD0800D10801D5080105AB98");
            aepApiHelper.createCommand(body);*/

            //AEP取消指令
            //aepApiHelper.cancleCommand("1","31e663633bbf47ccb953a2b355a66a49");

            //OneNet通过API获取位置
            oneNetApiHelper.getLatestLocation("861999061544863");

            /*TForwarderRecordsModel model = new TForwarderRecordsModel();
            model.setForwardSampleTime(new Date());
            model.setForwardTime(new Date());
            model.setAireadId(9999);
            model.setForwardNum(1);
            model.setReplyMsg("123");
            model.setSendMsg("321");
            model.setStationCode("0000009527");
            model.setForwardValue("98765.2145");
            forwarderRecordsService.saveTForwarderRecords(model);*/

            return "1";
        }catch (Exception e){
            return e.toString();
        }
    }

    @ApiOperation("生成系统批量任务")
    @RequestMapping(value = "/generateSystemBatchTasks/{param}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> generateSystemBatchTasks(@PathVariable("param") String param) {
        try {
            int res = taiZhangTest.generateSystemBatchTasks(param);
            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", res);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    @ApiOperation("生成水利所转发队列数据")
    @RequestMapping(value = "/generateSlsDataQueue", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> generateSlsDataQueue() {
        try {
            zhyForwarder.generateSlsDataQueue();
            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", 1);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }

    @Resource
    private ForwarderThread forwarderThread;

    @ApiOperation("临时测试接口")
    @RequestMapping(value = "/testMethod", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> testMethod() {
        try {
            //forwarderThread.dealCyForwardData();
            Map<String, Object> resMap = new CorrectMap();
            resMap.put("res", 1);
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resMap = new ErrorMap();
            resMap.put("error", e.getMessage());
            return resMap;
        }
    }
}
