package org.ts.ddcs.task;



import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.ts.ddcs.common.command.CommandEntity;
import org.ts.ddcs.common.constant.GBConstants;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.tool.BytesUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;

/**
 * 交通规约拍照指令下发任务
 *
 * @author dylan
 */
public class JtTakePhotoTask implements Callable<Integer> {

    private byte[] getTakePhotoDatagram(String phoneKey) {
        byte[] funCode = new byte[2];
        funCode[0] = (byte) 0x88;
        funCode[1] = (byte) 0x01;
        byte[] respPacket = funCode;
        int len = 12;
        //消息属性
        byte[] lenBuf = BytesUtil.int2Bytes(len);
        String bin = BytesUtil.bytesToBinStr(lenBuf);
        String parameter = "010000" + bin.substring(bin.length() - 10, bin.length());
        lenBuf = BytesUtil.binStrToBytes(parameter);
        respPacket = BytesUtil.arrayApend(respPacket, lenBuf);
        //版本
        byte[] ver = new byte[1];
        ver[0] = (byte) 0x01;
        respPacket = BytesUtil.arrayApend(respPacket, ver);
        //手机号
        respPacket = BytesUtil.arrayApend(respPacket, BytesUtil.hexStr2Bytes(phoneKey));
        //流水号
        byte[] index = new byte[2];
        index[0] = (byte) 0x00;
        index[1] = (byte) 0x01;
        respPacket = BytesUtil.arrayApend(respPacket, index);
        byte[] bodyBuff = new byte[12];
        //通道ID
        bodyBuff[0] = 0x01;
        //拍摄命令
        //   if (type.equals("0")) {
        bodyBuff[1] = 0x00;
        bodyBuff[2] = 0x01;
        bodyBuff[3] = 0x00;
//        } else {
//            //  byte[] tmpBuff = BytesUtil.hexStr2Bytes("FF");
//            bodyBuff[1] = (byte) 0xff;
//            bodyBuff[2] = (byte) 0xff;
//            bodyBuff[3] = 0x05;
//        }
        bodyBuff[4] = 0x78;
        bodyBuff[5] = 0x00;
        bodyBuff[6] = (byte) 0x00;
        bodyBuff[7] = 0x01;
        bodyBuff[8] = (byte) 0xfe;
        bodyBuff[9] = 127;
        bodyBuff[10] = 127;
        bodyBuff[11] = (byte) 0xfe;
        respPacket = BytesUtil.arrayApend(respPacket, bodyBuff);
        int crc = respPacket[0];
        for (int i = 1; i < respPacket.length; i++) {
            crc = crc ^ respPacket[i];
        }
        byte[] crcBuff = new byte[1];
        crcBuff[0] = (byte) crc;
        respPacket = BytesUtil.arrayApend(respPacket, crcBuff);
        byte[] flag = new byte[1];
        flag[0] = 0x7e;
        byte[] respBuff = flag;
        respBuff = BytesUtil.arrayApend(respBuff, respPacket);
        respBuff = BytesUtil.arrayApend(respBuff, flag);
        return respBuff;
    }

    public void SubmitCommand(String rtuCode, String datagram, String funcCode) {
        try {
            CommandEntity entity = new CommandEntity();
            entity.setDatagram(datagram);
            entity.setRtuCode(rtuCode);
            entity.setNeedTry(false);
            entity.setTryCount(0);
            entity.setCreateTime(new Date());
            entity.setLiveTime(24 * 60);
            entity.setFuncCode(funcCode);
            entity.setWaittingBack(true);
            entity.setTry(false);

            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            ListOperations<String, String> opsList = redisTemplate.opsForList();
            String commandJsonStr = JSONObject.toJSONString(entity);
            LogHelper.info("query command :" + commandJsonStr);
            opsList.rightPush(entity.getRtuCode() + ":" + GBConstants.REDIS_KEY_COMMAND_QUERY, commandJsonStr);

        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    public  void SubmitCommand(String rtuCode, String datagram, String funcCode, boolean isSetting) {
        try {
            if (isSetting) {
                CommandEntity entity = new CommandEntity();
                entity.setDatagram(datagram);
                entity.setRtuCode(rtuCode);
                entity.setNeedTry(false);
                entity.setTryCount(0);
                entity.setCreateTime(new Date());
                entity.setLiveTime(24 * 60);
                entity.setFuncCode(funcCode);
                entity.setWaittingBack(true);
                entity.setTry(false);

                RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
                ListOperations<String, String> opsList = redisTemplate.opsForList();
                String commandJsonStr = JSONObject.toJSONString(entity);
                LogHelper.info("setting command :" + commandJsonStr);
                opsList.rightPush(entity.getRtuCode() + ":" + GBConstants.REDIS_KEY_COMMAND_SETTING, commandJsonStr);
            } else {
               SubmitCommand(rtuCode, datagram, funcCode);
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }


    @Override
    public Integer call() throws Exception {
        try {
            //查所有交通的设备
          //  byte[] command= getTakePhotoDatagram();


            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            if (null == redisTemplate) {
                return 0;
            }
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();

//            Set<String> keys = opsHash.keys("rtu_online");
//            if (null != keys && keys.size() > 0) {
//                for (String rtuCode : keys) {
//                    String projectId = opsHash.get(rtuCode, "projectId");
//                    if (null != projectId) {
//                        /**检查所属项目配置,规则：项目预警开关配置需要显式配置为开，才会进行预警检查，没有配置或配置成关，不进行预警检查**/
//                        boolean warningActive = false;
//                        ProjectWarningSettingInfo projectWarningSettingInfo = WarningHelper.getProjectWarningSetting(projectId, redisTemplate);
//                        if (null != projectWarningSettingInfo) {
//                            String globalSwitch = projectWarningSettingInfo.getGlobalSwitch();
//                            if (null != globalSwitch && globalSwitch.equals(GBConstants.WARNING_ACTIVE_ON)) {
//                                warningActive = true;
//                            }
//                        }
//                        if (warningActive) {
//                            /**检查项目在线预警类别是否打开**/
//                            String offlineSwitch = projectWarningSettingInfo.getOfflineSwitch();
//                            if (null != offlineSwitch && offlineSwitch.equals(GBConstants.WARNING_ACTIVE_ON)) {
//                                /**
//                                 * 检查RTU预警开关是否打开,在项目预警开关打时，如果RTU预警开关没有配置或配置成开，需要进行检测；只有明显设置成关，才不检测
//                                 */
//                                RtuWarningSettingInfo rtuWarningSettingInfo = WarningHelper.getRtuWarningSetting(rtuCode, redisTemplate);
//                                boolean rtuWarningActive = true;
//                                if (null != rtuWarningSettingInfo) {
//                                    String globalSwitch = rtuWarningSettingInfo.getGlobalSwitch();
//                                    if (null != globalSwitch && globalSwitch.equals(GBConstants.WARNING_ACTIVE_OFF)) {
//                                        rtuWarningActive = false;
//                                    }
//                                }
//                                if (rtuWarningActive) {
//                                    //最后上线时间
//                                    String lastOnlineTime = opsHash.get("rtu_online", rtuCode);
//                                    //默认在线维持时长
//                                    int durationMinute = DataProcessHolder.newInstance().dataProcess.config.getOnlineDuration();
//                                    //先从测站设置中取在线预警信息
//                                    if (null != rtuWarningSettingInfo) {
//                                        String offlineActive = rtuWarningSettingInfo.getOfflineWarningActive();
//                                        if (null != offlineActive && offlineActive.equals(GBConstants.WARNING_ACTIVE_ON)) {
//                                            String onlineDurationSetting = rtuWarningSettingInfo.getOfflineDuration();
//                                            if (null != onlineDurationSetting && onlineDurationSetting.length() > 0) {
//                                                durationMinute = Integer.parseInt(onlineDurationSetting);
//                                            }
//                                        } else {
//                                            //从项目设置中取在线预警信息
//                                            String onlineDurationSetting = projectWarningSettingInfo.getOfflineDuration();
//                                            if (null != onlineDurationSetting && onlineDurationSetting.length() > 0) {
//                                                durationMinute = Integer.parseInt(onlineDurationSetting);
//                                            }
//                                        }
//                                    } else {
//                                        //从项目设置中取在线预警信息
//                                        String onlineDurationSetting = projectWarningSettingInfo.getOfflineDuration();
//                                        if (null != onlineDurationSetting && onlineDurationSetting.length() > 0) {
//                                            durationMinute = Integer.parseInt(onlineDurationSetting);
//                                        }
//                                    }
//                                    Date lastOnlineDt = timeFormat.parse(lastOnlineTime);
//                                    long goingTm = checkTime.getTime() - lastOnlineDt.getTime();
//                                    if (goingTm > 0) {
//                                        goingTm = goingTm / (60 * 1000);
//                                    } else {
//                                        goingTm = 0;
//                                    }
//                                    if (goingTm >= durationMinute) {
//                                        WarningInfo warningInfo = WarningHelper.toWarningInfo(rtuCode, GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_HAPPEN, checkTime, "设备不在线", null);
//                                        //保存预警信息
//                                        DataProcessHolder.newInstance().dataProcess.warningService.saveWarning(warningInfo);
//                                        if (opsHash.hasKey(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE)) {
//                                            String warningStatusValue = opsHash.get(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE);
//                                            //只在第一次预警时处理
//                                            if (null == warningStatusValue || warningStatusValue.equals(GBConstants.WARNING_STATUS_RECOVERY)) {
//                                                //更新缓存
//                                                opsHash.put(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_HAPPEN);
//                                                //推送预警信息
//                                                DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(warningInfo);
//                                            }
//                                        } else {
//                                            //更新缓存
//                                            opsHash.put(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_HAPPEN);
//                                            //推送预警信息
//                                            DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(warningInfo);
//                                        }
//                                    } else {
//                                        WarningInfo warningInfo = WarningHelper.toWarningInfo(rtuCode, GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_RECOVERY, checkTime, "设备在线恢复", null);
//                                        //保存预警信息
//                                        DataProcessHolder.newInstance().dataProcess.warningService.warningRecovery(warningInfo);
//                                        if (opsHash.hasKey(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE)) {
//                                            String warningStatus = opsHash.get(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE);
//                                            if (null != warningStatus && warningStatus.equals(GBConstants.WARNING_STATUS_HAPPEN)) {
//                                                //更新缓存
//                                                opsHash.put(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_RECOVERY);
//                                                //推送预警信息
//                                                DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(warningInfo);
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return 0;
    }
}
