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

import com.chinaitop.depot.intelligent.common.ConstantClass;
import com.chinaitop.depot.intelligent.socket.SocketServer;
import com.chinaitop.depot.intelligent.utils.ParameterUtil;
import com.chinaitop.depot.intelligent.ventilation.model.TCtldevinfo;
import com.chinaitop.depot.intelligent.ventilation.model.TCtldevinfoBype;
import com.chinaitop.depot.intelligent.ventilation.model.TVentilation;
import com.chinaitop.depot.intelligent.ventilation.service.AerationBypeService;
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 javax.annotation.Resource;
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;
    @Autowired
    private AerationBypeService bypeService;
    @Resource
    private SocketServer socketServer;


    @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, String type) {
        List<TVentilation> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = aerationRecordService.getList(vCfCode, vDevKindCode, type);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TVentilation> pageInfo = new PageInfo<TVentilation>(list);
        return ResponseEntity.ok(pageInfo);
    }

    //新增
    @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 (ParameterUtil.isnotnull(saveType) && ParameterUtil.isequal(saveType, "fumigationData")) {//新增熏蒸的通风控制
                aerationRecordService.saveFumigation(task, aerationTaskControl, orgId);
            } else {//新增通风控制
                // 通风指令发送
                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>>() {
                    });
                    for (int i = 0; i < idObject.size(); i++) {
                        TCtldevinfo tCtldevinfo = aerationParameterService.getById(idObject.get(i).getId());
                        //获取设备指令信息
                        TCtldevinfoBype aByte = bypeService.getByte(Integer.valueOf(tCtldevinfo.getVdevkindcode()));
                        //0:关闭,1:打开,2:反转,3:停止 上次操作在库里保存的 状态
//                        String vstatue = tCtldevinfo.getVstatue();
                        // 用户操作的是开启还是关闭
                        String userUseState = idObject.get(i).getVstatue();
                        String stopOrStart = "";
                        if (userUseState.equals(ConstantClass.TYPE_OFF)) {
                            stopOrStart = aByte.getTcStop();
                        } else if (userUseState.equals(ConstantClass.TYPE_NO)) {
                            stopOrStart = aByte.getTcStart();
                        }
                        // 调用socketServer,发送指令
                        result = socketServer.service(tCtldevinfo.getCtIp(), stopOrStart, 0);// 新增通风作业记录
                        aerationRecordService.save(tCtldevinfo, aerationTaskControl, orgId);
                    }
                }
            }
            // 返回结果处理方法
            return ResponseEntity.ok(socketServer.responseResultForPLC(result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed(TypeEnum.S_STX.getDesc());
        }
    }

    //根据仓房和设备名称查询通风的记录
    @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);
    }


    @RequestMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "数据更新与添加", notes = "数据更新与添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tVentilationJson", value = "表数据json串", paramType = "form")
    })
    public ResponseEntity add(String tVentilationJson, Integer orgId) {
        try {
            aerationRecordService.add(tVentilationJson, orgId);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.failed(e.getMessage());
        }
        return ResponseEntity.ok();
    }


    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ApiOperation(value = "根据粮情id删除信息", notes = "根据粮情id删除信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "粮情id", paramType = "query"),
            @ApiImplicitParam(name = "aerationParamJson", value = "通风参数json字符串", paramType = "query")
    })
    public ResponseEntity deleteById(String id) {
        if (StringUtils.isNotBlank(id)) {
            int count = aerationRecordService.deleteById(id);
            if (count > 0) {
                return ResponseEntity.ok();
            } else {
                return ResponseEntity.failed("删除失败!");
            }
        }
        return ResponseEntity.failed("ID数据有误!");
    }

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


    /**
     * TODO /test 测试ServerSocket 接口
     * http://localhost:9028/intelligents/aerationRecord/test?ip=10.100.208.225&orders=AA 00 00
     *
     * @param ip
     * @param orders
     */
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(String ip, String orders, int type) {
        String service = socketServer.service(ip, orders, type);
        String s = socketServer.responseResultForPLC(service);
        return service + ":" + s;
    }

}
