package com.gitee.sop.admin.service.isv.listener;

import com.gitee.sop.admin.dao.entity.IsvInfo;
import com.gitee.sop.admin.dao.mapper.IsvInfoMapper;
import com.gitee.sop.admin.service.isv.event.ChangeApiInfoEvent;
import com.gitee.sop.admin.service.isv.event.ChangeIsvInfoEvent;
import com.gitee.sop.admin.service.isv.event.ChangeIsvKeyEvent;
import com.gitee.sop.admin.service.isv.event.ChangeIsvPermEvent;
import com.gitee.sop.support.service.RefreshService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * 变更监听
 *
 * @author 六如
 */
@Component
public class ChangeListener {

    @DubboReference
    private RefreshService refreshService;

    @Autowired
    private IsvInfoMapper isvInfoMapper;

    /**
     * 监听isv信息变更
     *
     * @param event
     */
    @EventListener
    public void onChangeApiInfoEvent(ChangeApiInfoEvent event) {
        Collection<Long> apiIds = event.getApiIds();
        refreshService.refreshApi(apiIds);
    }

    /**
     * 监听isv信息变更
     *
     * @param event
     */
    @EventListener
    public void onChangeIsvInfoEvent(ChangeIsvInfoEvent event) {
        Collection<Long> isvIds = event.getIsvIds();
        Collection<String> appIds = isvInfoMapper.query()
                .in(IsvInfo::getId, isvIds)
                .listUniqueValue(IsvInfo::getAppId);
        refreshService.refreshIsv(appIds);
    }

    /**
     * 监听isv秘钥变更
     *
     * @param event
     */
    @EventListener
    public void onChangeIsvKeyEvent(ChangeIsvKeyEvent event) {
        List<Long> isvIds = event.getIsvIds();
        refreshService.refreshSecret(isvIds);
    }

    /**
     * 监听isv分组变更
     *
     * @param event
     */
    @EventListener
    public void onChangeIsvGroupEvent(ChangeIsvPermEvent event) {
        List<Long> isvIds = event.getIsvIds();
        refreshService.refreshIsvPerm(isvIds);
    }

}
