package com.hzya.frame.dingtalk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2DepartmentGetRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.hzya.frame.dingtalk.service.IDingTalkService;
import com.hzya.frame.dingtalk.util.DingTalkAccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 钉钉service
 * @Author xiangerlin
 * @Date 2024/8/27 16:17
 **/
@Service(value = "dingTalkService")
public class DingTalkServiceImpl implements IDingTalkService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${dingtalk.appKey:}")
    private String dAppKey;
    @Value("${dingtalk.appSecret:}")
    private String dAppSecret;


    /**
     * 根据userid获取用户详情
     *
     * @param userId    钉钉userid
     * @param appKey
     * @param appSecret
     * @return
     */
    @Override
    public OapiV2UserGetResponse.UserGetResponse getUserById(String userId, String appKey, String appSecret) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
        req.setUserid(userId);
        req.setLanguage("zh_CN");
        try {
            OapiV2UserGetResponse rsp = client.execute(req, DingTalkAccessToken.getAccessToken(appKey,appSecret));
            if (rsp.isSuccess()){
                OapiV2UserGetResponse.UserGetResponse result = rsp.getResult();
                String s = JSONObject.toJSONString(result);
                logger.info("人员详情信息:{}",s);
                return result;
            }
        }catch (Exception e){
            logger.error("根据部门id获取钉钉用户详情出错：{}",e);
        }
        return null;
    }

    /**
     * 根据userid获取用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public OapiV2UserGetResponse.UserGetResponse getUserById(String userId) {
        return getUserById(userId,dAppKey,dAppSecret);
    }

    /**
     * 获取部门用户列表
     *
     * @param req 请求参数
     * @param appKey
     * @param appSecret
     * @return
     */
    @Override
    public OapiV2UserListResponse.PageResult getUserListByDeptId(OapiV2UserListRequest req, String appKey, String appSecret) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
            req.setSize(100L);//每页最大只能查100条
            req.setOrderField("modify_desc");
            req.setContainAccessLimit(false);
            req.setLanguage("zh_CN");
            OapiV2UserListResponse rsp = client.execute(req, DingTalkAccessToken.getAccessToken(appKey,appSecret));
            OapiV2UserListResponse.PageResult result = rsp.getResult();
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据部门id获取部门详情
     *
     * @param deptId    钉钉部门id
     * @param appKey
     * @param appSecret
     * @return
     */
    @Override
    public OapiV2DepartmentGetResponse.DeptGetResponse getDeptById(Long deptId, String appKey, String appSecret) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
        OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
        req.setDeptId(deptId);
        req.setLanguage("zh_CN");
        try {
            OapiV2DepartmentGetResponse rsp = client.execute(req, DingTalkAccessToken.getAccessToken(appKey,appSecret));
            if (rsp.isSuccess()){
                OapiV2DepartmentGetResponse.DeptGetResponse result = rsp.getResult();
                String s = JSONObject.toJSONString(result);
                logger.info("部门详情信息:{}",s);
                return result;
            }
        }catch(Exception e){
            logger.error("根据部门id获取钉钉部门出错：{}",e);
        }
        return null;
    }

    /**
     * 根据部门id获取部门详情
     *
     * @param deptId
     * @return
     */
    @Override
    public OapiV2DepartmentGetResponse.DeptGetResponse getDeptById(Long deptId) {
        return getDeptById(deptId,dAppKey,dAppSecret);
    }

    /**
     * 获取部门列表，此接口只会返回下一级部门信息
     * @param deptId 部门id，如果不传则查询一级部门
     * @param appKey
     * @param appSecret
     * @return
     */
    @Override
    public List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDeptList(Long deptId,String appKey,String appSecret) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(deptId);
            req.setLanguage("zh_CN");
            OapiV2DepartmentListsubResponse rsp = client.execute(req, DingTalkAccessToken.getAccessToken(appKey,appSecret));
            if (rsp.isSuccess()){
                List<OapiV2DepartmentListsubResponse.DeptBaseResponse> result = rsp.getResult();
                return result;
            }
        }catch (Exception e){
            logger.error("获取部门列表接口出错:{}",e);
        }
        return null;
    }
}
