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

import com.chinaitop.depot.intelligent.basicdata.model.TNNtinfoHistory;
import com.chinaitop.depot.intelligent.basicdata.model.TNtinfo;
import com.chinaitop.depot.intelligent.basicdata.service.GasService;
import com.chinaitop.depot.intelligent.socket.SocketClient;
import com.chinaitop.depot.intelligent.utils.ConstUtils;
import com.chinaitop.depot.intelligent.utils.HexConvertUtils;
import com.chinaitop.depot.intelligent.utils.ParameterUtil;
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.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/intelligents/gas")
@Api(value = "GasController", description = "气调设备控制类")
public class GasController {

    @Resource
    private GasService gasService;
    @Autowired
    private SocketClient socketClient;
    @Autowired
    private ConstUtils constUtils;

    @RequestMapping(value = "/getList", 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<TNtinfo>> getList(Integer pageNum, Integer pageSize, String vCfCode) {
        List<TNtinfo> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = gasService.getList(vCfCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询气调列表失败");
        }
        PageInfo<TNtinfo> pageInfo = new PageInfo<TNtinfo>(list);
        return ResponseEntity.ok(pageInfo);
    }

    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    @ApiOperation(value = "根据气调id查询 信息", notes = "根据气调id查询 信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "气体id", paramType = "query")
    })
    public ResponseEntity<TNtinfo> getById(String id) {
        TNtinfo tNtinfo = null;
        if (StringUtils.isNotBlank(id)) {
            tNtinfo = gasService.getById(id);
        } else {
            return ResponseEntity.failed("ID数据有误!");
        }
        return ResponseEntity.ok(tNtinfo);
    }

    @RequestMapping(value = "/save", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "数据更新与添加", notes = "数据更新与添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grainJson", value = "表数据json串", paramType = "form")
    })
    public ResponseEntity save(String grainJson) {
        try {
            gasService.save(grainJson);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("保存失败");
        }
        return ResponseEntity.ok();
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ApiOperation(value = "根据气调id删除", notes = "根据气调id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "气体id", paramType = "query"),
            @ApiImplicitParam(name = "basicGasSetJson", value = "气体json数据", paramType = "query")
    })
    public ResponseEntity deleteById(String id,String basicGasSetJson) {
        if (StringUtils.isNotBlank(id)) {
            int count = gasService.deleteById(id,basicGasSetJson);
            if (count > 0) {
                ResponseEntity.ok();
                return ResponseEntity.ok();
            } else {
                return ResponseEntity.failed("删除失败!");
            }
        }
        return ResponseEntity.failed("ID数据有误!");
    }
    @RequestMapping(value = "/getBycfCode", method = RequestMethod.GET)
    @ApiOperation(value = "校验是否重复", notes = "校验是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vdevcode", value = "设备编码", paramType = "query"),
            @ApiImplicitParam(name = "vdevname", value = "设备名称", paramType = "query")
    })
    public ResponseEntity getBycfCode(String vdevcode, String vdevname) {
        boolean bycfCode = gasService.getBycfCode(vdevcode, vdevname);
        return ResponseEntity.ok(bycfCode);
    }

    /**
     * 氮气气调控制
     * @param vcfcode
     * @param ktinfoJson json数据socket发送成功保存气调作业记录
     * @param uperson socket发送成功保存气调作业记录操作人
     * @param vdevcode
     * @param type
     *        关闭:close,打开:open,反转:reverse,停止:stop,设置当前温度:temp,设置当前风速:wind,设置当前模式:mode
     * @return
     */
    @RequestMapping(value = "/sendAirConditionDir", method = RequestMethod.POST)
    @ApiOperation(value = "氮气气调控制指令", notes = "氮气气调控制指令")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vcfcode",defaultValue = "001",value = "仓库编号", paramType = "query"),
            @ApiImplicitParam(name = "vdevcode",defaultValue = "00001",value = "设备编号", paramType = "query"),
            @ApiImplicitParam(name = "type",defaultValue = "temp",value = "操作类型", paramType = "query"),
            @ApiImplicitParam(name = "ktinfoJson",value = "气调控制数据json", paramType = "query"),
            @ApiImplicitParam(name = "uperson",value = "操作人", paramType = "query")
    })
    public ResponseEntity<Map<String,String>> sendAirConditionDir(String vcfcode, String vdevcode, String type, String ktinfoJson, String uperson) {
        Map<String,String> map = new LinkedHashMap<>();
        String dir = "";
        // 确定控制类型
        if (ParameterUtil.isnotnull(vcfcode) && ParameterUtil.isnotnull(vdevcode)){
            if (org.apache.commons.lang.StringUtils.isNotBlank(type)){
                // 关闭:close ACT:0X00
                if (type.equals("close"))
                    // 0X09获取空调数据
                    dir = constUtils.directiveJoint(constUtils.NITR_TYPE, vcfcode, vdevcode,constUtils.TFK_DEVTYPE,constUtils.CLOSE_DEVTYPE,"");
                else if (type.equals("open")) // 打开:open ACT:0X01
                    dir = constUtils.directiveJoint(constUtils.NITR_TYPE, vcfcode, vdevcode,constUtils.TFK_DEVTYPE,constUtils.OPEN_DEVTYPE,"");
                    // 反转:reverse ACT:0X02
                else if (type.equals("reverse"))
                    dir = constUtils.directiveJoint(constUtils.NITR_TYPE, vcfcode, vdevcode,constUtils.TFK_DEVTYPE,constUtils.REV_DEVTYPE,"");
                    // 停止:stop ACT:0X03
                else if (type.equals("stop"))
                    dir = constUtils.directiveJoint(constUtils.NITR_TYPE, vcfcode, vdevcode,constUtils.TFK_DEVTYPE,constUtils.STOP_DEVTYPE,"");
                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(vcfcode, TypeEnum.S_NUL.getDesc()); // 失败
                    else if ("01".equals(substring)){
                        map.put(vcfcode,TypeEnum.S_SOH.getDesc()); // 成功
                        gasService.saveHistoryData(type,ktinfoJson,uperson,0); // 保存空调作业记录
                    }
                    else if ("02".equals(substring))
                        map.put(vcfcode,TypeEnum.S_STX.getDesc()); // 设备通讯异常
                    else if ("03".equals(substring))
                        map.put(vcfcode,TypeEnum.S_ETX.getDesc()); // 设备故障
                    else if ("04".equals(substring))
                        map.put(vcfcode,TypeEnum.S_EOT.getDesc()); // 未知原因
                    else if ("05".equals(substring))
                        map.put(vcfcode,TypeEnum.S_2D_SOH.getDesc()); // 本地模式,无法远程控制
                } else {
                    if (s.contains("323230")){ // 220-FileZilla Server 0.9.60 beta
                        map.put("error", s);
                    } else {
                        map.put("error", s);
                    }
                    return ResponseEntity.failed(s);
                }
            } else {
                map.put("type","操作类型为空!");
            }
        } else {
            map.put(TypeEnum.S_EM.getCode(),TypeEnum.S_EM.getDesc()+"或设备编号为空!"); // 仓房号为空!或设备编号为空!
        }
        return ResponseEntity.ok(map);
    }

    @RequestMapping(value = "/getHistoryList", 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"),
            @ApiImplicitParam(name = "energy", value = "判断查询的是氮气气调还是氮气房", paramType = "query")
    })
    public ResponseEntity<PageInfo<TNNtinfoHistory>> getHistoryList(Integer pageNum, Integer pageSize, String vCfCode, String energy) {
        List<TNNtinfoHistory> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = gasService.getHistoryList(vCfCode,energy);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询气调列表失败");
        }
        PageInfo<TNNtinfoHistory> pageInfo = new PageInfo<TNNtinfoHistory>(list);
        return ResponseEntity.ok(pageInfo);
    }

    @RequestMapping(value = "/synchronizationAll", method = RequestMethod.GET)
    @ApiOperation(value = "与智远同步气调设置基础数据", notes = "与智远同步气调设置基础数据")
    @ApiImplicitParam(name = "orgId", value = "库房编码", paramType = "query")
    public ResponseEntity synchronizationAll(String orgId) {
        if (StringUtils.isBlank(orgId)){
            return ResponseEntity.ok("库房编码不能为空！");
        }
        String msg = null;
        try {
            msg = gasService.synchronizationAll(orgId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("同步失败！");
        }
        return ResponseEntity.ok(msg);
    }
}
