package com.malk.service.dingtalk.impl;

import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Schedule;
import com.malk.utils.UtilList;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DDImplClient_Schedule implements DDClient_Schedule {

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    /**
     * 创建日程 [注意区分全天和非全天数据格式]
     *
     * @apiNote https://open.dingtalk.com/document/personalapp/create-schedule
     */
    @Override
    public DDR_New eventsSchedule(String access_token, String userId, Map body) {

        String unionId = String.valueOf(ddClient_contacts.getUserInfoById(access_token, userId).get("unionid"));
        // attendees 日程参数人上限为500, 需要传递unionId. ppExt: start 与 end 不能使用同一个map对象, 会报错date不能为空.
        List<String> attendees = UtilMap.getList(body, "userIds");
        if (UtilList.isNotEmpty(attendees)) {
            body.put("attendees", attendees.stream().map(dId -> {
                String uId = String.valueOf(ddClient_contacts.getUserInfoById(access_token, dId).get("unionid"));
                return UtilMap.map("id", uId);
            }).collect(Collectors.toList()));
        }
        // path参数: calendarId 统一为primary，表示用户的主日历
        return DDR_New.doPost("https://api.dingtalk.com/v1.0/calendar/users/" + unionId + "/calendars/primary/events", DDConf.initTokenHeader(access_token), null, body);
    }
}
