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

import com.usoftchina.dingtalk.sdk.ScheduleSdk;
import com.usoftchina.dingtalk.sdk.dto.AddScheduleReq;
import com.usoftchina.dingtalk.sdk.util.UrlUtils;
import com.usoftchina.uas.office.context.MasterHolder;
import com.usoftchina.uas.office.dingtalk.entity.Agenda;
import com.usoftchina.uas.office.dingtalk.manage.entity.DingTalkAgent;
import com.usoftchina.uas.office.dingtalk.manage.service.DingTalkAgentService;
import com.usoftchina.uas.office.dingtalk.service.UasAgendaService;
import com.usoftchina.uas.office.dto.UasEvent;
import com.usoftchina.uas.office.entity.DataCenter;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.listener.UasEventListener;
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;

    @Autowired
    private DingTalkAgentService agentService;

    /**
     * uas日程审核通过，写入DING日程
     *
     * @param event
     */
    @UasEventListener(caller = "Agenda", operation = "AUDIT")
    public void onAgendaAudit(UasEvent event) throws Exception{
        Agenda agenda = agendaService.getById((int) event.getKey());
        if (null != agenda) {
            DingTalkAgent uasAgent = getUasAgent();
            String sourceUrl = UrlUtils.generateAuthUrl(scheduleSdk.getCorpId(), event.getMaster(), uasAgent.getCode(), uasAgent.getOuterUrl(),
                    DataCenter.INSTANCE.getOuterUrl() + "authorize", "jsps/common/commonpage.jsp?whoami=Agenda&formCondition=ag_idIS" + agenda.getAg_id());
            AddScheduleReq req = new AddScheduleReq()
                    .organizer(agenda.getEm_ding())
                    .during(agenda.getAg_start().getTime(), agenda.getAg_end().getTime())
                    .summary(agenda.getAg_title())
                    .description(agenda.getAg_content())
                    .bizId(String.valueOf(agenda.getAg_id()))
                    .remindBefore(0)
                    .attendees(Arrays.asList(agenda.getEm_ding()))
                    .source("UAS系统", sourceUrl);
            String scheduleId = scheduleSdk.addSchedule("Uas", req);
            agenda.setAg_scheduleid(scheduleId);
            agendaService.setScheduleId(agenda);
        }
    }

    private DingTalkAgent getUasAgent() {
        try {
            DataSourceHolder.set(DataCenter.INSTANCE);
            return agentService.findByCode("Uas");
        } finally {
            DataSourceHolder.set(MasterHolder.get());
        }
    }
}
