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

import com.usoftchina.dingtalk.sdk.*;
import com.usoftchina.dingtalk.sdk.config.Agent;
import com.usoftchina.dingtalk.sdk.config.DingTalkProperties;
import com.usoftchina.uas.office.dingtalk.manage.entity.DingTalkAgent;
import com.usoftchina.uas.office.dingtalk.manage.event.DingTalkAgentEvent;
import com.usoftchina.uas.office.dingtalk.manage.event.DingTalkCorpEvent;
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/19
 */
@Configuration
public class DingTalkConfig {
    @Bean
    public DingTalkProperties dingTalkProperties() {
        return new DingTalkProperties();
    }

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

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

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

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

    @Bean
    public WorkRecordSdk workRecordSdk() {
        return new WorkRecordSdk(dingTalkProperties());
    }

    @Autowired
    private DingTalkProperties dingTalkProperties;

    @EventListener(DingTalkCorpEvent.class)
    public void onDingTalkCorpEvent(DingTalkCorpEvent event) {
        dingTalkProperties.setCorpId(event.getCorpId());
    }

    @EventListener(DingTalkAgentEvent.class)
    public void onDingTalkAgentEvent(DingTalkAgentEvent event) {
        List<DingTalkAgent> agents = event.getAgents();
        if (null != agents) {
            dingTalkProperties.setAgents(agents.stream().map(agent -> new Agent(agent.getCode(), agent.getAgentId(), agent.getAppKey(), agent.getAppSecret()))
                    .collect(Collectors.toList()));
        } else {
            dingTalkProperties.setAgents(null);
        }
    }
}
