package com.zksy.screen.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zksy.common.core.domain.Result;
import com.zksy.screen.domain.po.ScreenControl;
import com.zksy.screen.domain.request.TopWebPageRequest;
import com.zksy.screen.service.ScreenControlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@Api(tags = "灯杆大屏", description = "灯杆大屏")
@RequestMapping("/screenLamp")
@Slf4j
public class ScreenLampController {
    @Autowired
    private OkHttpClient httpClient;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private final String BASE_URL = "http://172.16.102.52:8016/command/";
    @Autowired
    private ScreenControlService screenControlService;
    @ApiOperation(value = "清屏，清除顶层网页内容")
    @PostMapping("/clearTopWebPage")
    public Result clearTopWebPage(
            @ApiParam(value = "设备编码", required = true) @RequestParam(value = "deviceCode", defaultValue = "") String deviceCode) {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode jsonNodes = objectMapper.createObjectNode();
        jsonNodes.put("type", "clear");
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(jsonNodes);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url(BASE_URL + deviceCode)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("_type");
                if ("success".equals(success.asText())) {
                    return Result.ok("清屏成功");
                } else {
                    return Result.error("清屏，清除顶层网页内容失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e.getMessage());
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "加载顶层网页")
    @PostMapping("/getTopWebPage")
    public Result getTopWebPage(
            TopWebPageRequest request,
            @ApiParam(value = "设备编码", required = true) @RequestParam(value = "deviceCode", defaultValue = "") String deviceCode) {
        if(StrUtil.isBlank(request.getUrl())){
            return Result.error("url不能为空");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode jsonNodes = objectMapper.createObjectNode();
        jsonNodes.put("type",Optional.ofNullable(request.getType()).orElse("loadUrl"));
        jsonNodes.put("persistent",Optional.ofNullable(request.getPersistent()).orElse(true));
        jsonNodes.put("url",request.getUrl());
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(jsonNodes);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url(BASE_URL + deviceCode)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("_type");
                if ("success".equals(success.asText())) {
                    return Result.ok("加载顶层网页成功");
                } else {
                    return Result.error("加载顶层网页失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e.getMessage());
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "开关屏")
    @PostMapping("/turnOffOrLight")
    public Result turnOffOrLight(
            @ApiParam(value = "设备编码", required = true) @RequestParam(value = "deviceCode", defaultValue = "") String deviceCode,
            @ApiParam(value = "指令", required = true) @RequestParam(value = "cmd") Boolean cmd){
        if(cmd == null){
            return Result.error("cmd不能为空");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode jsonNodes = objectMapper.createObjectNode();
        jsonNodes.put("type","callCardService");
        jsonNodes.put("fn","setScreenOpen");
        jsonNodes.put("arg1",cmd);
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(jsonNodes);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url(BASE_URL + deviceCode)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("_type");
                if ("success".equals(success.asText())) {
                    return Result.ok("发送指令成功");
                } else {
                    return Result.error("发送指令失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e.getMessage());
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "查询屏幕状态")
    @PostMapping("/checkScreenState")
    public Result checkScreenState(
            @ApiParam(value = "设备编码", required = true) @RequestParam(value = "deviceCode", defaultValue = "") String deviceCode
    ){
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode jsonNodes = objectMapper.createObjectNode();
        jsonNodes.put("type","callCardService");
        jsonNodes.put("fn","isScreenOpen");
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(jsonNodes);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url(BASE_URL + deviceCode)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("_type");
                if ("success".equals(success.asText())) {
                    boolean result = rootNode.path("result").asBoolean();
                    return Result.ok(result);
                } else {
                    return Result.error("发送指令失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e.getMessage());
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "添加屏幕控制")
    @PostMapping("/addScreenControl")
    public Result addScreenControl(@org.springframework.web.bind.annotation.RequestBody ScreenControl screenControl) {
        screenControl.setCreateTime(new Date());
        boolean saved = screenControlService.save(screenControl);
        if (saved) {
            return Result.ok("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    @ApiOperation(value = "删除屏幕控制")
    @DeleteMapping("/deleteScreenControl/{id}")
    public Result deleteScreenControl(@PathVariable Long id) {
        boolean deleted = screenControlService.removeById(id);
        if (deleted) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @ApiOperation(value = "更新屏幕控制")
    @PutMapping("/updateScreenControl")
    public Result updateScreenControl(@org.springframework.web.bind.annotation.RequestBody ScreenControl screenControl) {
        screenControl.setUpdateTime(new Date());
        boolean updated = screenControlService.updateById(screenControl);
        if (updated) {
            return Result.ok("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    @ApiOperation(value = "根据设备id获取屏幕控制")
    @GetMapping("/getScreenControl/{deviceId}")
    public Result getScreenControl(@PathVariable String deviceId) {
        ScreenControl screenControl = screenControlService.getOne(new QueryWrapper<ScreenControl>().eq("device_id", deviceId));
        if (screenControl != null) {
            return Result.ok(screenControl);
        } else {
            return Result.error("记录不存在");
        }
    }

    @ApiOperation(value = "获取全部屏幕控制")
    @GetMapping("/getAllScreenControl")
    public Result getAllScreenControl() {
        List<ScreenControl> screenControls = screenControlService.list();
        if (screenControls != null) {
            return Result.ok(screenControls);
        } else {
            return Result.error("记录不存在");
        }
    }
}
