package com.youchain.businessdata.rest;

import com.alibaba.fastjson.JSONObject;
import com.github.s7connector.api.S7Connector;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.businessdata.service.MoService;
import com.youchain.exception.handler.ApiResult;
import com.youchain.utils.S7ConnectorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;

/**
 * @author huojin
 * @website
 * @date 2024-04-10
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "plc管理")
@RequestMapping("/api/plc")
public class PlcController {

    private final MoService moService;

    @PostMapping("/scanMo")
    @AnonymousAccess
    @Log("PLC扫描容器")
    @ApiOperation("PLC扫描容器")
    public ResponseEntity<Object> scanMo(@RequestBody String moJson) {
        /*S7Connector connector = S7ConnectorUtils.connect();
        if (connector == null) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "PLC连接失败", ""), HttpStatus.BAD_REQUEST);
        }*/
        try {
            JSONObject json = JSONObject.parseObject(moJson);
            if (json == null) {
                return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "参数错误", ""), HttpStatus.BAD_REQUEST);
            }
            String mo = json.getString("mo");
            moService.scanMo(mo);
            //S7ConnectorUtils.write(connector,2);
            return new ResponseEntity<>(ApiResult.success(OK.value(), "", ""), HttpStatus.OK);
        } catch (Exception e) {
            //S7ConnectorUtils.write(connector,1);
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), e.getMessage(), ""), HttpStatus.BAD_REQUEST);
        }

    }
}
