package com.unis.detectionnum.server.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.serotonin.modbus4j.code.DataType;
import com.unis.common.utils.ResponseWrapper;
import com.unis.detectionnum.common.vo.DeviceInfoQueryVO;
import com.unis.detectionnum.common.vo.DeviceInfoVO;
import com.unis.detectionnum.common.vo.DeviceOperateVO;
import com.unis.detectionnum.common.vo.ScanPointsQueryVO;
import com.unis.detectionnum.server.service.ScanPointsService;
import com.unis.detectionnum.server.utils.Modbus4jUtils;
import com.unis.detectionnum.server.utils.Register;
import com.unis.detectionnum.server.utils.ReturnResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.net.Socket;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description 粮食数据量检测控制类
 * @Package: com.unis.detectionnum.server.controller
 * @Author: LiuFeng
 * @Description:
 * @Date: Created in 2019/8/14
 */

@RestController
@Api(value = "数量监测管理", tags = "数量监测管理")
public class DetectionController {

    private static final Logger log = LoggerFactory.getLogger(DetectionController.class);

    @Autowired
    private ScanPointsService pointsService;

    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "启动扫描接口")
    @RequestMapping(value = "/detection/scan/start", method = RequestMethod.GET)
    @ResponseBody
    public Map scanStrat(HttpServletRequest request) {
        try {

            //获取扫描状态值（寄存器地址0x000A） 0：扫描完成  1：正在扫描
            Number number = Modbus4jUtils.readHoldingRegister(Register.SLAVE_IP, Register.SLAVE_PORT, Register.SLAVE_ID, Register.SCAN_STATUS, DataType.TWO_BYTE_INT_SIGNED);
            log.debug(String.valueOf(number.intValue()));

            if (number.intValue() == 0) {
                //扫描状态值为0时，设置寄存器地址0x4060处值，值为0x00FF，启动扫描器
                Boolean isSet = Modbus4jUtils.writeRegister(Register.SLAVE_IP, Register.SLAVE_PORT, Register.SLAVE_ID, Register.SCAN_SET, Register.SCAN_SET_VALUE);
                if (isSet) {
                    return ReturnResult.successResult("启动成功");
                } else {
                    return ReturnResult.errorResult("寄存器地址0x4060，写入值0x00FF失败");
                }
            }
            return ReturnResult.errorResult("启动失败");


        } catch (Exception e) {
            log.error("DetectionController.scanStrat", e);
            return ReturnResult.errorResult("创建失败");
        }
    }

    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "读取点数数据接口")
    @RequestMapping(value = "/detection/points/readData", method = RequestMethod.GET)
    @ResponseBody
    public Map readData(HttpServletRequest request) {

        try {

            Number number = Modbus4jUtils.readHoldingRegister(Register.SLAVE_IP, Register.SLAVE_PORT, Register.SLAVE_ID, Register.SCAN_STATUS, DataType.TWO_BYTE_INT_SIGNED);

            if (number.intValue() == 0) {
                Map<String,Object> result = pointsService.savePointsData(Register.SLAVE_IP, Register.SLAVE_PORT, Register.SLAVE_ID,new Date());
                return result;
            } else {
                return ReturnResult.errorResult("扫描未完成");
            }
        } catch (Exception e) {
            log.error("DetectionController.readData", e);
            return ReturnResult.errorResult("数据读取失败");
        }

    }
    
    @ApiOperation(value = "数据查询-设备信息【列表查询】")
    @PostMapping(value = "/detection/device/infoLlist")
    public ResponseWrapper getDeviceInfoList(HttpServletRequest request, @RequestBody DeviceInfoQueryVO deviceInfoQueryVO) {

        try {
        	List<DeviceInfoVO> list = pointsService.getDeviceInfoList(deviceInfoQueryVO);
        	return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), list);
        }catch (Exception e){
            log.error("DetectionController.getDeviceInfoList",e);
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }
    
    @ApiOperation(value = "数据查询-扫描纪录信息【列表查询】")
    @PostMapping(value = "/detection/device/operateList")
    public ResponseWrapper getDeviceOperateList(HttpServletRequest request, @RequestBody DeviceInfoQueryVO deviceInfoQueryVO) {

        try {
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pointsService.getDeviceOperateList(deviceInfoQueryVO));
        }catch (Exception e){
            log.error("DetectionController.getDeviceOperateList",e);

        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }
    
    @ApiOperation(value = "数据查询-扫描纪录信息列表【分页查询】")
    @PostMapping(value = "/detection/device/operate-page/{pageNum}/{pageSize}")
    public ResponseWrapper getDeviceOperatePageList(HttpServletRequest request, 
    		@PathVariable("pageNum") Integer pageNum,
    		@PathVariable("pageSize") Integer pageSize,
    		@RequestBody DeviceInfoQueryVO deviceInfoQueryVO) {

        try {
        	PageHelper.startPage(pageNum, pageSize);
        	List<DeviceOperateVO> list = pointsService.getDeviceOperateList(deviceInfoQueryVO);
        	PageInfo<DeviceOperateVO> operatePageInfo = new PageInfo<>(list);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), operatePageInfo);
        }catch (Exception e){
            log.error("DetectionController.getDeviceOperateList",e);
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

    @ApiOperation(value = "数据查询-点数数据查询")
    @PostMapping(value = "/detection/scan/pointList")
    public ResponseWrapper getList(HttpServletRequest request, @RequestBody ScanPointsQueryVO pointsQueryVO) {

        try {
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pointsService.getPointList(pointsQueryVO));
        }catch (Exception e){
            log.error("DetectionController.getList",e); 

        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");

    }



}
