package com.usoftchina.uas.office.dingtalk.manage.service;

import com.usoftchina.uas.office.context.ContextHolder;
import com.usoftchina.uas.office.dingtalk.manage.entity.DingTalkAgent;
import com.usoftchina.uas.office.dingtalk.manage.event.DingTalkAgentEvent;
import com.usoftchina.uas.office.event.DataCenterEvent;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.service.AbstractService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @author yingp
 * @date 2020/2/15
 */
@Service
public class DingTalkAgentService extends AbstractService {

    @Cacheable(value = "DingTalkAgent", key = "#code")
    public DingTalkAgent findByCode(String code) {
        return queryForBean("select * from DingTalkAgent where code=?", DingTalkAgent.class, code);
    }

    public List<DingTalkAgent> findAll() {
        return queryForBeanList("select * from DingTalkAgent order by code", DingTalkAgent.class);
    }

    @CacheEvict(value = "DingTalkAgent", key = "#agent.code")
    public void save(DingTalkAgent agent) {
        if (!StringUtils.isEmpty(agent.getOuterUrl())) {
            if (!agent.getOuterUrl().endsWith("/")) {
                agent.setOuterUrl(agent.getOuterUrl() + "/");
            }
        }
        int count = queryForObject("select count(1) from DingTalkAgent where code=?", Integer.class, agent.getCode());
        if (count == 0) {
            jdbcTemplate.update("insert into DingTalkAgent(code,description,agent_id,app_key,app_secret,outer_url) values (?,?,?,?,?,?)",
                    agent.getCode(), agent.getDescription(), agent.getAgentId(), agent.getAppKey(), agent.getAppSecret(), agent.getOuterUrl());
        } else {
            jdbcTemplate.update("update DingTalkAgent set description=?,agent_id=?,app_key=?,app_secret=?,outer_url=? where code=?",
                    agent.getDescription(), agent.getAgentId(), agent.getAppKey(), agent.getAppSecret(), agent.getOuterUrl(), agent.getCode());
        }

        ContextHolder.getApplicationContext().publishEvent(new DingTalkAgentEvent(this, findAll()));
    }

    @CacheEvict(value = "DingTalkAgent", key = "#code")
    public void delete(String code) {
        jdbcTemplate.update("delete from DingTalkAgent where code=?", code);

        ContextHolder.getApplicationContext().publishEvent(new DingTalkAgentEvent(this, findAll()));
    }

    @Async
    @EventListener(DataCenterEvent.class)
    public void onDataCenterEvent(DataCenterEvent event) throws Exception {
        try {
            DataSourceHolder.set(event.getDataCenter());
            List<DingTalkAgent> agents = findAll();
            if (CollectionUtils.isEmpty(agents)) {
                agents = new ArrayList<>();
                // 初始化
                agents.add(new DingTalkAgent("Uas", "UAS系统"));
                jdbcTemplate.batchUpdate("insert into DingTalkAgent(code,description) values (?,?)",
                        agents.stream().map(agent -> new Object[]{agent.getCode(), agent.getDescription()})
                                .collect(Collectors.toList()));
            }
            ContextHolder.getApplicationContext().publishEvent(new DingTalkAgentEvent(this, agents));
        } finally {
            DataSourceHolder.clear();
        }
    }
}
