package com.ads.business.service.impl;

import com.ads.business.service.RoleService;
import com.ads.business.service.TokenService;
import com.ads.business.service.model.request.RoleUserListRequest;
import com.ads.common.data.JsonResult;
import com.ads.common.dingTalk.domain.ServiceResult;
import com.ads.common.dingTalk.service.DingTalkService;
import com.alibaba.fastjson.JSON;
import com.dingtalk.api.response.OapiRoleListResponse;
import com.dingtalk.api.response.OapiRoleSimplelistResponse;
import lombok.extern.slf4j.Slf4j;
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/7 14:00
 * @Destription
 */

@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private DingTalkService dingTalkService;

    @Resource
    private TokenService tokenService;

    @Override
    public JsonResult<List<OapiRoleListResponse.OpenRole>> list() {
        log.info("查询角色列表--RoleServiceImpl--开始");
        String result = tokenService.getAccessToken();
        ServiceResult<List<OapiRoleListResponse.OpenRoleGroup>> data = dingTalkService.getRoleList(result);
        if (!data.isSuccess()) {
            return JsonResult.success(Collections.emptyList());
        }
        ArrayList<OapiRoleListResponse.OpenRole> list = new ArrayList<>();
        for (OapiRoleListResponse.OpenRoleGroup group : data.getResult()) {
            list.addAll(group.getRoles());
        }
        return JsonResult.success(list);
    }

    @Override
    public JsonResult<List<OapiRoleSimplelistResponse.OpenEmpSimple>> users(RoleUserListRequest request) {
        log.info("根据角色id查询角色员工列表--RoleServiceImpl--request:{}", JSON.toJSONString(request));
        String accessToken = tokenService.getAccessToken();
        ServiceResult<List<OapiRoleSimplelistResponse.OpenEmpSimple>> result = dingTalkService.getRoleUsers(accessToken, request.getRoleId());
        if (!result.isSuccess()) {
            return JsonResult.success(Collections.emptyList());
        }
        return JsonResult.success(result.getResult());
    }
}
