package com.ads.business.service.impl;


import com.ads.business.service.ApiUserService;
import com.ads.business.service.DepartmentService;
import com.ads.business.service.TokenService;
import com.ads.business.service.data.GetLoginOutData;
import com.ads.business.service.model.request.DepartmentUserListRequest;
import com.ads.common.data.JsonResult;
import com.ads.common.dingTalk.domain.DepartmentDTO;
import com.ads.common.dingTalk.domain.UserDTO;
import com.ads.common.exception.LoginException;
import com.ads.common.redis.RedisKeyConstant;
import com.ads.common.redis.RedisManager;
import com.ads.common.util.OnlineUserUtils;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApiUserServiceImpl implements ApiUserService {

    @Resource
    private TokenService tokenService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private RedisManager redisManager;

    @Override
    public JsonResult<GetLoginOutData> userInfo() {
        log.info("获取当前登陆人用户信息");
        GetLoginOutData user = OnlineUserUtils.get();
        if (Objects.isNull(user)) {
            log.error("获取用户信息失败");
            throw new LoginException();
        }
        return JsonResult.success(user);
    }

    @Override
    public List<UserDTO> allUsers() {
        log.info("获取所有钉钉用户信息");
        List<UserDTO> userDTOList = new ArrayList<>();
        String allUserStr = (String) redisManager.get(RedisKeyConstant.DING_ALL_USER);
        if (StringUtils.isNotBlank(allUserStr)){
            return JSONArray.parseArray(allUserStr, UserDTO.class);
        }
        List<DepartmentDTO> department = departmentService.getDepartment(1L);
        if (CollectionUtils.isNotEmpty(department)) {
            department.forEach(e->{
                DepartmentUserListRequest request = new DepartmentUserListRequest();
                request.setParentId(e.getId());
                List<UserDTO> users = departmentService.getDepartmentUsers(request);
                if ( CollectionUtils.isNotEmpty(users)){
                    userDTOList.addAll(users);
                }
            });
        }
        List<UserDTO> userDTOs = userDTOList.stream().distinct().collect(Collectors.toList());
        redisManager.set(RedisKeyConstant.DING_ALL_USER,JSONArray.toJSONString(userDTOs),60*60);
        return userDTOs;
    }

}
