package com.taobao.utils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;

import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.sys.util.LocalDateUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceGetleavestatusRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiUserListsimpleRequest;
import com.dingtalk.api.response.OapiAttendanceGetleavestatusResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiUserListsimpleResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.taobao.api.ApiException;
import com.thinkgem.jeesite.common.utils.EhCacheUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author yuanshuai
 * @date 2021/6/17 10:12
 */
public class DDUtils {

	private static final String ONE_HOUR_CACHE = "oneHourCache";
	private static final String DD_ACCESS_TOKEN = "dd_access_token";

	/**
	 * 技术部部门列表
	 */
	private static final String[] DEPT_ARRAY = { "137633499", "132052890", "132059833", "132609282" };

	/**
	 * 钉钉获取accessToken
	 *
	 * @author yuanshuai
	 * @date 2021/6/17 10:38
	 */
	public static String getAccessToken(String ddAppKey, String ddAppSecret) throws ApiException {
		String accessToken = null;//(String) EhCacheUtils.get(ONE_HOUR_CACHE, DD_ACCESS_TOKEN);
		if (StringUtils.isBlank(accessToken)) {
			DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
			OapiGettokenRequest tokenRequest = new OapiGettokenRequest();
			tokenRequest.setAppkey(ddAppKey);
			tokenRequest.setAppsecret(ddAppSecret);
			tokenRequest.setHttpMethod("GET");
			OapiGettokenResponse response = client.execute(tokenRequest);
			if (0 != response.getErrcode()) {
				throw new ZAException(ZAErrorCode.ZA_ERROR, "扫码失败，请再次尝试。如多次尝试均无法登录请联系技术部");
			}
			accessToken = response.getAccessToken();
//			EhCacheUtils.put(ONE_HOUR_CACHE, DD_ACCESS_TOKEN, accessToken);
		}
		return accessToken;
	}

	/**
	 * 根据部门获取用户信息
	 *
	 * @author yuanshuai
	 * @since 2023/11/22 10:41
	 */
	public static List<Map<String, String>> getUserListSimple(String accessToken, String deptId, Integer pageNum,
			Integer pageSize) throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listsimple");
		OapiUserListsimpleRequest req = new OapiUserListsimpleRequest();
		req.setDeptId(Long.parseLong(deptId));
		req.setCursor(pageNum.longValue());
		req.setSize(pageSize.longValue());
		OapiUserListsimpleResponse rsp = client.execute(req, accessToken);
		JSONObject jsonResp = JSONObject.fromObject(rsp.getBody());
		if ("0".equals(jsonResp.getString("errcode"))) {
			JSONArray jsonArray = jsonResp.getJSONObject("result").getJSONArray("list");
			List<Map<String, String>> respList = Lists.newArrayList();
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject userJson = jsonArray.getJSONObject(i);
				Map<String, String> map = Maps.newHashMap();
				map.put("name", userJson.getString("name"));
				map.put("userId", userJson.getString("userid"));
				respList.add(map);
			}
			return respList;
		} else {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "获取用户信息失败");
		}
	}

	/**
	 * 根据用户id获取请假信息
	 *
	 * @author yuanshuai
	 * @since 2023/11/22 10:35
	 */
	public static List<Map<String, String>> getLeaveStatus(String accessToken, List<String> idList,
			LocalDateTime startTime, LocalDateTime endTime, Integer pageSize) throws ApiException {
		boolean hasMore = Boolean.TRUE;
		int pageNum = 0;
		List<Map<String, String>> respList = Lists.newArrayList();
		while (hasMore) {
			DingTalkClient client = new DefaultDingTalkClient(
					"https://oapi.dingtalk.com/topapi/attendance/getleavestatus");
			OapiAttendanceGetleavestatusRequest req = new OapiAttendanceGetleavestatusRequest();
			req.setUseridList(String.join(",", idList));
			req.setStartTime(startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
			req.setEndTime(endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
			req.setOffset((long) pageNum);
			req.setSize(pageSize.longValue());
			OapiAttendanceGetleavestatusResponse rsp = client.execute(req, accessToken);
			JSONObject jsonResp = JSONObject.fromObject(rsp.getBody());
			if ("0".equals(jsonResp.getString("errcode"))) {
				hasMore = jsonResp.getJSONObject("result").getBoolean("has_more");
				pageNum += pageSize;
				JSONArray jArray = jsonResp.getJSONObject("result").getJSONArray("leave_status");
				for (int i = 0; i < jArray.size(); i++) {
					JSONObject leaveJson = jArray.getJSONObject(i);
					Map<String, String> leaveMap = Maps.newHashMap();
					leaveMap.put("userId", leaveJson.getString("userid"));
					String leaveStartTime = leaveJson.getString("start_time");
					leaveMap.put("startTime", LocalDateUtils.formatLocalDateTime(
							LocalDateUtils.getDateTimeOfTimestamp(Long.parseLong(leaveStartTime))));
					String leaveEndTime = leaveJson.getString("end_time");
					leaveMap.put("endTime", LocalDateUtils
							.formatLocalDateTime(LocalDateUtils.getDateTimeOfTimestamp(Long.parseLong(leaveEndTime))));
					respList.add(leaveMap);
				}
			} else {
				throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "获取请假信息失败");
			}
		}
		return respList;
	}

	/**
	 * 获取技术部员工请假状态
	 *
	 * @author yuanshuai
	 * @since 2023/11/22 10:50
	 */
	public static List<Map<String, String>> getTechLeaveStatus(String ddAppKey, String ddAppSecret,
			LocalDateTime startTime, LocalDateTime endTime) {
		try {
			Integer pageNum = 0;
			Integer pageSize = 20;
			// 获取token
			String accessToken = DDUtils.getAccessToken(ddAppKey, ddAppSecret);
			// 查询技术部用户
			List<Map<String, String>> userList = Lists.newArrayList();
			for (String deptId : DEPT_ARRAY) {
				List<Map<String, String>> deptUserList = DDUtils.getUserListSimple(accessToken, deptId, pageNum,
						pageSize);
				userList.addAll(deptUserList);
			}
			// 查询请假信息
			// 过滤崔蕊
			List<String> techIdList = userList.stream().filter(um -> !"0917601316772790".equals(um.get("userId")))
					.map(m -> m.get("userId")).collect(Collectors.toList());
			List<Map<String, String>> leaveList = DDUtils.getLeaveStatus(accessToken, techIdList, startTime, endTime,
					pageSize);
			leaveList.forEach(m -> {
				String userId = m.get("userId");
				Map<String, String> userMap = userList.stream().filter(um -> userId.equals(um.get("userId")))
						.findFirst().orElse(null);
				if (Objects.nonNull(userMap)) {
					m.put("name", userMap.get("name"));
				}
			});
			return leaveList;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		LocalDateTime startTime = LocalDateTime.of(2023, 11, 25, 0, 0, 0);
		LocalDateTime endTime = LocalDateTime.of(2023, 11, 26, 0, 0, 0);
		System.out.println(DDUtils.getTechLeaveStatus("dingtoh6yup2dai4mmps",
				"t-OHle56Yz3IHVoib8Tm0rcujTYzCXEkVvC-RFhnrbXmCxlF-ggQmwSu_zXouep2", startTime, endTime));
	}

}
