package com.willalp.control.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.control.domain.HsControlTiming;
import com.willalp.control.domain.HsControlUsenoConfig;
import com.willalp.control.domain.vo.OpenOrCloseVo;
import com.willalp.control.mapper.HsControlUsenoConfigMapper;
import com.willalp.control.netty.handler.RwxdSocket;
import com.willalp.control.netty.model.ControlDataModel;
import com.willalp.control.netty.service.CommandControlService;
import com.willalp.control.netty.service.CommandNettyService;
import com.willalp.control.service.ControlService;
import com.willalp.control.service.IHsControlDeviceInfoService;
import com.willalp.control.service.IHsControlLogService;
import com.willalp.control.service.IHsControlTimingService;
import com.willalp.device.domain.Device;
import com.willalp.device.mapper.DeviceMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author hs
 * <p>
 * 控制业务实现类
 */
@Service
public class ControlServiceImpl implements ControlService {
    private static final Logger log = LoggerFactory.getLogger(ControlServiceImpl.class);

    @Resource
    private IHsControlDeviceInfoService deviceInfoService;

    @Resource
    private HsControlUsenoConfigMapper useNoConfigMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private CommandNettyService commandNettyService;


    @Override
    public int openOrClose(OpenOrCloseVo openOrCloseVo) {
        int isOpenOrClose = openOrCloseVo.getIsOpenOrClose();
        String useNoId = openOrCloseVo.getUseNoId();
        String deviceId = openOrCloseVo.getDeviceId();
        String deviceInfoId = openOrCloseVo.getDeviceInfoId();
        if (StringUtils.isBlank(useNoId)) {
            throw new BaseException("control.useNoId.null", new Object[]{openOrCloseVo.toString()});
        }
        if (StringUtils.isBlank(deviceId)) {
            throw new BaseException("基站ID不得为空");
        }
        if (StringUtils.isBlank(deviceInfoId)) {
            throw new BaseException("设备信息ID不得为空");
        }
        //查询执行口
        HsControlUsenoConfig useNoConfig = useNoConfigMapper.selectById(useNoId);
        //判断发送 开还是关
        String command = isOpenOrClose == 0 ? useNoConfig.getCommandClose() : useNoConfig.getCommandOpen();
        command = commandNettyService.getCommandToStr(command);
        Device device = deviceMapper.selectById(deviceId);
        String deviceIpAddr = device.getDeviceIpAddr();
        //发送指令 发送成功后 异步 修改灯信息
        if (RwxdSocket.sendDeviceCommand(command, deviceIpAddr)) {
            //修改 设备（灯）运行信息 并生成日志
            deviceInfoService.openOrCloseUpdateDeviceInfo(openOrCloseVo);
            String text = isOpenOrClose == 0 ? "{ 关" : "{ 开";
            log.info(text + " }指令 - 发送成功");
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public void getIpAndCmdByUseNoIdAndSend(Long useNoId, int openOrClose) {
        HsControlUsenoConfig useNoConfig = ControlDataModel.useMap.get(useNoId);
        if (ObjectUtil.isNull(useNoConfig)) {
            throw new BaseException("查询{jvm}中{执行口信息} - 为空 - 参数：" + useNoId, new Object[]{useNoId});
        }
        Device device = ControlDataModel.deviceMap.get(useNoConfig.getDeviceId());
        if (ObjectUtil.isNull(device)) {
            throw new BaseException("查询 {jvm} 中 {设备信息} - 为空 - 参数：" + useNoConfig.getDeviceId(),
                    new Object[]{useNoConfig.getDeviceId()});
        }
        String ipAddr = device.getDeviceIpAddr();
        String command = openOrClose == 1 ?
                useNoConfig.getCommandOpen() : useNoConfig.getCommandClose();
        String commandToStr = commandNettyService.getCommandToStr(command);
        RwxdSocket.sendDeviceCommand(commandToStr, ipAddr);
        //异步更新
        deviceInfoService.timingOpenOrCloseUpdateDeviceInfo(useNoId, openOrClose);
    }

    @Override
    public void asyncTimingStartOrEnd(List<HsControlTiming> list, int startOrEnd) {
        for (HsControlTiming t : list) {
            //获取DB中存储的时间
            Time dbTime = 0 == startOrEnd ? t.getEndTime() :
                    t.getStartTime();
            //获取当前 时:分
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            /*测试变量 */
            //String nowTime = dateFormat.format(new Date(0, Calendar.JANUARY, 0, 9, 22, 0));
            String nowTime = dateFormat.format(new Date());
            //拆分比对 时分
            String[] dbStartTimes = dbTime.toString().split(":");
            String[] nowTimes = nowTime.split(":");
            //比对 时 部分
            if (dbStartTimes[0].equals(nowTimes[0])) {
                //比对 分 部分
                if (dbStartTimes[1].equals(nowTimes[1])) {
                    this.getIpAndCmdByUseNoIdAndSend(t.getUseNoId(), startOrEnd);
                }
            }
        }
    }
}
