package com.zd.laboratory.controller.device;

import com.zd.common.core.domain.R;
import com.zd.common.core.utils.ReUtil;
import com.zd.common.redis.service.RedisService;
import com.zd.laboratory.socket.runner.TCPServer;
import com.zd.laboratory.socket.service.SocketService;
import com.zd.laboratory.utils.CRCCHECK;
import com.zd.system.api.domain.PlayVo;
import com.zd.system.api.laboratory.CabinetV2Lock;
import com.zd.system.api.laboratory.domain.CabinetLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * 设备远程控制接口
 */
@RestController
@RequestMapping("/device/remote")
public class DeviceRemoteController {
    private static Logger logger = LoggerFactory.getLogger(DeviceRemoteController.class);

    @Autowired
    private SocketService socketService;
    @Autowired
    private RedisService redisService;


    @PostMapping("/cabinetLock")
    public R cabinetLock(@RequestBody @Valid CabinetLock cabinetLock){
        socketService.sendWriteHelmCommand(
                cabinetLock.getLockId(),
                cabinetLock.getPosition(),
                cabinetLock.getTime(),
                cabinetLock.getSpeed());
        return R.ok();
    }

    @PostMapping("/V2/openLock")
    public R cabinetV2OpenLock(@RequestBody CabinetV2Lock cabinetV2Lock){
        String instruct = CRCCHECK.getOpenLockOrder(Integer.parseInt(cabinetV2Lock.getLockId()));
        String relayCode = cabinetV2Lock.getRelayCode();
        OutputStream ops = TCPServer.cacheMap.get(relayCode);

        try {
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();
            logger.info("柜锁开锁指令：" + instruct);

            Thread.sleep(500);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();

            Thread.sleep(300);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();
            Thread.sleep(500);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();
            Thread.sleep(300);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();
            Thread.sleep(500);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();
            Thread.sleep(300);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();

            instruct = CRCCHECK.getReadLockOrder(Integer.parseInt(cabinetV2Lock.getLockId()));
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();

            Thread.sleep(500);
            Integer status = redisService.getCacheObject(relayCode + ":" + cabinetV2Lock.getLockId());
            logger.info("柜锁开锁锁状态查询：" + instruct + "，开锁结果：" + status);
            /*if(status != null && status == 1){
                return R.ok("开锁成功");
            }*/
            // TODO 因样件锁 发送开锁指令后锁未主动弹开，先不关注锁的状态
            return R.ok("开锁成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("柜锁连接失败：" + e.getMessage());
            return R.fail("柜锁连接失败！");
        }
        //return R.fail("开锁失败");
    }

    /**
     * 柜锁关锁锁 V2
     */
    @PostMapping("/V2/closeLock")
    public R cabinetV2CloseLock(@RequestBody CabinetV2Lock cabinetV2Lock){
        String instruct = CRCCHECK.getCloseLockOrder(Integer.parseInt(cabinetV2Lock.getLockId()));
        String relayCode = cabinetV2Lock.getRelayCode();
        OutputStream ops = TCPServer.cacheMap.get(relayCode);

        try {
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();
            logger.info("柜锁关锁指令：" + instruct);
            Thread.sleep(1000);

            instruct = CRCCHECK.getReadLockOrder(Integer.parseInt(cabinetV2Lock.getLockId()));
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();

            Thread.sleep(600);
            ops.write(ReUtil.hexStringToByteArray(instruct));
            ops.flush();

            Thread.sleep(900);
            Integer status = redisService.getCacheObject(relayCode + ":" + cabinetV2Lock.getLockId());
            logger.info("柜锁关锁状态查询：" + instruct + "，关锁结果" + status);
            if(status != null && status == 0){
                return R.ok("关锁成功");
            }
//            return R.ok("关锁成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("柜锁连接失败：" + e.getMessage());
            return R.fail("柜锁连接失败！");
        }
        return R.fail("关锁失败：请手动按压柜锁，确认已关闭！");
    }
}
