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

import com.usoftchina.qywx.sdk.AddrBookSdk;
import com.usoftchina.qywx.sdk.OaSdk;
import com.usoftchina.qywx.sdk.ScheduleSdk;
import com.usoftchina.uas.office.context.ContextHolder;
import com.usoftchina.uas.office.event.DataCenterEvent;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.qywx.manage.entity.QywxAgent;
import com.usoftchina.uas.office.qywx.manage.event.QywxAgentEvent;
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 QywxAgentService extends AbstractService {

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

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

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

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

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

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

    @Async
    @EventListener(DataCenterEvent.class)
    public void onDataCenterEvent(DataCenterEvent event) throws Exception {
        try {
            DataSourceHolder.set(event.getDataCenter());
            List<QywxAgent> agents = findAll();
            if (CollectionUtils.isEmpty(agents)) {
                agents = new ArrayList<>();
                // 初始化
                agents.add(new QywxAgent(AddrBookSdk.ADDRESS_BOOK_AGENT_CODE, "通讯录"));
                agents.add(new QywxAgent(OaSdk.CHECKIN_AGENT_CODE, "打卡"));
                agents.add(new QywxAgent(ScheduleSdk.SCHEDULE_AGENT_CODE, "日程"));
                agents.add(new QywxAgent("Uas", "Uas系统"));
                agents.add(new QywxAgent("UasAudit", "U审批"));
                agents.add(new QywxAgent("UasSubscribe", "U订阅"));
                agents.add(new QywxAgent("UasReport", "U报表"));
                jdbcTemplate.batchUpdate("insert into QywxAgent(code,description,readonly) values (?,?,?)",
                        agents.stream().map(agent -> new Object[]{agent.getCode(), agent.getDescription(), agent.getReadonly()})
                                .collect(Collectors.toList()));
            }
            ContextHolder.getApplicationContext().publishEvent(new QywxAgentEvent(this, agents));
        } finally {
            DataSourceHolder.clear();
        }
    }
}
