package com.inspect.patrol.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.access.base.feign.AccessFeign;
import com.inspect.base.core.domain.Response;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.sftp.SftpUploadEntity;
import com.inspect.base.core.utils.HexUtils;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.redis.service.RedisService;
import com.inspect.patrol.contants.LinkageDeviceType;
import com.inspect.patrol.domain.PatrolLinkageStrategy;
import com.inspect.patrol.linkage.NettyUdpClient;
import com.inspect.patrol.linkage.frame.DeviceInfoFrame;
import com.inspect.patrol.linkage.frame.LinkageSignByte;
import com.inspect.patrol.linkage.frame.LinkageSignEntity;
import com.inspect.patrol.linkage.notify.LinkageNotify;
import com.inspect.patrol.linkage.processor.ReceiveProcessor;
import com.inspect.patrol.model.SnapModel;
import com.inspect.patrol.service.BasedataChannelService;
import com.inspect.patrol.service.PatrolTaskService;
import com.inspect.patrol.service.WebsocketService;
import com.inspect.patrol.service.impl.DeviceIntoService;
import com.inspect.patrol.service.impl.PatrolLinkageStrategyServiceImpl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPSClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import static com.inspect.patrol.linkage.constain.LinkageContain.REDIS_LINKAGE_QUEUE_NOW;

@ApiIgnore
@RestController
@RequestMapping({"/test"})
public class TestController extends BaseController {
    @Autowired
    private PatrolTaskService patrolTaskService;
    @Autowired
    private LinkageNotify linkageNotify;
    @Autowired
    private NettyUdpClient nettyUdpClient;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private PatrolLinkageStrategyServiceImpl patrolLinkageStrategyService;
    @Autowired
    private WebsocketService websocketService;
    @Autowired
    private AccessFeign accessFeign;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SftpClient sftpClient;
    @Autowired
    private BasedataChannelService basedataChannelService;
    @Autowired
    private DeviceIntoService deviceIntoService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ReceiveProcessor receiveProcessor;

    @GetMapping({"c/{p}"})
    public AjaxResult c(@PathVariable("p") String p) {
        if (p.equals("1")) {
            return AjaxResult.success(Boolean.valueOf(this.patrolTaskService.isManualControlPTZ("010010000103010001", this.httpServletRequest)));
        } else {
            this.patrolTaskService.updateCameraPatrolTaskExecRecordState("010010000103010001", "2");
            return AjaxResult.success();
        }
    }

    @GetMapping({"clean_redis"})
    public AjaxResult removeRedisKey() {
        int total = 0;
        this.redisService.deleteObject("REDIS_LINKAGE_QUEUE");
        this.redisService.deleteObject(REDIS_LINKAGE_QUEUE_NOW);

        for (int i = 0; i < 10; ++i) {
            Collection<String> keys = this.redisService.keys(i + "*");
            this.redisService.deleteObject(keys);
            total += keys.size();
        }

        return AjaxResult.success(Integer.valueOf(total));
    }

    public static void main(String[] args) throws Exception {
        picAnalyse();
    }

    @GetMapping({"testFtp"})
    public AjaxResult testFtp() throws Exception {
        ftp();
        return AjaxResult.success();
    }

    @GetMapping({"job"})
    public Response testJob() throws Exception {
        String basePath = "1/2022/07/06/CCD";
        String fileName = "hongww.jpg";
        String sipb = "http://172.21.101.112:9906/api/v1/device/channelsnap";
        InputStream stream = HttpClientUtils.getStream(sipb, "serial=1&realtime=true&code=04644116564209110121#641fd3e415ce4080855106c528bfa138");
        SftpUploadEntity sftpUploadEntity = new SftpUploadEntity(stream);
        sftpUploadEntity.setFilePath(basePath);
        sftpUploadEntity.setFileName(fileName);
        return Response.ok(this.sftpClient.upload(sftpUploadEntity));
    }

    @GetMapping({"ftp1"})
    public AjaxResult testFtp1() throws Exception {
        String basePath = "1/2022/07/06/CCD";
        String fileName = "hongww.jpg";
        SftpUploadEntity sftpUploadEntity = new SftpUploadEntity(new FileInputStream("D:/1.jpg"));
        sftpUploadEntity.setFilePath(basePath);
        sftpUploadEntity.setFileName(fileName);
        String upload = this.sftpClient.upload(sftpUploadEntity);
        return AjaxResult.success(upload);
    }

    private static void ftp() throws Exception {
        FTPSClient ftps = new FTPSClient(true);
        ftps.connect("10.10.17.151", 990);
        boolean login = ftps.login("xgftp", "Xg369246$");
        FileInputStream fileInputStream = new FileInputStream("D:/tmp/1.jpg");
        ftps.enterLocalPassiveMode();
        ftps.setControlEncoding("UTF-8");
        ftps.enterLocalPassiveMode();
        ftps.setFileType(2);
        ftps.setFileTransferMode(10);
        ftps.execPROT("P");
        boolean success = ftps.storeFile("test1.jpg", fileInputStream);
        System.out.println("================success:" + success);
        String replyString = ftps.getReplyString();
        System.out.println("================replyString:" + replyString);
    }

    private static void picAnalyse() {
        JSONObject params = new JSONObject();
        params.put("requestHostIp", "172.21.101.110");
        params.put("requestHostPort", "9901");
        params.put("requestId", Long.valueOf(System.currentTimeMillis()));
        params.put("objectList", (new JSONArray()).fluentAdd((new JSONObject()).fluentPut("objectId", "2023557").fluentPut("typeList", (new JSONArray()).fluentAdd("tx_pb")).fluentPut("imageNormalUrlPath", "algorithm_base_image/d16bfc37-d15d-42ff-8550-a1bba0869e40.jpg").fluentPut("imageUrlList", (new JSONArray()).fluentAdd("1/2022/07/18/879/CCD/2023557_34020000001320000001_20220718101304.jpg"))));
        String s = HttpClientUtils.sendPostAgain("http://172.21.101.118:20011/picAnalyse", params.toJSONString());
        System.out.println(s);
    }

    @PostMapping
    public Response testPost(@RequestBody JSONObject params) {
        this.logger.info("==============iot接收参数：{}", params.getString("camId"));
        return Response.ok();
    }

    @GetMapping({"t"})
    public AjaxResult t() {
        return AjaxResult.success();
    }

    @GetMapping({"info"})
    public void sendInfoRequest() throws Exception {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("linkage_info.txt");
        byte[] bytes = new byte[1024];
        StringBuffer sb = new StringBuffer();

        int i;
        while ((i = resourceAsStream.read(bytes)) > -1) {
            sb.append(new String(Arrays.copyOfRange(bytes, 0, i), "GB2312"));
        }

        DeviceInfoFrame deviceInfoFrame = new DeviceInfoFrame();
        List<byte[]> byteList = deviceInfoFrame.combine(sb.toString(), (short) 1);
        this.nettyUdpClient.sendMessage(byteList);
    }

    @GetMapping({"snap"})
    private String snap() throws Exception {
        SnapModel snapModel = new SnapModel();
        snapModel.setPatrolDeviceCode("267710000003010001");
        snapModel.setChannelCode("267710000003010037");
        return this.deviceIntoService.snap(snapModel);
    }

    @GetMapping({"reverse"})
    public void reverse() {
        this.linkageNotify.alarm("5", "{\"Code\":\"\",\"Command\":\"\",\"Items\":[{\"content\":\"500kV保护小室起火\",\"patroldevice_code\":\"E100-001\",\"patroldevice_name\":\"null\",\"time\":\"2022-05-20 11:29:52\"}],\"ReceiveCode\":\"192.168.1.66\",\"SendCode\":\"192.168.1.15\",\"Time\":\"2022-05-20 11:29:52\",\"Type\":\"5\"}");
    }

    @GetMapping({"linkage"})
    public void sendLinkageRequest(String linkageStrategyId) throws Exception {
        PatrolLinkageStrategy patrolLinkageStrategy = this.patrolLinkageStrategyService.selectPatrolLinkageStrategyByLinkageStrategyId(Long.valueOf(Long.parseLong(linkageStrategyId)));
        if ("3".equals(patrolLinkageStrategy.getTriggerSignalType())) {
            String queueName = (String) this.redisService.getCacheObject("sys_config:PATROL_ALARM_QUEUE_NAME");
            String exchangeName = "exchange-" + queueName;
            String routingName = "springboot." + queueName;
            MessageProperties messageProperties = new MessageProperties();//qinyl
            String message = "{\"Code\":\"\",\"Command\":\"\",\"Items\":[{\"content\":\"" + patrolLinkageStrategy.getLinkageSignalName() + "\",\"patroldevice_code\":\"E100-001\",\"patroldevice_name\":\"null\",\"time\":\"2022-05-20 11:29:52\"}],\"ReceiveCode\":\"192.168.1.66\",\"SendCode\":\"192.168.1.15\",\"Time\":\"2022-05-20 11:29:52\",\"Type\":\"5\"}";
            this.rabbitTemplate.send(exchangeName, routingName, new Message(message.getBytes(), messageProperties));//qinyl
        } else {
            LinkageSignEntity linkageSignEntity = new LinkageSignEntity();
            LinkageSignByte linkageSignByte = new LinkageSignByte();
            linkageSignByte.setType(linkageSignEntity.getType());
            linkageSignByte.setStationNo(Short.parseShort(patrolLinkageStrategy.getStationNo()));
            linkageSignByte.setMonitorIndexNo(Short.parseShort(patrolLinkageStrategy.getMonitorIndexNo()));
            int value = LinkageDeviceType.getInstance(patrolLinkageStrategy.getLinkageSignal()).getValue();
            linkageSignByte.setLinkageType(value);
            linkageSignByte.setLinkageAttribute(patrolLinkageStrategy.getLinkageAttribute());
            linkageSignByte.setLinkageAttributeLen(linkageSignByte.getLinkageAttribute().length);
            linkageSignByte.setLinkageValue(patrolLinkageStrategy.getLinkageValue());
            linkageSignByte.setLinkageValueLen(linkageSignByte.getLinkageValue().length);
            linkageSignByte.setLinkageTime(new Date());
            linkageSignByte.setSumCheck(14 + linkageSignByte.getLinkageAttribute().length + linkageSignByte.getLinkageValue().length);
            List<byte[]> list = new ArrayList();
            list.add(linkageSignByte.toBytes());
            this.nettyUdpClient.sendMessage(list);
        }

    }

    @GetMapping({"parse"})
    public void parse(String hexString) throws Exception {
        byte[] bytes = HexUtils.hexToByteArray(hexString);
        this.receiveProcessor.parse(bytes);
    }
}
