package com.sw.mes.outside.service.impl;

import cn.hutool.core.convert.Convert;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.NumberUtil;
import com.sw.mes.outside.dto.IpcButtonControlTimeParam;
import com.sw.mes.redis.server.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @author liuzemin
 * @date 2023/1/31 13:17
 * @description
 */
@Service
public class IpcButtonControlService {

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private RedisUtils redisUtils;

    //工控机按钮时间控制
    public void ipcButtonControlTime(IpcButtonControlTimeParam param){
        DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("IPCButtonControl", param.getButtonName(), true);
        String time = Optional.ofNullable(item).map(DictionaryItem::getValue).orElse(param.getDefaultTime());
        String shutdownTimeStr
                = NumberUtil.object2String(redisUtils.hmGet(param.getKey(), param.getEquipmentCode()), null);
        Date shutdownTime = DateUtil.toDateNull(shutdownTimeStr, DateUtil.longFormat);
        if (shutdownTime != null && (System.currentTimeMillis() - shutdownTime.getTime()) < 1000 * 60 * Convert.toInt(time, 600)) {
            throw new RuntimeException("距离上次"+ param.getButtonOtherName() +"时间（" + shutdownTimeStr + "），不足"+time+"分钟，请不要频繁进行补"+ param.getButtonOtherName() +"信号操作");
        }
    }
}
