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

import com.usoftchina.uas.office.context.ContextHolder;
import com.usoftchina.uas.office.dingtalk.manage.entity.DingTalkSetting;
import com.usoftchina.uas.office.dingtalk.manage.event.DingTalkCorpEvent;
import com.usoftchina.uas.office.event.DataCenterEvent;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
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 DingTalkSettingService extends AbstractService {

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

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

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

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

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