package com.jeeplus.test.dingding.controller;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.utils.StringUtils;
import com.taobao.api.ApiException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping(value = "/test/attendance")
public class DingdingController {
    private String appKey = "dingtk0peibzdlxdmojz";

    private String appSecret = "NWFAu2fcfKlW3GxlvrGEwMjvJ7jyCPq0Q70XzptUsxE5PYs9cx5wTBWL0wjxKBtf";
    private static String accessTokenUrl = "https://oapi.dingtalk.com/gettoken";//通用


    public String getToken(){
        try {
            DingTalkClient client = new DefaultDingTalkClient(accessTokenUrl);
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appKey);
            req.setAppsecret(appSecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            System.out.println(rsp.getAccessToken());
            return rsp.getAccessToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Error converting JSON to Object: " + e.getMessage(), e);
        }
    }
    @ApiLog("获取考勤结果列表")
    @ApiOperation(value = "获取考勤结果列表")
    @GetMapping("getWorkListCord")
    public ResponseEntity getWorkListCord(String userId,String workDateFrom,String workDateTo) {
        // 获取access_token
        String access_token = getToken();
        // 通过调用接口获取考勤打卡结果
        DingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
        OapiAttendanceListRequest requestAttendanceListRequest = new OapiAttendanceListRequest();
        if (StringUtils.isBlank(workDateFrom) && StringUtils.isBlank(workDateTo)){
            // 查询考勤打卡记录的起始工作日
            LocalDate today = LocalDate.now();

            // 获取上午9点的时间
            LocalDateTime morning9 = today.atTime(LocalTime.of(9, 0));

            // 获取下午6点的时间
            LocalDateTime afternoon6 = today.atTime(LocalTime.of(18, 0));

            // 定义日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            workDateFrom = morning9.format(formatter);
            workDateTo = afternoon6.format(formatter);
        }

        requestAttendanceListRequest.setWorkDateFrom(workDateFrom);
        // 查询考勤打卡记录的结束工作日
        requestAttendanceListRequest.setWorkDateTo(workDateTo);
        // 员工在企业内的userid列表，最多不能超过50个。
        requestAttendanceListRequest.setUserIdList(Arrays.asList(userId));
        // 表示获取考勤数据的起始点
        requestAttendanceListRequest.setOffset(0L);
        // 表示获取考勤数据的条数，最大不能超过50条。
        requestAttendanceListRequest.setLimit(10L);
        OapiAttendanceListResponse response = null;
        try {
            response = clientDingTalkClient.execute(requestAttendanceListRequest,access_token);
            return ResponseEntity.ok(response);
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ResponseEntity.ok(response);
    }

    @ApiLog("获取个人考勤详情")
    @ApiOperation(value = "获取个人考勤详情")
    @GetMapping("getByUserId")
    public ResponseEntity getByUserId(String userId) throws ApiException {
        String access_token = getToken();

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/listRecord");
        OapiAttendanceListRecordRequest req = new OapiAttendanceListRecordRequest();
        req.setUserIds(Arrays.asList(userId));
        // 查询考勤打卡记录的起始工作日
        LocalDate today = LocalDate.now();

        // 获取上午9点的时间
        LocalDateTime morning9 = today.atTime(LocalTime.of(9, 0));

        // 获取下午6点的时间
        LocalDateTime afternoon6 = today.atTime(LocalTime.of(18, 0));

        // 定义日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        req.setCheckDateFrom(morning9.format(formatter));
        req.setCheckDateTo(afternoon6.format(formatter));
        req.setIsI18n(false);
        OapiAttendanceListRecordResponse rsp = client.execute(req, access_token);
        return ResponseEntity.ok(rsp);
    }


    @ApiLog("获取用户考勤统计列表")
    @ApiOperation(value = "获取用户考勤统计列表")
    @GetMapping("getattcolumns")
    public ResponseEntity getattcolumns() throws ApiException {
        String access_token = getToken();

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getattcolumns");
        OapiAttendanceGetattcolumnsRequest req = new OapiAttendanceGetattcolumnsRequest();
        OapiAttendanceGetattcolumnsResponse rsp = client.execute(req, access_token);
        return ResponseEntity.ok(rsp);
    }

    @ApiLog("获取用户考勤统计详情")
    @ApiOperation(value = "获取用户考勤统计详情")
    @GetMapping("getleavetimebynames")
    public ResponseEntity getleavetimebynames(String userId,String leaveTypes,String dateFrom,String dateTo) throws ApiException, ParseException {
        String access_token = getToken();

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
        OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
        req.setUserid(userId);
        req.setColumnIdList(leaveTypes);
        Date from;
        Date to;
        //日期必须传,当没有日期的时候获取当前的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (StringUtils.isBlank(dateFrom) && StringUtils.isBlank(dateTo)){
            LocalDate today = LocalDate.now();
            LocalDate firstDayOfMonth = today.withDayOfMonth(1);
            // 将 LocalDate 转换为 Date 对象
            Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
            Date fromDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());

            // 使用 SimpleDateFormat 格式化 Date 对象
            String toattedDate = sdf.format(date);
            String formattedDate = sdf.format(fromDate);
            from = sdf.parse(formattedDate);
            to = sdf.parse(toattedDate);
        }else {
            from = sdf.parse(dateFrom);
            to = sdf.parse(dateTo);
        }
        req.setFromDate(from);
        req.setToDate(to);
        OapiAttendanceGetcolumnvalResponse rsp = client.execute(req, access_token);


        return ResponseEntity.ok(rsp);
    }


}
