package com.willalp.control.netty.service.impl;

import com.willalp.common.exception.GlobalException;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.control.netty.model.ControlDataModel;
import com.willalp.control.netty.service.CommandControlService;
import com.willalp.control.netty.service.CommandNettyService;
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;


/**
 * @author xian
 * @Description 基站交互接口实现类
 * @date 2021/7/31
 */
@Service
public class CommandNettyServiceImpl implements CommandNettyService {
    protected final static Logger logger = LoggerFactory.getLogger(CommandNettyServiceImpl.class);


    @Resource
    private ControlDataModel commandDataControl;

    @Resource
    private CommandControlService commandControlService;

    @Resource
    private DeviceMapper deviceMapper;


    @Override
    public void commandServiceControl(String str, String ipAddr) {
        if (StringUtils.isBlank(str)) {
            return;
        }
        /*
         *  拆分收到的指令
         *  示例：HS01010000002C00000000000000000000WP
         *    针头: HS                       strings[0]
         *    通讯地址: 0101000000            strings[1]
         *    指令类型: 2C                    strings[2]
         *    指令内容: 000000000000000000    strings[3]
         *    返回结果: 00                    strings[4]
         *    针尾: WP                       strings[5]
         */
        String[] strings = commandControlService.dismantlingCommand(str);
        if (null == strings) {
            return;
        }
        //拆分五级地址
/*        String[] fiveAddress = commandControlService.parsingInstructions(strings[1]);
        String executiveUnit = null;
        for (int i = 0; i < fiveAddress.length; i++) {
            //获取第一个为00的地址的下标
            if (WCmdGrid.RETURN_SUCCESS.equals(fiveAddress[i])) {
                if (i != 0) {
                    //获取到上一级 确定执行单位
                    executiveUnit = fiveAddress[i - 1];
                    break;
                } else {
                    return;
                }
            }
        }
        if (StringUtils.isBlank(executiveUnit)) {
            return;
        }*/
        long txAddress = Long.parseLong(strings[2], 16);

/*        if (0 < txAddress && 36 >= txAddress) {
            commandControlService.lockControlBoardLogicControl(strings, ipAddr);
        } else if (43 == txAddress) {
            commandControlService.icCardLogicControl(strings, ipAddr);
        } else if (37 <= txAddress && 42 >= txAddress) {
            commandControlService.fingerprintLogicControl(strings, ipAddr);
        } else if (44 == txAddress) {
            commandControlService.lockControlBoardLogicControl(strings, ipAddr);
        } else {
            logger.info("没有找到对应的控制");
        }*/

        /*//边缘数采前置机
        if (txAddress > 0 && txAddress <= 100) {

        }
        //多功能控制器
        else if (txAddress >= 101 && txAddress <= 200) {

        }
        //IC卡/读卡器模块
        else if (txAddress >= 201 && txAddress <= 210) {
        }
        //指纹模块
        else if (txAddress >= 211 && txAddress <= 220) {
        }
        //二维码模块
        else if (txAddress >= 221 && txAddress <= 230) {

        }
        //锁控板模块
        else if (txAddress >= 231 && txAddress <= 240) {
            commandControlService.lockControlBoardLogicControl(strings);
        }
        //其他
        else if (txAddress >= 241 && txAddress <= 250) {

        }
        //其他
        else if (txAddress >= 251 && txAddress <= 255) {

        }
*/
    }


    /**
     * 获取需要发送命令的基站IP
     *
     * @param deviceId
     * @return
     */
    @Override
    public String getNeedSendCommandBaseStationIp(String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            throw new BaseException("设备信息ID不得为空");
        }
        Device device = deviceMapper.selectById(deviceId);
        if (null == device) {
            throw new BaseException("此设备暂无配置信息，或不存在");
        }
        String deviceIpAddr = device.getDeviceIpAddr();
        if (null == deviceIpAddr) {
            throw new BaseException("此设备还未配置IP");
        }
        return deviceIpAddr;
    }

    @Override
    public String waitingToReceiveData(String baseIp, int type) {
        //开始等待时间   默认: 15s 没有结果，则结束请求
        long beginTime = System.currentTimeMillis();

        try {
            for (; ; ) {
                if (baseIp.equals(commandDataControl.getBreakOffIp())) {
                    if (type == commandDataControl.getBreakOffType()) {
                        BaseException nowBreakOff = new BaseException("已中断");
                        nowBreakOff.setCode("444");
                        logger.info(Thread.currentThread().getName() + " - 已中断");
                        throw nowBreakOff;
                    }
                }
                //阻塞线程释放占用的cpu资源  优化无限循环对cpu的占用
                Thread.sleep(100);

                if (StringUtils.isNotBlank(baseIp)) {
                    //锁定基站IP 获取数据
                    if (baseIp.equals(commandDataControl.getLockIp())) {
                        switch (type) {
                            case 1:
                                break;
                            case 2:
                                break;
                            case 3:
                                break;
                            default:
                                throw new GlobalException("识别类型传递出错");
                        }
                    }
                    //等待 15s 结束
                    if (beginTime + ControlDataModel.OVER_TIME <= System.currentTimeMillis()) {
                        throw new GlobalException("已等待超时，请重试");
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ControlDataModel.ERROR_LOGO;
    }

    @Override
    public String getCommandToStr(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        return ControlDataModel.PINHEAD + "0102030405" + str + ControlDataModel.RETURN_SUCCESS + ControlDataModel.PIN_TAIL;
    }

}
