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

import com.chinaitop.depot.intelligent.grainsituation.model.TQtdevinfoValue;
import com.chinaitop.depot.intelligent.grainsituation.model.TTestdata;
import com.chinaitop.depot.intelligent.grainsituation.service.GasDetectionService;
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.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.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/intelligents/gasDetection")
@Api(value = "GasDetectionController", description = "气体检测记录控制类")
@SuppressWarnings("all")
public class GasDetectionController {

    @Value("${gas-org-ids}")
    private String orgIds = "386";

    @Resource
    private GasDetectionService gasDetectionService;

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(value = "查询 气体 信息列表", notes = "查询 气体 信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "仓库名称", paramType = "query")
    })
    public ResponseEntity<PageInfo<Object>> getList(Integer pageNum, Integer pageSize, String vCfCode, String startTime, String endTime) {
        List<Object> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = gasDetectionService.getList(vCfCode, startTime, endTime, "");//查询方法添加id查询
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<Object> pageInfo = new PageInfo<Object>(list);
        return ResponseEntity.ok(pageInfo);
    }

    @RequestMapping(value = "/getListGroup", method = RequestMethod.GET)
    @ApiOperation(value = "查询 气体 检测列表", notes = "查询 气体 检测列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "仓库名称", paramType = "query")
    })
    public ResponseEntity<PageInfo<Object>> getListGroup(Integer pageNum, Integer pageSize, String vCfCode) {
        List<Object> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = gasDetectionService.getListGroup(vCfCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<Object> pageInfo = new PageInfo<Object>(list);
        return ResponseEntity.ok(pageInfo);
    }

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

    @RequestMapping(value = "/sendNowGasDetection", method = RequestMethod.POST)
    @ApiOperation(value = "气体实时检测", notes = "气体实时检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeCode", defaultValue = "001", value = "仓库编号", paramType = "query")
    })
    public ResponseEntity<Map<String, String>> sendNowInsectPest(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.SUB_P, constUtils.GAS_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);
    }

    /**
     * 单仓检测接口
     *
     * @param vCfCode
     * @return
     */
    @RequestMapping(value = "/sendOnlyGasDetection", method = RequestMethod.POST)
    @ApiOperation(value = "单仓气体实时检测", notes = "单仓气体实时检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vCfCode", defaultValue = "001", value = "仓库编号", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "库点编号", paramType = "query")
    })
    public ResponseEntity sendOnlyInsectPestDetection(String vCfCode, String orgId) {
        String result = "";
        try {
            String gasType = "";
            List<String> list = Arrays.asList(orgIds.split(","));
            if (list.contains(orgId)){
                gasType = constUtils.MGAS_TYPE;
            } else {
                gasType = constUtils.GAS_TYPE;
            }
            if (StringUtils.isNotBlank(vCfCode)) {
                // 数据采集,仓房号,设备编号若为0则控全部
                String dir = constUtils.directiveJoint(constUtils.F_EXTENT, constUtils.SUB_P, gasType, vCfCode, "");
                // 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);
    }

    /**
     * 所有实时检测
     *
     * @return
     */
    @RequestMapping(value = "/sendGasDetectionAll", method = RequestMethod.GET)
    @ApiOperation(value = "所有仓气体实时检测", notes = "所有仓气体实时检测")
    @ApiImplicitParam(name = "orgId", value = "库点编号", paramType = "query")
    public ResponseEntity sendTemperatureDetectionAll(String orgId) {
        String result = "";
        try {
            boolean temp = false;
            String gasType = "";
            List<String> list = Arrays.asList(orgIds.split(","));
            if (list.contains(orgId)){
                gasType = constUtils.MGAS_TYPE;
                temp = true;
            } else {
                gasType = constUtils.GAS_TYPE;
            }
            // 0X07虫情数据采集,仓房号,设备编号若为0则控全部
            String dir = constUtils.HEADER + constUtils.F_EXTENT + gasType + constUtils.SUB_P + constUtils.ALL_STORE;
            // 16进制字符串转byte数组
            byte[] bytes = HexConvertUtils.hexStringToByte(dir);
            // 发送指令
            String s = socketClient.startClient(bytes);
            // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
            result = TypeEnum.resultDispose(s);
            if (temp && result.contains("检测开始")){
                result += "本次检测大概需要30至60分钟，请稍后查看。";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("设备连接异常！");
        }
        return ResponseEntity.ok(result);
    }

}
