package com.ym.mec.biz.event.listener;

import com.ym.mec.biz.dal.dao.OrganizationDao;
import com.ym.mec.biz.dal.entity.Organization;
import com.ym.mec.biz.event.SendSeoMessageChangeEvent;
import com.ym.mec.biz.service.SysEmployeePositionService;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.common.tenant.TenantContextHolder;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;

//发送站内消息
@Component
public class SendSeoMessageListener implements ApplicationListener<SendSeoMessageChangeEvent> {

    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private SysEmployeePositionService employeePositionService;
    @Resource
    private OrganizationDao organizationDao;

    @Async
    @Override
    public void onApplicationEvent(SendSeoMessageChangeEvent event) {
        Organization organization = organizationDao.get(event.getOrganId());
        TenantContextHolder.setTenantId(organization.getTenantId());
        //获取当前分部，指定角色的用户列表
        Set<Integer> targetUserIdList = employeePositionService.queryUserIdByRoleId(event.getRoleArr(), organization.getId());
        if(event.getTargetId() != null){
            targetUserIdList.add(event.getTargetId());
        }
        if(targetUserIdList.size() > 0){
            sysMessageService.batchSeoMessage(targetUserIdList,
                    event.getMsgTemplate(),
                    event.getMemo(),
                    Arrays.stream(event.getArgs()).toArray(Object[]::new));
        }
        TenantContextHolder.clearTenantId();
    }
}
