package com.ads.business.service.impl;

import com.ads.business.service.DepartmentService;
import com.ads.business.service.TokenService;
import com.ads.business.service.model.request.DepartmentListRequest;
import com.ads.business.service.model.request.DepartmentUserListRequest;
import com.ads.common.dingTalk.domain.DepartmentDTO;
import com.ads.common.dingTalk.domain.ServiceResult;
import com.ads.common.dingTalk.domain.UserDTO;
import com.ads.common.dingTalk.service.DingTalkService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Return
 * @Author hou
 * @Date 2021/9/3 16:25
 * @Destription
 */
@Slf4j
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DingTalkService dingTalkService;

    @Resource
    private TokenService tokenService;

    @Override
    public List<DepartmentDTO> list(DepartmentListRequest request) {
        log.info("查询部门列表--DepartmentServiceImpl--request:{}", JSON.toJSON(request));
        String accessToken = tokenService.getAccessToken();
        ServiceResult<List<DepartmentDTO>> result = dingTalkService.getDepartmentList(accessToken, request.getParentId().toString());
        if (!result.isSuccess()) {
            return Collections.emptyList();
        }
        return result.getResult();
    }

    @Override
    public List<UserDTO> getDepartmentUsers(DepartmentUserListRequest request) {
        log.info("查询部门下员工列表--getDepartmentUsers--request:{}", JSON.toJSONString(request));
        String accessToken = tokenService.getAccessToken();
        Long offset = 0L;
        Long size = 0L;
        if (request.getPage() > 0 && request.getPageSize() > 0) {
            offset = (request.getPage() - 1) * request.getPageSize();
            size = request.getPageSize();
        }
        ServiceResult<List<UserDTO>> result = dingTalkService.getDepartmentUsers(accessToken, request.getParentId(), offset, size);
        if (!result.isSuccess()) {
            return Collections.emptyList();
        }
        return result.getResult();
    }

    @Override
    public List<DepartmentDTO> getDepartment(Long parentId){
        DepartmentListRequest request = new DepartmentListRequest();
        request.setParentId(parentId);
        List<DepartmentDTO> list = list(request);
        if (CollectionUtils.isNotEmpty(list)){
            List<DepartmentDTO> responses = new ArrayList<>(list);
            list.forEach(e->{
                responses.addAll(getDepartment(e.getId()));
            });
            return responses;
        }
        return Collections.emptyList();
    }
}
