package com.willalp.control.netty.model;

import com.willalp.control.domain.HsControlUsenoConfig;
import com.willalp.control.service.IHsControlUsenoConfigService;
import com.willalp.device.domain.Device;
import com.willalp.device.service.IDeviceService;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author xian
 */
@Data
@Component
public class ControlDataModel {
    /**
     * 针头
     */
    public static final String PINHEAD = "HS";
    /**
     * 针尾
     */
    public static final String PIN_TAIL = "WP";
    /**
     * 返回值：成功
     */
    public static final String RETURN_SUCCESS = "00";
    /**
     * 针头
     */
    public static final String ERROR_LOGO = "ERROR";
    /**
     * 等待数据时 超时时间
     */
    public static final long OVER_TIME = 15 * 1000;

    private final String[] weekDays = {"0", "1", "2", "3", "4", "5", "6"};

    public String getWeek() {
        Calendar calendar = Calendar.getInstance();
        return weekDays[calendar.get(Calendar.DAY_OF_WEEK) - 1];
    }

    /**
     * 执行口jvm缓存
     */
    public static Map<Long, HsControlUsenoConfig> useMap = new HashMap<>(16);

    /**
     * 设备jvm缓存
     */
    public static Map<String, Device> deviceMap = new HashMap<>(16);

    /**
     * 等待延迟时间
     */
    public static final Map<String, Date> WAIT_MAP = new Hashtable<>(16);

    @Resource
    private IHsControlUsenoConfigService useNoConfigService;
    @Resource
    private IDeviceService deviceService;
    /**
     * 共享通道 Map<IP地址,数据>
     */
    private Map<String, String[]> dataIntermediaryMap;
    /**
     * 锁定IP
     */
    private String lockIp;
    /**
     * 需要中断的IP
     */
    private String breakOffIp = "";
    /**
     * 需要中断的类型
     */
    private int breakOffType;

    @PostConstruct
    public void updateMap() {
        List<HsControlUsenoConfig> list1 = useNoConfigService.list(null);
        if (0 != list1.size()) {
            list1.forEach((d) -> useMap.put(d.getUseNoId(), d));
        }
        List<Device> list2 = deviceService.list(null);
        if (0 != list2.size()) {
            list2.forEach((d) -> deviceMap.put(d.getDeviceId(), d));
        }
    }

    /**
     * 清除缓存数据
     */
    public void clear() {
        this.dataIntermediaryMap.clear();
        this.lockIp = null;
    }

    /**
     * 中断等待中的数据
     */
    public void cancelBreakOff() {
        breakOffIp = null;
        breakOffType = 0;
    }

}
