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

import com.chinaitop.depot.intelligent.coldStorage.model.TKtinfoHistory;
import com.chinaitop.depot.intelligent.coldStorage.service.ColdStorageService;
import com.chinaitop.depot.intelligent.insideCirculation.service.InsideCirculationService;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qingsong.han
 * @description: 低温储粮模块
 * @create 2019-01-24 15:25
 */

@RestController
@RequestMapping(value = "/intelligents/insideCirculation")
@Api(value = "InsideCirculationController", description = "内环流控制类")
@SuppressWarnings("all")
public class InsideCirculationController {
    @Autowired
    private SocketClient socketClient;
    @Autowired
    private ConstUtils constUtils;
    @Autowired
    private InsideCirculationService insideCirculationService;

    /**
     * 内环流控制
     * @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,Integer orgId) {
        Map<String,String> map = new LinkedHashMap<>();
        String dir = "";
        // 确定控制类型
        if (StringUtils.isNotBlank(vcfcode) && StringUtils.isNotBlank(vdevcode)){
            if (StringUtils.isNotBlank(type)){
                // 关闭:close ACT:0X00
                if (type.equals("close"))
                    // 0X09获取空调数据
                    dir = constUtils.directiveJoint(constUtils.GAS_TYPE, vcfcode, vdevcode,constUtils.HLFJ_DEVTYPE,constUtils.CLOSE_DEVTYPE,"");
                else if (type.equals("open")) // 打开:open ACT:0X01
                    dir = constUtils.directiveJoint(constUtils.GAS_TYPE, vcfcode, vdevcode,constUtils.HLFJ_DEVTYPE,constUtils.OPEN_DEVTYPE,"");
                    // 反转:reverse ACT:0X02
                else if (type.equals("reverse"))
                    dir = constUtils.directiveJoint(constUtils.GAS_TYPE, vcfcode, vdevcode,constUtils.HLFJ_DEVTYPE,constUtils.REV_DEVTYPE,"");
                    // 停止:stop ACT:0X03
                else if (type.equals("stop"))
                    dir = constUtils.directiveJoint(constUtils.GAS_TYPE, vcfcode, vdevcode,constUtils.HLFJ_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()); // 成功
                        insideCirculationService.saveHistoryData(type,ktinfoJson,uperson,orgId); // 保存空调作业记录
                    }
                    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","操作类型为空!");
                return ResponseEntity.failed("操作类型为空!");
            }
        } else {
            map.put(TypeEnum.S_EM.getCode(),TypeEnum.S_EM.getDesc()+"或设备编号为空!"); // 仓房号为空!或设备编号为空!
            return ResponseEntity.failed(TypeEnum.S_EM.getDesc()+"或设备编号为空!");
        }
        return ResponseEntity.ok(map);
    }

    /**
     * 内环流作业记录条件列表
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param vcfcode
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(value = "内环流记录列表", notes = "空调作业记录列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query"),
            @ApiImplicitParam(name = "vcfcode", value = "仓房编号", paramType = "query")
    })
    public ResponseEntity<PageInfo<TKtinfoHistory>> getList(Integer pageNum, Integer pageSize, String orgId, String vcfcode) {
        List<TKtinfoHistory> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = insideCirculationService.getList(orgId,vcfcode);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TKtinfoHistory> pageInfo = new PageInfo<TKtinfoHistory>(list);
        return ResponseEntity.ok(pageInfo);
    	
    }

}
