package yangtz.cs.liu.dingding.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.ruoyi.common.utils.StringUtils;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import yangtz.cs.liu.dingding.vo.DingSchoolDeptVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理
 */
@Component
public class DingDeptUtils {

    @Autowired
    private AccessTokenUtils accessTokenUtils;

    /**
     * 创建部门
     */
    public Long createDept(DingSchoolDeptVo deptVo){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/create");
            OapiV2DepartmentCreateRequest req = new OapiV2DepartmentCreateRequest();
            req.setName(deptVo.getName());
            req.setParentId(deptVo.getParentId());
            if (StringUtils.isNotNull(deptVo.getHideDept())){
                req.setHideDept(deptVo.getHideDept());
            }
            if (StringUtils.isNotEmpty(deptVo.getDeptPermits())){
                req.setDeptPermits(deptVo.getDeptPermits());
            }
            if (StringUtils.isNotEmpty(deptVo.getUserPermits())){
                req.setUserPermits(deptVo.getUserPermits());
            }
            if (StringUtils.isNotNull(deptVo.getOuterDept())){
                req.setOuterDept(deptVo.getOuterDept());
            }
            if (StringUtils.isNotNull(deptVo.getOuterDeptOnlySelf())){
                req.setOuterDeptOnlySelf(deptVo.getOuterDeptOnlySelf());
            }
            if (StringUtils.isNotEmpty(deptVo.getOuterPermitUsers())){
                req.setOuterPermitUsers(deptVo.getOuterPermitUsers());
            }
            if (StringUtils.isNotEmpty(deptVo.getOuterPermitDepts())){
                req.setOuterPermitDepts(deptVo.getOuterPermitDepts());
            }
            if (StringUtils.isNotNull(deptVo.getCreateDeptGroup())){
                req.setCreateDeptGroup(deptVo.getCreateDeptGroup());
            }
            if (StringUtils.isNotNull(deptVo.getAutoApproveApply())){
                req.setAutoApproveApply(deptVo.getAutoApproveApply());
            }
            if (StringUtils.isNotNull(deptVo.getOrder())){
                req.setOrder(deptVo.getOrder());
            }
            if (StringUtils.isNotEmpty(deptVo.getSourceIdentifier())){
                req.setSourceIdentifier(deptVo.getSourceIdentifier());
            }
            OapiV2DepartmentCreateResponse rsp = client.execute(req, token);
            return rsp.getResult().getDeptId();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    /**
     * 更新部门
     */
    public String updateDept(DingSchoolDeptVo deptVo){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/update");
            OapiV2DepartmentUpdateRequest req = new OapiV2DepartmentUpdateRequest();
            req.setDeptId(deptVo.getDeptId());
            if (StringUtils.isNotNull(deptVo.getParentId())){
                req.setParentId(deptVo.getParentId());
            }
            if (StringUtils.isNotNull(deptVo.getOuterDept())){
                req.setOuterDept(deptVo.getOuterDept());
            }
            if (StringUtils.isNotNull(deptVo.getHideDept())){
                req.setHideDept(deptVo.getHideDept());
            }
            if (StringUtils.isNotNull(deptVo.getCreateDeptGroup())){
                req.setCreateDeptGroup(deptVo.getCreateDeptGroup());
            }
            if (StringUtils.isNotNull(deptVo.getOrder())){
                req.setOrder(deptVo.getOrder());
            }
            if (StringUtils.isNotEmpty(deptVo.getName())){
                req.setName(deptVo.getName());
            }
            if (StringUtils.isNotEmpty(deptVo.getSourceIdentifier())){
                req.setSourceIdentifier(deptVo.getSourceIdentifier());
            }
            if (StringUtils.isNotEmpty(deptVo.getDeptPermits())){
                req.setDeptPermits(deptVo.getDeptPermits());
            }
            if (StringUtils.isNotEmpty(deptVo.getUserPermits())){
                req.setUserPermits(deptVo.getUserPermits());
            }
            if (StringUtils.isNotEmpty(deptVo.getOuterPermitUsers())){
                req.setOuterPermitUsers(deptVo.getOuterPermitUsers());
            }
            if (StringUtils.isNotEmpty(deptVo.getOuterPermitDepts())){
                req.setOuterPermitDepts(deptVo.getOuterPermitDepts());
            }
            if (StringUtils.isNotNull(deptVo.getOuterDeptOnlySelf())){
                req.setOuterDeptOnlySelf(deptVo.getOuterDeptOnlySelf());
            }
            if (StringUtils.isNotEmpty(deptVo.getLanguage())){
                req.setLanguage(deptVo.getLanguage());
            }
            if (StringUtils.isNotNull(deptVo.getAutoAddUser())){
                req.setAutoAddUser(deptVo.getAutoAddUser());
            }
            if (StringUtils.isNotEmpty(deptVo.getDeptManagerUseridList())){
                req.setDeptManagerUseridList(deptVo.getDeptManagerUseridList());
            }
            if (StringUtils.isNotNull(deptVo.getGroupContainSubDept())){
                req.setGroupContainSubDept(deptVo.getGroupContainSubDept());
            }
            if (StringUtils.isNotNull(deptVo.getGroupContainOuterDept())){
                req.setGroupContainOuterDept(deptVo.getGroupContainOuterDept());
            }
            if (StringUtils.isNotNull(deptVo.getGroupContainHiddenDept())){
                req.setGroupContainHiddenDept(deptVo.getGroupContainHiddenDept());
            }
            if (StringUtils.isNotEmpty(deptVo.getOrgDeptOwner())){
                req.setOrgDeptOwner(deptVo.getOrgDeptOwner());
            }
            OapiV2DepartmentUpdateResponse rsp = client.execute(req, token);
            return rsp.getErrmsg();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除部门
     * @param deptId 部门id
     * @return
     */
    public Boolean deleteDept(Long deptId){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/delete");
            OapiV2DepartmentDeleteRequest req = new OapiV2DepartmentDeleteRequest();
            req.setDeptId(deptId);
            OapiV2DepartmentDeleteResponse rsp = client.execute(req, token);
            return rsp.isSuccess();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取部门详情
     * @param deptId 部门id
     * @param language 通讯录语言： zh_CN（默认）：中文 ， en_US：英文
     * @return
     */
    public OapiV2DepartmentGetResponse.DeptGetResponse getDept(Long deptId,String language){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.setDeptId(deptId);
            if (StringUtils.isNotEmpty(language)){
                req.setLanguage(language);
            }
            OapiV2DepartmentGetResponse rsp = client.execute(req, token);
            return rsp.getResult();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return new OapiV2DepartmentGetResponse.DeptGetResponse();
    }

    /**
     * 获取部门列表
     * @param deptId 部门id
     * @param language 通讯录语言： zh_CN（默认）：中文 ， en_US：英文
     * @return
     */
    public List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDeptList(Long deptId,String language){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(deptId);
            if (StringUtils.isNotEmpty(language)){
                req.setLanguage(language);
            }
            OapiV2DepartmentListsubResponse rsp = client.execute(req, token);
            return rsp.getResult();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    /**
     * 获取子部门id列表
     * @param deptId 部门id
     * @return
     */
    public OapiV2DepartmentListsubidResponse.DeptListSubIdResponse getDeptIdList(Long deptId){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.setDeptId(deptId);
            OapiV2DepartmentListsubidResponse rsp = client.execute(req, token);
            return rsp.getResult();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return new OapiV2DepartmentListsubidResponse.DeptListSubIdResponse();
    }

    /**
     * 获取指定部门的所有父部门列表
     * @param deptId 部门id
     * @return
     */
    public OapiV2DepartmentListparentbydeptResponse.DeptListParentByDeptIdResponse getParentByDept(Long deptId){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listparentbydept");
            OapiV2DepartmentListparentbydeptRequest req = new OapiV2DepartmentListparentbydeptRequest();
            req.setDeptId(deptId);
            OapiV2DepartmentListparentbydeptResponse rsp = client.execute(req, token);
            return rsp.getResult();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return new OapiV2DepartmentListparentbydeptResponse.DeptListParentByDeptIdResponse();
    }

    /**
     * 获取指定用户的所有父部门列表
     * @param userId 用户id
     * @return
     */
    public OapiV2DepartmentListparentbyuserResponse.DeptListParentByUserResponse getParentByUser(String userId){
        //获取access_token
        String token = accessTokenUtils.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listparentbyuser");
            OapiV2DepartmentListparentbyuserRequest req = new OapiV2DepartmentListparentbyuserRequest();
            req.setUserid(userId);
            OapiV2DepartmentListparentbyuserResponse rsp = client.execute(req, token);
            return rsp.getResult();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return new OapiV2DepartmentListparentbyuserResponse.DeptListParentByUserResponse();
    }

    /**
     * 获取通讯录权限范围
     */
    public Map<String,Object> getScopes(){
        //获取access_token
        String token = accessTokenUtils.getToken();
        Map<String,Object> map = new HashMap<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/auth/scopes");
            OapiAuthScopesRequest req = new OapiAuthScopesRequest();
            req.setHttpMethod("GET");
            OapiAuthScopesResponse rsp = client.execute(req, token);
            OapiAuthScopesResponse.AuthOrgScopes authOrgScopes = rsp.getAuthOrgScopes();
            List<String> authUserField = rsp.getAuthUserField();
            map.put("authOrgScopes",authOrgScopes);
            map.put("authUserField",authUserField);
            return map;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return map;
    }
}
