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.CardResultDao;
import com.zjty.tynotes.attendance.dao.DingUserDao;
import com.zjty.tynotes.attendance.entity.CardResult;
import com.zjty.tynotes.attendance.entity.DingUser;
import com.zjty.tynotes.pas.dao.ConfigDao;
import com.zjty.tynotes.pas.dao.DayDao;
import com.zjty.tynotes.pas.dao.PasUserDao;
import com.zjty.tynotes.pas.entity.Day;
import com.zjty.tynotes.pas.entity.User;
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;
    @Autowired
    private CardResultDao cardResultDao;
    @Autowired
    private DayDao dayDao;
    @Autowired
    private PasUserDao pasUserDao;

    /**
     * 定时任务，定时获取打卡信息.计算前天的个人考勤信息情况
     */
    @Scheduled(cron = "0 59 23 * * ? ")
    public List<CardResult> getCardDetails(){
        List<User> users = pasUserDao.findAll();
        List<User> userList = new ArrayList<>();
        if(users!=null){
            users.forEach(user -> {
                if(!user.getUsername().equals("root")){
                    userList.add(user);
                }
            });
        }
        List<CardResult> cardResults = new ArrayList<>();
        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 = sdf.format(time);
        String endTime = sdf.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(50L);
        try {
            init.getToken();
            OapiAttendanceListResponse response = client.execute(request,init.token);
            if(response!=null){
                List<OapiAttendanceListResponse.Recordresult> recordresult = response.getRecordresult();
                if(recordresult!=null){
                    recordresult.forEach(recordresult1 -> {
                        String userId = recordresult1.getUserId();
                        DingUser dingUser = dingUserDao.findByDingUserId(userId);
                        CardResult cardResult = new CardResult(recordresult1);
                        cardResult.setUserId(dingUser.getUserId());
                        cardResults.add(cardResult);
                    });
                }
                List<CardResult> cardResults1 = cardResultDao.saveAll(cardResults);
                computerPersonAttenDanceDay(startTime,endTime,userList,cardResults1);
                return cardResults1;
            }
        } catch (ApiException e) {
            logger.error("定时获取打卡信息失败");
        }
        return null;
    }

    private void computerPersonAttenDanceDay(String startTime, String endTime, List<User> userList, List<CardResult> cardResults1) {
        if(userList!=null){
            userList.forEach(user -> {
                if(cardResults1!=null){
                    List<CardResult> cardResults = new ArrayList<>();
                    cardResults1.forEach(cardResult -> {
                        String userId = cardResult.getUserId();
                        if(user.getId().equals(userId)){
                            cardResults.add(cardResult);
                        }
                    });
                    cardResults.forEach(cardResult -> {

                    });
                }
            });
        }
    }

    /**
     * 定时任务，定时进行运算
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void calculate() throws Exception{
        int attendanceDay = 0;//应出勤天数
        int averageWorkHours = 0;//平均工时
        int realAttendanceDay = 0;//实际出勤天数
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        Date parse = sdf.parse(format);
        //计算这个月的应出勤天数
        calendar.set(Calendar.DAY_OF_MONTH,1);
        Date startTime = calendar.getTime();
        calendar.add(Calendar.MONTH,1);
        calendar.set(Calendar.DAY_OF_MONTH,0);
        Date endTime = calendar.getTime();
        List<Day> days = dayDao.findAllByStatusAndDateBetween("0", startTime, endTime);
        if(days!=null){
            attendanceDay = days.size();
        }
        List<User> users = pasUserDao.findAll();
        List<User> userList = new ArrayList<>();
        if(users!=null){
            users.forEach(user -> {
                if(!user.getUsername().equals("root")){
                    userList.add(user);
                    List<CardResult> cardResults = cardResultDao.findAllByUserIdAndUserCheckTimeBetween(user.getId(), startTime, endTime);

                }
            });
        }
    }

    public static void main(String[] args) throws Exception{
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date date = new Date();
        String date = "2020-03-29 11:11:11";
        String format = sdf.format(new Date());
        //计算这个月的应出勤天数
        Date parse = sdf.parse(date);
        calendar.setTime(parse);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        Date time = calendar.getTime();
        System.out.println(time);
        calendar.add(Calendar.MONTH,1);
        calendar.set(Calendar.DAY_OF_MONTH,0);
        Date time1 = calendar.getTime();
        System.out.println("time1:"+time1);
    }

}
