package com.zjty.tynotes.attendance.task;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.taobao.api.ApiException;
import com.zjty.tynotes.attendance.dao.DingUserDao;
import com.zjty.tynotes.attendance.entity.DingUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author gwj
 * @create 2020/3/26 14:51
 * @des 定时任务，定时获取打卡信息
 */
@Component
public class CardTask {

    private static final Logger logger = LoggerFactory.getLogger(CardTask.class);

    @Value("ding.userCardUrl")
    private String userCardUrl;
    @Autowired
    private MyInit init;
    @Autowired
    private DingUserDao dingUserDao;

    /**
     * 定时任务，定时获取打卡信息
     */
    @Scheduled(cron = "0 59 23 * * ? ")
    public void getCardDetails(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
//        LocalDateTime.now().minusDays(1).atOffset(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));

        Date time = calendar.getTime();
        String startTime = sdf2.format(time);
        String endTime = sdf2.format(new Date());

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
        OapiAttendanceListRequest request = new OapiAttendanceListRequest();

        List<DingUser> dingUsers = dingUserDao.findAll();
        List<String> dingUserIds = new ArrayList<>();
        if(dingUsers!=null){
            dingUsers.forEach(dingUser -> {
                dingUserIds.add(dingUser.getDingUserId());
            });
        }
        request.setWorkDateFrom(startTime);
        request.setWorkDateTo(endTime);
        request.setUserIdList(dingUserIds);
        request.setOffset(0L);
        request.setLimit(1L);
        try {
            init.getToken();
            OapiAttendanceListResponse response = client.execute(request,init.token);
            if(response!=null){
                List<OapiAttendanceListResponse.Recordresult> recordresult = response.getRecordresult();

            }
        } catch (ApiException e) {
            logger.error("定时获取打卡信息失败");
        }
    }
}
