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

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.chinaitop.depot.intelligent.ventilation.model.TCtldevinfo;
import com.chinaitop.depot.intelligent.ventilation.model.TVentilation;
import com.chinaitop.depot.intelligent.ventilation.service.AerationParameterService;
import com.chinaitop.depot.intelligent.ventilation.service.AerationRecordService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@RequestMapping(value = "/intelligents/aerationRecord")
@Api(value = "AerationRecordController", description = "通风记录控制类")
public class AerationRecordController {

    @Autowired
    private AerationRecordService aerationRecordService;
    @Autowired
    private AerationParameterService aerationParameterService;


    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(value = "查询 通风记录列表", notes = "查询 通风记录列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "vDevKindCode", value = "设备类型", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "仓库名称", paramType = "query")
    })
    public ResponseEntity<PageInfo<TVentilation>> getList(Integer pageNum, Integer pageSize, String vCfCode, String vDevKindCode) {
        List<TVentilation> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = aerationRecordService.getList(vCfCode, vDevKindCode);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TVentilation> pageInfo = new PageInfo<TVentilation>(list);
        return ResponseEntity.ok(pageInfo);
    }

    @Autowired
    private SocketClient socketClient;

  //新增
    @RequestMapping(value = "/save", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "数据更新与添加", notes = "数据更新与添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "task", value = "所有id的Sting", paramType = "form"),
            @ApiImplicitParam(name = "aerationTaskControl", value = "表数据json串", paramType = "form"),
            @ApiImplicitParam(name = "orgId", value = "当前登录人组织id", paramType = "form"),
            @ApiImplicitParam(name = "saveType", value = "存储类型", paramType = "form")
    })
    public ResponseEntity save(String task, String aerationTaskControl, Integer orgId, String saveType) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        String result = "";
        try {
            //新增通风控制
            // 通风指令发送

            if(task!=null){

                String devinfo = "";
                if(!task.contains("[") && !task.contains("]")){
                   devinfo = "["+task+"]";  //task 包括id和vstatue
                }else{
                    devinfo = task;
                }
                List<TCtldevinfo> idObject = mapper.readValue(devinfo, new TypeReference<List<TCtldevinfo>>() {});
                TCtldevinfo tCtldevinfo = new TCtldevinfo();
                for(int i = 0;i<idObject.size();i++){
                    tCtldevinfo = aerationParameterService.getById(idObject.get(i).getId());
                    tCtldevinfo.setvState(Integer.valueOf(idObject.get(i).getVstatue()));
                    String dir = ConstUtils.directiveJoint("00", tCtldevinfo.getVcfcode(), tCtldevinfo.getVdevcode(), tCtldevinfo.getVdevkindcode(), "0" + tCtldevinfo.getVstatue(), "");
                    System.out.println(dir);
                    // 16进制字符串转byte数组
                    byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                    // 发送指令
                    String soc = socketClient.startClient(bytes);
                    result = TypeEnum.resultDispose(soc);
                    if(TypeEnum.S_SOH.getDesc().equals(result) && tCtldevinfo.getvState()!=Integer.valueOf(tCtldevinfo.getVstatue())){
                        aerationRecordService.save(tCtldevinfo, aerationTaskControl, orgId);
                    }
                    Thread.currentThread().sleep(2000);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("设备连接异常！！");
        }
        return ResponseEntity.ok(result);
    }

    //根据仓房和设备名称查询通风的记录
    @RequestMapping(value = "/getByCode", method = RequestMethod.POST)
    @ApiOperation(value = "根据仓房和设备名称查询信息", notes = "根据仓房和设备名称查询信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vcfcode", value = "vcfcode", paramType = "query"),
            @ApiImplicitParam(name = "vdevname", value = "vdevname", paramType = "query")
    })
    public ResponseEntity<TVentilation> getById(String vcfcode, String vdevname) {
        TVentilation tVentilation = null;
        if (StringUtils.isNotBlank(vcfcode) && StringUtils.isNotBlank(vcfcode)) {
            tVentilation = aerationRecordService.getByCode(vcfcode, vdevname);
        } else {
            return ResponseEntity.failed("ID数据有误!");
        }
        return ResponseEntity.ok(tVentilation);
    }

}
