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.Meeting;
import com.usoftchina.uas.office.qywx.service.UasMeetingService;
import com.usoftchina.uas.office.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.stream.Collectors;

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

    /**
     * uas会议申请审核通过，写入企业微信日程
     *
     * @param event
     */
    @UasEventListener(caller = "Meetingroomapply", operation = "AUDIT")
    public void onMeetingAudit(UasEvent event) {
        if (!scheduleSdk.enabled()) {
            return;
        }
        Meeting meeting = meetingService.getById((int) event.getKey());
        if (null != meeting) {
            AddScheduleReq req = new AddScheduleReq()
                    .organizer(meeting.getEm_qywx())
                    .during(meeting.getMa_starttime().getTime() / 1000, meeting.getMa_endtime().getTime() / 1000)
                    .summary("会议-" + meeting.getMa_theme())
                    .remindBefore(900);
            if (null != meeting.getRoom()) {
                req.location(meeting.getRoom().getMr_site() + " " + meeting.getRoom().getMr_name());
            }
            if (!StringUtils.isEmpty(meeting.getMa_remark())) {
                req.description(meeting.getMa_remark());
            }
            if (!CollectionUtils.isEmpty(meeting.getAttendees())) {
                req.attendees(meeting.getAttendees().stream().map(Meeting.MeetingAttendee::getEm_qywx).collect(Collectors.toList()));
            }
            String scheduleId = scheduleSdk.addSchedule(req);
            meeting.setMa_scheduleid(scheduleId);
            meetingService.setScheduleId(meeting);
        }
    }

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