package com.usoftchina.uas.office.qywx.config;

import com.usoftchina.qywx.sdk.*;
import com.usoftchina.qywx.sdk.config.Agent;
import com.usoftchina.qywx.sdk.config.QywxProperties;
import com.usoftchina.uas.office.qywx.manage.entity.QywxAgent;
import com.usoftchina.uas.office.qywx.manage.event.QywxAgentEvent;
import com.usoftchina.uas.office.qywx.manage.event.QywxCorpEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yingp
 * @date 2020/2/15
 */
@Configuration
public class QywxConfig {

    @Bean
    public QywxProperties qywxProperties() {
        return new QywxProperties();
    }

    @Bean
    public AddrBookSdk addrBookSdk() {
        return new AddrBookSdk(qywxProperties());
    }

    @Bean
    public MediaSdk mediaSdk() {
        return new MediaSdk(qywxProperties());
    }

    @Bean
    public MessageSdk messageSdk() {
        return new MessageSdk(qywxProperties());
    }

    @Bean
    public OaSdk oaSdk() {
        return new OaSdk(qywxProperties());
    }

    @Bean
    public ScheduleSdk scheduleSdk() {
        return new ScheduleSdk(qywxProperties());
    }

    @Autowired
    private QywxProperties qywxProperties;

    @EventListener(QywxCorpEvent.class)
    public void onQywxCorpEvent(QywxCorpEvent event) {
        qywxProperties.setCorpId(event.getCorpId());
    }

    @EventListener(QywxAgentEvent.class)
    public void onQywxAgentEvent(QywxAgentEvent event) {
        List<QywxAgent> agents = event.getAgents();
        if (null != agents) {
            qywxProperties.setAgents(agents.stream().map(agent -> new Agent(agent.getCode(), agent.getAgentId(), agent.getSecret(), agent.readonly()))
                    .collect(Collectors.toList()));
        } else {
            qywxProperties.setAgents(null);
        }
    }
}
