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

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.QywxSetting;
import com.usoftchina.uas.office.qywx.manage.event.QywxCorpEvent;
import com.usoftchina.uas.office.service.AbstractService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author yingp
 * @date 2020/2/17
 */
@Service
public class QywxSettingService extends AbstractService {

    public QywxSetting find() {
        return queryForBean("select * from QywxSetting", QywxSetting.class);
    }

    public void setCorpId(String corpId) {
        QywxSetting setting = find();
        if (null == setting) {
            jdbcTemplate.update("insert into QywxSetting(corp_id) values (?)", corpId);
        } else {
            jdbcTemplate.update("update QywxSetting set corp_id=?", corpId);
        }
        ContextHolder.getApplicationContext().publishEvent(new QywxCorpEvent(this, corpId));
    }

    public Long getCheckinTime() {
        QywxSetting setting = find();
        if (null != setting && null != setting.getCheckinTime()) {
            return setting.getCheckinTime().getTime();
        }
        return null;
    }

    public void setCheckinTime(Date checkinTime) {
        QywxSetting setting = find();
        if (null == setting) {
            jdbcTemplate.update("insert into QywxSetting(checkin_time) values (?)", checkinTime);
        } else {
            jdbcTemplate.update("update QywxSetting set checkin_time=?", checkinTime);
        }
    }

    @Async
    @EventListener(DataCenterEvent.class)
    public void onDataCenterEvent(DataCenterEvent event) throws Exception {
        try {
            DataSourceHolder.set(event.getDataCenter());
            QywxSetting setting = find();
            if (null != setting && null != setting.getCorpId()) {
                ContextHolder.getApplicationContext().publishEvent(new QywxCorpEvent(this, setting.getCorpId()));
            }
        } finally {
            DataSourceHolder.clear();
        }
    }
}
