package com.usoftchina.uas.office.qywx.listener;

import com.usoftchina.qywx.sdk.ScheduleSdk;
import com.usoftchina.qywx.sdk.dto.AddScheduleReq;
import com.usoftchina.uas.office.dto.UasEvent;
import com.usoftchina.uas.office.listener.UasEventListener;
import com.usoftchina.uas.office.qywx.entity.Agenda;
import com.usoftchina.uas.office.qywx.service.UasAgendaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author yingp
 * @date 2020/2/16
 */
@Component
public class UasAgendaListener {
    @Autowired
    private ScheduleSdk scheduleSdk;

    @Autowired
    private UasAgendaService agendaService;

    /**
     * uas日程审核通过，写入企业微信日程
     *
     * @param event
     */
    @UasEventListener(caller = "Agenda", operation = "AUDIT")
    public void onAgendaAudit(UasEvent event) {
        if (!scheduleSdk.enabled()) {
            return;
        }
        Agenda agenda = agendaService.getById((int) event.getKey());
        if (null != agenda) {
            AddScheduleReq req = new AddScheduleReq()
                    .organizer(agenda.getEm_qywx())
                    .during(agenda.getAg_start().getTime() / 1000, agenda.getAg_end().getTime() / 1000)
                    .summary(agenda.getAg_title())
                    .description(agenda.getAg_content())
                    .remindBefore(0)
                    .attendees(Arrays.asList(agenda.getEm_qywx()));
            String scheduleId = scheduleSdk.addSchedule(req);
            agenda.setAg_scheduleid(scheduleId);
            agendaService.setScheduleId(agenda);
        }
    }

    /**
     * uas日程反审核，删除企业微信日程
     *
     * @param event
     */
    @UasEventListener(caller = "Agenda", operation = "RESAUDIT")
    public void onAgendaUnAudit(UasEvent event) {
        if (!scheduleSdk.enabled()) {
            return;
        }
        String scheduleId = agendaService.getScheduleId((int) event.getKey());
        if (scheduleId != null) {
            scheduleSdk.deleteSchedule(scheduleId);
        }
    }
}
