package com.rongwei.bscommon.sys.utils;

import com.rongwei.bscommon.sys.dao.ApsProcessOperationBackupDao;
import com.rongwei.bscommon.sys.dao.ApsProcessOperationProcessEquBackupDao;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.exception.CustomException;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.CXCommonUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * ApsUtils class
 *
 * @author XH
 * @date 2024/05/07
 */
@Component
public class ApsUtils {
    private static final Logger log = LoggerFactory.getLogger(ApsUtils.class.getName());
    private static ApsProcessOperationBackupDao apsProcessOperationBackupDao;
    private static ApsProcessOperationProcessEquBackupDao apsProcessOperationProcessEquBackupDao;
    private static RedissonClient redissonClient;
    @Autowired
    private ApsProcessOperationBackupDao autoApsProcessOperationBackupDao;
    @Autowired
    private ApsProcessOperationProcessEquBackupDao autoApsProcessOperationProcessEquBackupDao;
    @Autowired
    private RedissonClient autoredissonClient;
    @PostConstruct
    public void info() {
        apsProcessOperationBackupDao = autoApsProcessOperationBackupDao;
        apsProcessOperationProcessEquBackupDao = autoApsProcessOperationProcessEquBackupDao;
        redissonClient = autoredissonClient;
    }
    /**
     * 删除当前员工所属工厂的排程备份信息
     *
     * @param currentUser
     */
    public static void clearBackup(SysUserVo currentUser) {
        if (currentUser == null) {
            currentUser = CXCommonUtils.getCurrentUser();
        }
        String factoryId = CXCommonUtils.getCurrentUserFactoryId(currentUser);
        log.info("开始删除工厂：{}的排除备份数据", factoryId);
        // 先删除
        apsProcessOperationBackupDao.deletedByBlankId(null, factoryId);
        apsProcessOperationProcessEquBackupDao.deletedByBlankId(null, factoryId);
    }

    /**
     * 校验当前是否正在排程中
     * 正在排程的情况下抛出异常
     */
    public static void checkScheduling(SysUserVo currentUser ) {
        // 当前等路人所属工厂
        if(currentUser==null){
            currentUser = CXCommonUtils.getCurrentUser();
        }
        String tenantId = currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1];
        if (StringUtils.isBlank(tenantId)) {
            throw new CustomException("当前用户所属工厂信息为空");
        }
        // 按照所属工厂加锁
        RLock rLock = redissonClient.getLock(tenantId);
        boolean isLocked = rLock.isLocked();
        // 锁是否被占用
        if (isLocked) {
            throw new CustomException("正在排程、请稍等一会！");
        }
    }




}
