package com.chinaitop.depot.intelligent.grainsituation.controller;

import com.chinaitop.depot.intelligent.grainsituation.model.TTestdata;
import com.chinaitop.depot.intelligent.grainsituation.model.TTestdataLayer;
import com.chinaitop.depot.intelligent.grainsituation.service.TPointsService;
import com.chinaitop.depot.intelligent.grainsituation.service.TemperatureRecordService;
import com.chinaitop.depot.intelligent.socket.SocketClient;
import com.chinaitop.depot.intelligent.utils.ConstUtils;
import com.chinaitop.depot.intelligent.utils.HexConvertUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unissoft.model.ResponseEntity;
import com.unissoft.model.TypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping(value = "/intelligents/temperatureRecord")
@Api(value = "TemperatureRecordController", description = "测温记录控制类")
@SuppressWarnings("all")
public class TemperatureRecordController {

    @Autowired
    private TemperatureRecordService temperatureRecordService;
    @Resource
    private TPointsService tpointsService;


    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(value = "查询 测温 信息列表", notes = "查询 测温 信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "vDatatime", value = "采集时间", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "仓库名称", paramType = "query"),
            @ApiImplicitParam(name = "tType", value = "检测类型0测温，1粮油,2测水分", paramType = "query")
    })
    public ResponseEntity<PageInfo<TTestdata>> getList(Integer pageNum, Integer pageSize, String vCfCode, String vDatatime, String startTime, String endTime, String tType,String orgId) {
        List<TTestdata> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = temperatureRecordService.getList(vCfCode, vDatatime, startTime, endTime, tType, orgId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TTestdata> pageInfo = new PageInfo<TTestdata>(list);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     * 获取一条数据
     *
     * @param vCfCode   库房编码
     * @param vDatatime 检测时间
     * @return
     */
    @RequestMapping(value = "/findByHouseAndTime", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value = "根据库房编码和测温时间查询单条检测记录包括每层的最高温最低温平均温", notes = "根据库房编码和测温时间查询单条检测记录包括每层的最高温最低温平均温")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lqId", value = "粮情id", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "库房编码", paramType = "query"),
            @ApiImplicitParam(name = "vDatatime", value = "测温时间", paramType = "query")
    })
    public ResponseEntity findByHouseAndTime(String lqId, String vCfCode, String vDatatime) {
        List<TTestdataLayer> tTestdataLayer = null;
        try {
            tTestdataLayer = temperatureRecordService.findByHouseAndTime(lqId, vCfCode, vDatatime);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询失败");
        }
        return ResponseEntity.ok(tTestdataLayer);
    }

    /**
     *
     * @param lqId
     * @param vCfCode
     * @param vDatatime
     * @param viewFlag true: 表格数据,false: 3D三温图数据
     * @return
     */
    @RequestMapping(value = "/findByHouseAndTimes", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value = "根据库房编码和测温时间查询检测记录包括层，行，各个节点的值", notes = "根据库房编码和测温时间查询检测记录包括层，行，各个节点的值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lqId", value = "粮情id", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "库房编码", paramType = "query"),
            @ApiImplicitParam(name = "vDatatime", value = "测温时间", paramType = "query"),
            @ApiImplicitParam(name = "viewFlag", value = "区分表格和3D图", paramType = "query")
    })
    public ResponseEntity findByHouseAndTimes(String lqId, String vCfCode, String vDatatime, boolean viewFlag) {
        ArrayList<Object> byHouseAndTimes = null;
        try {
            byHouseAndTimes = temperatureRecordService.findByHouseAndTimes(lqId, vCfCode, vDatatime, viewFlag);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询失败");
        }
        return ResponseEntity.ok(byHouseAndTimes);
    }

    /**
     * 左图表对比接口
     *
     * @param pageNum
     * @param pageSize
     * @param vCfCodeLeft
     * @param startTimeLeft
     * @param endTimeLeft
     * @return
     */
    @RequestMapping(value = "/getComparisonLeft", method = RequestMethod.GET)
    @ApiOperation(value = "左图表对比信息列表", notes = "左图表对比列表,支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", defaultValue = "1", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", defaultValue = "7", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "vCfCodeLeft", value = "左图仓房编码", paramType = "query"),
            @ApiImplicitParam(name = "startTimeLeft", value = "左图开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTimeLeft", value = "左图结束时间", paramType = "query"),
            @ApiImplicitParam(name = "tType", value = "检测类型0测温，1粮油,2测水分", paramType = "query")
    })
    public ResponseEntity<PageInfo<TTestdata>> getComparisonLeft(Integer pageNum, Integer pageSize, String vCfCodeLeft,
                                                                 String startTimeLeft, String endTimeLeft, String tType) {
        List<TTestdata> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = temperatureRecordService.getComparison(vCfCodeLeft, startTimeLeft, endTimeLeft, null, null, null, tType);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TTestdata> pageInfo = new PageInfo<TTestdata>(list);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     * 左图表对比接口
     *
     * @param pageNum
     * @param pageSize
     * @param vCfCodeRight
     * @param startTimeRight
     * @param endTimeRight
     * @return
     */
    @RequestMapping(value = "/getComparisonRight", method = RequestMethod.GET)
    @ApiOperation(value = "右图表对比信息列表", notes = "右图表对比列表,支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", defaultValue = "1", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", defaultValue = "7", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "vCfCodeRight", value = "右图仓房编码", paramType = "query"),
            @ApiImplicitParam(name = "startTimeRight", value = "右图开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTimeRight", value = "右图结束时间", paramType = "query"),
            @ApiImplicitParam(name = "tType", value = "检测类型0测温，1粮油,2测水分", paramType = "query")
    })
    public ResponseEntity<PageInfo<TTestdata>> getComparisonRight(Integer pageNum, Integer pageSize, String vCfCodeRight,
                                                                  String startTimeRight, String endTimeRight, String tType) {
        List<TTestdata> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = temperatureRecordService.getComparison(null, null, null, vCfCodeRight, startTimeRight, endTimeRight, tType);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TTestdata> pageInfo = new PageInfo<TTestdata>(list);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     * 所有点粮情对比
     *
     * @param pageNum
     * @param pageSize
     * @param storehouse
     * @param time
     * @return
     */
    @RequestMapping(value = "/getGrainPointAll", method = RequestMethod.GET)
    @ApiOperation(value = "点粮情对比", notes = "点粮情对比，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "30", paramType = "query"),
            @ApiImplicitParam(name = "time", value = "采集时间", paramType = "query"),
            @ApiImplicitParam(name = "storehouse", value = "仓库编号", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "粮情,水分id", paramType = "query")
    })
    public ResponseEntity<PageInfo<Map<String, Object>>> getGrainPointAll(Integer pageNum, Integer pageSize, String storehouse, String time, String id) {
        List<Map<String, Object>> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = tpointsService.getGrainPointAll(storehouse, time, id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     * orgid下的所有仓房粮情检测
     *
     * @param storeCode
     * @return
     */
    @Autowired
    private SocketClient socketClient;
    @Autowired
    private ConstUtils constUtils;

    @RequestMapping(value = "/sendTemperatureDetection", method = RequestMethod.POST)
    @ApiOperation(value = "粮情实时检测", notes = "粮情实时检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeCode", defaultValue = "001", value = "仓库编号", paramType = "query")
    })
    public ResponseEntity<Map<String, String>> sendTemperatureDetection(String storeCode) {
        Map<String, String> map = new LinkedHashMap<>();
        if (StringUtils.isNotBlank(storeCode)) {
            String sTemp = storeCode.substring(0, storeCode.length());
            String[] sArray = sTemp.split(",");
            for (String cfCode : sArray) {
                // 0X02粮情数据采集,仓房号,设备编号若为0则控全部
                String dir = constUtils.directiveJoint(constUtils.F_EXTENT, constUtils.F_SUB_P, constUtils.GRAIN_TYPE, cfCode, "");
                // 16进制字符串转byte数组
                byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                // 发送指令
                String s = socketClient.startClient(bytes);
                // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
                if (s.contains("7E")) {
                    String substring = s.substring(s.length() - 2, s.length());
                    if ("00".equals(substring))
                        map.put(cfCode, TypeEnum.S_NUL.getDesc()); // 失败
                    else if ("01".equals(substring))
                        map.put(cfCode, TypeEnum.S_SOH.getDesc()); // 成功
                    else if ("02".equals(substring))
                        map.put(cfCode, TypeEnum.S_STX.getDesc()); // 设备通讯异常
                    else if ("03".equals(substring))
                        map.put(cfCode, TypeEnum.S_ETX.getDesc()); // 设备故障
                    else if ("04".equals(substring))
                        map.put(cfCode, TypeEnum.S_EOT.getDesc()); // 未知原因
                    else if ("05".equals(substring))
                        map.put(cfCode, TypeEnum.S_2D_SOH.getDesc()); // 本地模式,无法远程控制
                    else if ("06".equals(substring))
                        map.put(cfCode, TypeEnum.SM.getDesc()); // 设备正忙
                } else {
                    if (s.contains("323230")) { // 220-FileZilla Server 0.9.60 beta
                        map.put("error", "无法连接到服务器!");
                    } else {
                        map.put("error", s);
                    }
                    return ResponseEntity.failed(s);
                }
            }
        } else {
            return ResponseEntity.failed(TypeEnum.S_EM.getDesc());  // 仓房号为空
        }
        return ResponseEntity.ok(map);
    }

    @RequestMapping(value = "/sendTemperatureDetectionAll", method = RequestMethod.GET)
    @ApiOperation(value = "所有仓粮情实时检测", notes = "所有仓粮情实时检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tType", value = "检测类型0测温，1粮油,2测水分", paramType = "query")
    })
    public ResponseEntity sendTemperatureDetectionAll(String tType) {
       /* 比如获取所有仓粮情的指令为：7E 0005 02 0101 0000000000，
        那获取所有水位数据是：       7E 0005 0E 0101 0000000000 */
        byte[] b = new byte[11];
        b[0] = 0x7E;
        b[1] = 0x00;
        b[2] = 0x05;
        if (tType.equals("0")) {
            b[3] = 0x02;
        } else {
            b[3] = 0X0E;
        }
        b[4] = 0x01;
        b[5] = 0x01;
        b[6] = 0x00;
        b[7] = 0x00;
        b[8] = 0x00;
        b[9] = 0x00;
        b[10] = 0x00;
        String result = "";
        // 发送指令
        try {
            String s = socketClient.startClient(b);
            // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
            result = TypeEnum.resultDispose(s);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("设备连接异常！");
        } finally {
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 单仓检测接口
     *
     * @param storeCode
     * @return
     */
    @RequestMapping(value = "/sendOnlyStoreDetection", method = RequestMethod.POST)
    @ApiOperation(value = "单仓粮情实时检测", notes = "单仓粮情实时检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeCode", defaultValue = "001", value = "仓库编号", paramType = "query"),
            @ApiImplicitParam(name = "tType", value = "检测类型0测温，1粮油,2测水分", paramType = "query")
    })
    public ResponseEntity sendOnlyStoreDetection(String storeCode, String tType) {
        String result = "";
        try {
            if (StringUtils.isNotBlank(storeCode) && StringUtils.isNotBlank(tType)) {
                // 0X02粮情数据采集,仓房号,设备编号若为0则控全部
                String type = "";
                if (tType.equals("0")) {
                    type = constUtils.GRAIN_TYPE;
                } else {
                    type = constUtils.DEW_TYPE;
                }
                String dir = constUtils.directiveJoint(constUtils.F_EXTENT, constUtils.F_SUB_P, type, storeCode, "");
                // 16进制字符串转byte数组
                byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                // 发送指令
                String s = socketClient.startClient(bytes);
                result = TypeEnum.resultDispose(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("设备连接异常！");
        }
        return ResponseEntity.ok(result);
    }

    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    @ApiOperation(value = "根据粮情id查询粮情信息", notes = "根据粮情id查询粮情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "粮情id", paramType = "query")
    })
    public ResponseEntity findById(String id) {
        TTestdata byId = null;
        try {
            byId = temperatureRecordService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询失败");
        }
        return ResponseEntity.ok(byId);
    }
}
