package com.yqd.dingding.util;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import com.yqd.dingding.bean.*;

import java.util.*;

public class DingDingUtil {

    private static String appKey = "";

    private static String appsectet = "";

    private static String corpId = "dingf2686e63feb5696135c2f4657eb6378f";

    private static String ssoSecret = "PeMFCtG5dAmYHfb03xjib5N03ZMhsi-arCpX6HfpeQMiA6ceBBSq-fU_mHWuKeiL";

    public void setKeyAndSectet(String appKey, String appsectet) {
        this.appKey = appKey;
        this.appsectet = appsectet;
    }

    public TokenBean getDingDingToken() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(DingDingUtil.appKey);
            req.setAppsecret(DingDingUtil.appsectet);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            String tokenStr = rsp.getBody();
            TokenBean tokenBean = JSON.parseObject(tokenStr, TokenBean.class);
            return tokenBean;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 签到记录
     * @param beginTime
     * @param endTime
     * @param access_token
     */
    public void getSignInfo(long beginTime, long endTime, String access_token) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/checkin/record");
            OapiCheckinRecordRequest req = new OapiCheckinRecordRequest();
            req.setDepartmentId("1");
            req.setEndTime(endTime);
            req.setStartTime(beginTime);
            req.setOffset(0L);
            req.setSize(100L);
            req.setOrder("asc");
            req.setHttpMethod("GET");
            OapiCheckinRecordResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    /**
     * 考勤信息
     * @param access_token
     */
    public RecordDateBean getAttendanceInfo(String access_token, String checkDateFrom, String checkDateTo, List<String> userids) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/listRecord");
            OapiAttendanceListRecordRequest req = new OapiAttendanceListRecordRequest();
            req.setUserIds(userids);
            req.setCheckDateFrom(checkDateFrom);
            req.setCheckDateTo(checkDateTo);
            OapiAttendanceListRecordResponse rsp = client.execute(req, access_token);
            RecordDateBean resultBean = JSON.parseObject(rsp.getBody(), RecordDateBean.class);
            return resultBean;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 免登陆验证
     */
    public void noLoginCheck() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/gettoken");
            OapiSsoGettokenRequest req = new OapiSsoGettokenRequest();
            req.setCorpid(DingDingUtil.corpId);
            req.setCorpsecret(DingDingUtil.ssoSecret);
            req.setHttpMethod("GET");
            OapiSsoGettokenResponse rsp = client.execute(req);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据手机号获取用户id
     * @param access_token
     * @param mobile
     */
    public UserIDBean getUserIdByMobile(String access_token, String mobile) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
            OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
            req.setMobile(mobile);
            req.setHttpMethod("GET");
            OapiUserGetByMobileResponse rsp = client.execute(req, access_token);
            UserIDBean userIDBean = JSON.parseObject(rsp.getBody(), UserIDBean.class);
            return userIDBean;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取列定义
     * @param access_token
     */
    public ColumnDefintionBean getColumnDefinition(String access_token) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getattcolumns");
            OapiAttendanceGetattcolumnsRequest req = new OapiAttendanceGetattcolumnsRequest();
            OapiAttendanceGetattcolumnsResponse rsp = client.execute(req, access_token);
            ColumnDefintionBean columnDefintionBean = JSON.parseObject(rsp.getBody(), ColumnDefintionBean.class);
            return columnDefintionBean;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取报表考情数据
     * @param access_token
     * @param userid
     * @param columnIdList
     * @param fromDate
     * @param toDate
     */
    public void getAttendanceReport(String access_token, String userid, String columnIdList, Date fromDate, Date toDate) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
            OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
            req.setUserid(userid);
            req.setColumnIdList(columnIdList);
            req.setFromDate(fromDate);
            req.setToDate(toDate);
            OapiAttendanceGetcolumnvalResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        DingDingUtil dingDingUtil = new DingDingUtil();
        dingDingUtil.setKeyAndSectet("dingnwjgigolatb7tihb", "dLtF3JE4e-eGI3aiVtRb2WyRQiA9R4Bwks51b6ys7VNvLH9YZZ8oRmctwoJR4pwa");
        TokenBean tokenBean = dingDingUtil.getDingDingToken();
        System.out.println(tokenBean);

        // 获取用户信息
        UserIDBean userIDBean_huyi = dingDingUtil.getUserIdByMobile(tokenBean.getAccess_token(), "15234760931");
        UserIDBean userIDBean_wangjie = dingDingUtil.getUserIdByMobile(tokenBean.getAccess_token(), "15234190483");
        List<String> userids = new ArrayList<>();
        userids.add(userIDBean_huyi.getUserid());
        userids.add(userIDBean_wangjie.getUserid());
//        RecordDateBean recordDateBean = dingDingUtil.getAttendanceInfo(tokenBean.getAccess_token(), "2021-03-17 00:00:00", "2021-03-18 00:00:00", userids);

        // StringUtils.parseDateTime("2020-09-07 12:12:12")

        ColumnDefintionBean columnDefintionBean = dingDingUtil.getColumnDefinition(tokenBean.getAccess_token());
        ColumnsResult columnsResult = columnDefintionBean.getResult();
        List<ColumnsBean> columnsBeanList = columnsResult.getColumns();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < columnsBeanList.size(); i++) {
            ColumnsBean columnsBean = columnsBeanList.get(i);
            System.out.println(columnsBean);
            if (null != columnsBean.getId() && !"".equals(columnsBean.getId()) && !"null".equals(columnsBean.getId())) {
                sb.append(columnsBean.getId());
                if (i != columnsBeanList.size() - 1) {
                    sb.append(",");
                }
            }
        }
        System.out.println(sb.toString());
        dingDingUtil.getAttendanceReport(tokenBean.getAccess_token(), userIDBean_huyi.getUserid(), "168355738", StringUtils.parseDateTime("2021-02-01 00:00:00"), StringUtils.parseDateTime("2021-03-01 00:00:00"));
    }
}
