package com.hotent.uc.manager.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalktodo_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.OpenDingTalkClient;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonArray;
import com.hotent.base.feign.BpmRuntimeFeignService;
import com.hotent.base.feign.PortalFeignService;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.*;
import com.hotent.uc.dao.DIngApiDao;
import com.hotent.uc.dao.DIngUserDao;
import com.hotent.uc.dao.DIngUserDeptDao;
import com.hotent.uc.dao.OrgDao;
import com.hotent.uc.manager.*;
import com.hotent.uc.model.*;
import com.hotent.uc.params.org.OrgVo;
import com.hotent.uc.util.Constant;
import com.hotent.uc.util.ContextUtil;
import com.hotent.uc.util.DingCallbackCrypto;
import com.hotent.uc.util.DingTalkConsts;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 用户与外部通讯录关系表 服务实现类
 *
 * @company 广州宏天软件股份有限公司
 * @author pangquan
 * @since 2020-10-30
 */
@Service
public class DIngApiManagerImpl extends BaseManagerImpl<DIngApiDao, OrgExternalDept> implements DingApiManager {

    //    @Value("${dingSetting.appkey}")
//    private  String clientId;//钉钉应用key
//    @Value("${dingSetting.appSecret}")
//    private  String appSecret;//钉钉应用密钥
    @Autowired
    private OrgExternalSettingManager orgExtSettingService;
    private static  String appSecret;
    @Value("${dingSetting.appSecret}")
    public void setAppSecret(String appSecret) {
        DIngApiManagerImpl.appSecret = appSecret;
    }

    private static  String clientId;
    @Value("${dingSetting.appkey}")
    public void setClientId(String clientId) {
        DIngApiManagerImpl.clientId = clientId;
    }

    @Autowired
    private OrgDao orgDao;
    @Autowired
    private OrgManager orgManager;
    @Autowired
    private DingUserManager dingUserManager;
    @Autowired
    private DingUserDeptManager dingUserDeptManager;
    @Autowired
    private DIngUserDao dingUserDao;
    @Autowired
    private com.hotent.uc.dao.DIngUserDeptDao dingUserDeptDao;
    @Autowired
    private UserManager userManager;
    @Autowired
    private OrgExternalSettingManager orgExternalSettingManager;
    @Autowired
    private ExtOrgLogManager extOrgLogManager;
    @Autowired
    private DingTokenManager dingTokenManager;
    @Autowired
    PortalFeignService portalFeignService;
    @Value("${dingSetting.dingPcTodoUrl}")
    private String dingPcTodoUrl;

    @Value("${dingSetting.dingAppTodoUrl}")
    private String dingAppTodoUrl;
    @Resource
    BpmRuntimeFeignService bpmRuntimeFeignService;

    @Override
    public String[] addDingApiDept(Org org,String orgId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/create");
        OapiV2DepartmentCreateRequest req = new OapiV2DepartmentCreateRequest();
        req.setParentId(Long.parseLong(org.getParentId()));//父部门ID，根部门ID为1。
        req.setName(org.getName());//部门名称。
        OapiV2DepartmentCreateResponse rsp = null;
        try {
            rsp = client.execute(req, getAccessToken(orgId));
            System.out.println(rsp.getBody());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
            if(jsonObject!=null){
                cn.hutool.json.JSONObject result= new cn.hutool.json.JSONObject(jsonObject.get("result"));
                int errcode= (int) jsonObject.get("errcode");
                String[] resultArr=new String[3];
                resultArr[0]=errcode+"";
                if(errcode==0){
                    int dingDeptId= (int) result.get("dept_id");
                    resultArr[1]=dingDeptId+"";
                    return resultArr;
                }else{
                    if(errcode==60021){
                        String errmsg= (String) jsonObject.get("errmsg");
                        String deptId=errmsg.split("=")[1].trim();
                        resultArr[1]=deptId;
                        resultArr[0]="0";
                    }else{
                        String errmsg= (String) jsonObject.get("errmsg");
                        resultArr[1]=org.getName()+"部门，层级："+org.getPathName()+",部门创建失败，原因："+errmsg;
                    }
                    return resultArr;
                }
            }
            return null;

        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public JSONObject updateDingApiDept(OrgExternalDept org,String orgId) {
        if(StringUtil.isNotEmpty(org.getExternalDeptId())){
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/update");
            OapiV2DepartmentUpdateRequest req = new OapiV2DepartmentUpdateRequest();
            req.setDeptId(Long.parseLong(org.getExternalDeptId()));
            req.setParentId(Long.parseLong(org.getExternalParentId()));
            req.setName(org.getExternalName());
            req.setLanguage("zh_CN");
            OapiV2DepartmentUpdateResponse rsp = null;
            try {
                rsp = client.execute(req, getAccessToken(orgId));
                System.out.println(rsp.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void loopGetDeptList(String orgId,String deptId,String pahtName) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        req.setDeptId(Long.parseLong(deptId));
        req.setLanguage("zh_CN");
        OapiV2DepartmentListsubResponse rsp = null;
        try {
            rsp = client.execute(req, getAccessToken(orgId));
            System.out.println(rsp.getBody());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
            int errorCode= (int) jsonObject.get("errcode");
            if(errorCode==0){
                JSONArray jsonArray= jsonObject.getJSONArray("result");
                if(jsonArray.size()>0){
                    for(int i=0;i<jsonArray.size();i++){
                        JSONObject jsonDept= (JSONObject) jsonArray.get(i);
                        int deptId_temp= (int) jsonDept.get("dept_id");
                        String name= (String) jsonDept.get("name");
                        int parent_id= (int) jsonDept.get("parent_id");
                        System.out.println("departName="+name);
                        OrgExternalDept saveEntity=new OrgExternalDept();
                        saveEntity.setCreateTime(LocalDateTime.now());
                        saveEntity.setExternalDeptId(deptId_temp+"");
                        saveEntity.setExternalName(name);
                        saveEntity.setExternalParentId(parent_id+"");
                        saveEntity.setType(Constant.EXTERNAL_DING_FLAG);
                        saveEntity.setPathName(pahtName+"/"+name);
                        saveEntity.setOrgId(orgId);
                        saveEntity.setDingDelete(Constant.DING_DATA_STATUS_0);
                        saveDingDept(orgId,saveEntity);
                        if(!Objects.isNull(deptId_temp)){
                            loopGetDeptList(orgId,deptId_temp+"",pahtName+"/"+name);
                        }
                    }
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

    }

    @Override
    public CommonResult<String> synDingDept(String orgId, String deptId) {
        List<CommonResult<String>> resultList=new ArrayList<>();
        Org orgIndex=orgDao.get(orgId);
        String pushType=orgIndex.getJoinExtSystemType();//=1为钉钉
        String pushDir=orgIndex.getJoinExtSystemSyndir();//=0=>钉钉
        if(StringUtil.isEmpty(pushType)){
            return new CommonResult<String>(true, "该组织没有开启组织同步", "");
        }
        if(StringUtil.isNotEmpty(pushType)&&pushType.equals(Org.ORG_SYN_TYPE_0)){
            return new CommonResult<String>(true, "该组织没有开启组织同步", "");
        }
        if(pushType.equals(Org.ORG_SYN_TYPE_1)){//钉钉推送
            if(StringUtil.isNotEmpty(pushDir)){

                if(pushDir.equals("0")){//=>钉钉
                    resultList= releSystemToDingDeptFun(orgId);
                }else if(pushDir.equals("1")){//=>系统
                    CompletableFuture<Boolean>  supplyAsync=CompletableFuture.supplyAsync(()->{
                        loopGetDeptList(orgId,deptId,"");
                        return true;
                    });
                    if(supplyAsync.join()){
                        resultList=releDingToSystemDeptFun(orgId);
                    }
                }
            }
        }
        extOrgLogManager.saveSynExtOrgLog(resultList,orgId,pushType,pushDir,"0");
        return new CommonResult<String>(true, "同步部门数据成功！", resultList.stream().map(r->r.getValue()).collect(Collectors.joining()));
    }
    //钉钉向系统中同步部门
    private  List<CommonResult<String>> releDingToSystemDeptFun(String orgId){
        List<CommonResult<String>> resultList=new ArrayList<>();
        LambdaQueryWrapper<OrgExternalDept> orgExtDeptQw=new LambdaQueryWrapper<>();
        orgExtDeptQw.eq(OrgExternalDept::getOrgId,orgId);
        List<OrgExternalDept> orgExtDeptList=this.baseMapper.selectList(orgExtDeptQw);
        if(orgExtDeptList.size()>0){
            orgExtDeptList.stream().forEach(item->{
                if(item.getExternalDeptId()!=null){
                    CommonResult<String> result=  releDingToSystemDept(orgId,item.getExternalDeptId());
                    resultList.add(result);
                }
            });
        }
        return  resultList;
    }

    //系统向钉钉中同步部门
    private   List<CommonResult<String>>  releSystemToDingDeptFun(String orgId){
        List<CommonResult<String>> resultList=new ArrayList<>();
        List<Org> orgList=getOrgAllDept(orgId);
        if(orgList.size()>0){
            orgList.stream().forEach(item->{
                if(item.getId()!=null){
                    CommonResult<String> result=  releSystemToDingdept(orgId,item.getId());
                    System.out.println(result.getValue());
                    resultList.add(result);
                }
            });
        }
        return  resultList;
    }
    /**
     * @description
     * @author  yangzibin
     * @date    2024/1/12 14:19
     * @param	orgId  组织id
     * @return  java.util.List<com.hotent.uc.model.Org>
     */
    private List<Org> getOrgAllDept(String orgId){
        Org orgIndex= orgDao.get(orgId);
        QueryWrapper<Org> extList=new QueryWrapper<>();
        extList.like("PATH_NAME_",orgIndex.getPathName());
        extList.eq("IS_DELE_","0");
        extList.eq("ORG_TYPE_",Org.ORG_TYPE_DEP);//只同步部门
        List<Org> orgList=orgDao.selectOrgByWrapper(extList);//查找数据
        return  orgList;
    }

    @Override
    public void saveDingDept(String orgId,OrgExternalDept extDingDept) {
        LambdaQueryWrapper<OrgExternalDept> deptQw=new LambdaQueryWrapper<>();
        deptQw.eq(OrgExternalDept::getExternalParentId,extDingDept.getExternalParentId());
        deptQw.eq(OrgExternalDept::getExternalDeptId,extDingDept.getExternalDeptId());
        OrgExternalDept haveEntity= this.baseMapper.selectOne(deptQw);
        if(haveEntity==null){
            this.save(extDingDept);
        }else{
            extDingDept.setUpdateTime(LocalDateTime.now());
            extDingDept.setId(haveEntity.getId());
            extDingDept.setTenantId(haveEntity.getTenantId());
            extDingDept.setDeptId(haveEntity.getDeptId());
            this.saveOrUpdate(extDingDept);
        }
    }

    @Override
    public CommonResult<String> releDingToSystemDept(String orgId, String externalDeptId) {

        List<OrgExternalDept> list=getExtDeptList(externalDeptId);
        Org org=orgDao.get(orgId);
        for(int i=0;i<list.size();i++){
            OrgExternalDept entity=list.get(i);
            QueryWrapper<Org> extList=new QueryWrapper<>();
            extList.eq("ORG_TYPE_",Org.ORG_TYPE_DEP);
            extList.eq("IS_DELE_","0");
            if(entity.getDeptId()!=null){
                extList.eq("ID_",entity.getDeptId()).or(e->e.eq("PATH_NAME_",org.getPathName()+entity.getPathName()).like("PATH_",orgId));
            }else{
                extList.like("PATH_",orgId);
                extList.eq("PATH_NAME_",org.getPathName()+entity.getPathName());//拼接当前部门的pathName
            }

            List<Org> result=orgDao.selectOrgByWrapper(extList);//查询钉钉部门是否在中台中存在
            if(result.size()>0){//存在部门直接关联
                entity.setDeptId(result.get(0).getId());
                entity.setUpdateTime(LocalDateTime.now());
                this.saveOrUpdate(entity);
                updateDeptaData(entity,result.get(0));
                return new CommonResult<String>(true, entity.getExternalName()+"更新数据成功", entity.getExternalName()+"更新数据成功");
            }else{//不存在的部门进行创建
                String orgNewId=addOrgData(entity,org);
                entity.setDeptId(orgNewId);
                entity.setUpdateTime(LocalDateTime.now());
                this.saveOrUpdate(entity);
                return new CommonResult<String>(true, entity.getExternalName()+"新增数据成功", entity.getExternalName()+"新增数据成功");
            }
        }
        return new CommonResult<String>(true, "同步部门数据成功！", "");
    }
    /**
     * @description  根据orgid pathName path 确定部门
     * @author  yangzibin
     * @date    2024/1/12 14:40
     * @param	pathName
     * @param	deptName
     * @param	orgId
     * @return  com.hotent.uc.model.Org
     */
    private Org getDeptNameAndPathName(String pathName,String deptName,String orgId){
        Org orgIndex=orgDao.get(orgId);
        LambdaQueryWrapper<Org> orgQw=new LambdaQueryWrapper<>();
        orgQw.eq(Org::getPathName,orgIndex.getPathName()+pathName);
        orgQw.eq(Org::getName,deptName);
        orgQw.like(Org::getPath,orgId);
        Org org=orgDao.selectOne(orgQw);
        return  org;
    }

    @Override
    public CommonResult<String> releSystemToDingdept(String orgId, String deptId) {
        List<String> dingAddDeptResult=new ArrayList<>();
        Org org=orgDao.get(deptId);//当前部门
        Org orgIndex=orgDao.get(orgId);//部门所属组织

        try {
            OrgExternalSetting orgExternalSetting=  orgExternalSettingManager.querySettingByCorpIdReturn(orgId);
            if(orgExternalSetting==null){
                return new CommonResult<String>(false, "该组织没有添加外部系统配置", dingAddDeptResult.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<String> nameList=getPathNameList(org.getPathName());
        List<String> dingDeptId=new ArrayList<>();
        String pathName="";
        for(int i=0;i<nameList.size();i++){
            String name=nameList.get(i);
            Org orgTemp=getDeptNameAndPathName(pathName+"/"+name,name,orgId);
            LambdaQueryWrapper<OrgExternalDept> deptQw=new LambdaQueryWrapper<>();
            deptQw.eq(OrgExternalDept::getOrgId,orgId);
            if(orgTemp!=null){
                deptQw.eq(OrgExternalDept::getDeptId,orgTemp.getId());
            }else{
                deptQw.eq(OrgExternalDept::getExternalName,name);
                deptQw.eq(OrgExternalDept::getPathName,pathName+"/"+name);
            }
            OrgExternalDept haveEntity= this.baseMapper.selectOne(deptQw);
            pathName=pathName+"/"+name;
            if(haveEntity==null){//没有进行创建部门
                String deptDingId="";
                Org orgDing =new Org();
                if(i==0){
                    orgDing.setParentId("1");
                }else{
                    orgDing.setParentId(dingDeptId.get(i-1));
                }
                orgDing.setName(name);
                orgDing.setPathName(pathName);
                //通过钉钉api创建部门返回钉钉部门id
                String[] resultArr=addDingApiDept(orgDing,orgId);//返回数组结果
                //储存钉钉部门id
                if(resultArr!=null){
                    if(resultArr[0].equals("0")){
                        deptDingId=resultArr[1];
                        dingAddDeptResult.add(orgTemp.getName()+"添加部门成功");
                    }else{
                        dingAddDeptResult.add(orgTemp.getName()+"添加部门失败，原因；"+resultArr[1]+"");
                    }
                }
                dingDeptId.add(deptDingId);
                //创建钉钉关联
                if(orgTemp!=null){
                    OrgExternalDept orgExtDept=new OrgExternalDept();
                    orgExtDept.setOrgId(deptId);
                    orgExtDept.setExternalName(name);
                    orgExtDept.setExternalDeptId(deptDingId);
                    orgExtDept.setExternalParentId(orgDing.getParentId());
                    orgExtDept.setDeptId(orgTemp.getId());
                    orgExtDept.setType(Constant.EXTERNAL_DING_FLAG);
                    orgExtDept.setDingDelete(Constant.DING_DATA_STATUS_0);
                    orgExtDept.setCreateTime(LocalDateTime.now());
                    orgExtDept.setPathName(orgTemp.getPathName().replaceAll(orgIndex.getPathName(),""));
                    orgExtDept.setOrgId(orgId);
                    this.saveOrUpdate(orgExtDept);
                }
            }else{//更新部门名称
                dingDeptId.add(haveEntity.getExternalDeptId());
                haveEntity.setExternalName(orgTemp.getName());
                haveEntity.setPathName(orgTemp.getPathName().replaceAll(orgIndex.getPathName(),""));
                this.saveOrUpdate(haveEntity);//更新必要数据
                dingAddDeptResult.add(orgTemp.getName()+"更新部门成功");
                //调用接口更新钉钉部门
                updateDingApiDept(haveEntity,orgId);
            }
        }

        return new CommonResult<String>(true, "向钉钉同步部门数据成功！", dingAddDeptResult.toString());
    }

    @Override
    public CommonResult<String> getDingALlUser(String orgId) {
        List<CommonResult<String>> resultList=new ArrayList<>();
        Org orgIndex=orgDao.get(orgId);
        String pushType=orgIndex.getJoinExtSystemType();//=1为钉钉
        String pushDir=orgIndex.getJoinExtSystemSyndir();//=0=>钉钉
        if(StringUtil.isEmpty(pushType)){
            return new CommonResult<String>(true, "该组织没有开启组织同步", "");
        }
        if(StringUtil.isNotEmpty(pushType)&&pushType.equals(Org.ORG_SYN_TYPE_0)){
            return new CommonResult<String>(true, "该组织没有开启组织同步", "");
        }


        if(pushType.equals(Org.ORG_SYN_TYPE_1)){//钉钉推送
            if(StringUtil.isNotEmpty(pushDir)){
                if(pushDir.equals("0")){//=>钉钉
                    //中台 => 钉钉同步用户
                    resultList=releSystemToDingUser(orgId);
                }else if(pushDir.equals("1")){//=>系统
                    LambdaQueryWrapper<OrgExternalDept> deptQw=new LambdaQueryWrapper<>();
                    deptQw.eq(OrgExternalDept::getOrgId,orgId);
                    List<OrgExternalDept> extDeptList=this.baseMapper.selectList(deptQw);
                    if(extDeptList.size()<1){
                        return  new CommonResult<String>(false, "该组织没有同步钉钉部门！", "");
                    }
                    List<String> extDeptIdList=extDeptList.stream().map(e->e.getExternalDeptId()).collect(Collectors.toList());
                    if(extDeptIdList.size()>0){
                        extDeptIdList.add(0,"1");
                        //****************************1.同步用户首先得先把钉钉的用户数据拉取到中台的中间表中**********************************
                        CompletableFuture<Boolean>  supplyAsync=CompletableFuture.supplyAsync(()->{
                            getDingUser(orgId,extDeptIdList);
                            return true;
                        });
                        System.out.println("异步完成结果====================："+supplyAsync.join());
                        //****************************2.拉取完成钉钉用户，再进行选向的同步操作**********************************
                        if(supplyAsync.join()){
                            // 加载完钉钉用户数据，处理用户同步，需要根据用户手机号进行查询
                            //钉钉 => 中台同步用户
                            resultList=releDingToSystemUser(orgId);

                        }
                    }
                }
            }
        }
        extOrgLogManager.saveSynExtOrgLog(resultList,orgId,pushType,pushDir,"1");
        return new CommonResult<String>(true, "获取钉钉用户成功！", "");
    }
    /**
     * @description  中台向钉钉批量同步用户
     * @author  yangzibin
     * @date    2024/1/9 14:06
     * @param
     * @return  void
     */
    private List<CommonResult<String>> releSystemToDingUser(String orgId){
        List<User> userList= new ArrayList<>();//查询组织所有用户
        List<CommonResult<String>> resultList=new ArrayList<>();
        try {
            Org orgIndex=orgDao.get(orgId);
            LambdaQueryWrapper<Org> orgQw=new LambdaQueryWrapper<>();
            orgQw.like(Org::getPathName,orgIndex.getPathName());
            orgQw.like(Org::getOrgType,Org.ORG_TYPE_DEP);
            orgQw.eq(Org::getIsDelete,"0");
            List<Org> orgList=orgDao.selectList(orgQw);
            orgList.add(orgIndex);
            orgList.forEach(item->{
                try {
                    userList.addAll(userManager.getUserListByOrgId(item.getId()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
//            userList.stream().distinct().collect(Collectors.toList());
            List<User> userListTemp= new ArrayList<>();//查询组织所有用户
            userListTemp=userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getId()))), ArrayList::new));
            userListTemp.stream().forEach(item->{
                CommonResult<String> resultStr= dingUserManager.systemToDingUser(orgId,item);
                resultList.add(resultStr);
            });
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
    static <T> Predicate<T> distinctByKey1(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    /**
     * @description  钉钉向中台批量同步用户
     * @author  yangzibin
     * @date    2024/1/9 14:06
     * @param
     * @return  void
     */
    private List<CommonResult<String>> releDingToSystemUser(String orgId){
        List<CommonResult<String>> resultList=new ArrayList<>();
        LambdaQueryWrapper<OrgExternalUser> orgExtUserQw=new LambdaQueryWrapper<>();
        orgExtUserQw.eq(OrgExternalUser::getOrgId,orgId);
        List<OrgExternalUser> orgExtUserList=dingUserDao.selectList(orgExtUserQw);
        if(orgExtUserList.size()>0){
            orgExtUserList.stream().forEach(item->{
                CommonResult<String> result=dingUserManager.dingToSystemUser(orgId,item);
                resultList.add(result);
                System.out.println(result.getMessage());
            });
        }
        return  resultList;
    }
    /**
     * @description  根据部门id获取钉钉用户
     * @author  yangzibin
     * @date    2024/1/4 16:49
     * @param	extDeptIdList
     * @return  void
     */
    private void getDingUser(String orgId,List<String> extDeptIdList){
        for(int i=0;i<extDeptIdList.size();i++){
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
            OapiUserListidRequest req = new OapiUserListidRequest();
            req.setDeptId(Long.parseLong(extDeptIdList.get(i)));
            OapiUserListidResponse rsp = null;
            try {
                rsp = client.execute(req, getAccessToken(orgId));
                System.out.println(rsp.getBody());
                cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
                int errorCode= (int) jsonObject.get("errcode");
                if(errorCode==0){
                    cn.hutool.json.JSONObject jsonResult= (JSONObject) jsonObject.get("result");
                    cn.hutool.json.JSONArray jsonArray=jsonResult.getJSONArray("userid_list");
                    if(jsonArray.size()>0){
                        for(int j=0;j<jsonArray.size();j++){
                            String userId= (String) jsonArray.get(j);
                            getUserInfo(orgId,userId,extDeptIdList.get(i));
                        }
                    }
                }
            } catch (ApiException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * @description 获取钉钉用户详细信息
     * @author  yangzibin
     * @date    2024/1/4 17:22
     * @param
     * @return  void
     */
    private void getUserInfo(String orgId,String userId,String extDeptId){
        cn.hutool.json.JSONObject jsonResult= getDingUserInfo(userId,orgId);
        if(jsonResult!=null){//验证用户是否已存在
            OrgExternalUser orgExtUser=new OrgExternalUser();
            orgExtUser.setExternalUserId(userId);
            orgExtUser.setExternalUserName((String) jsonResult.get("name"));
            orgExtUser.setExternalMobile((String) jsonResult.get("mobile"));
            orgExtUser.setExternalJobNumber((String) jsonResult.get("job_number"));
            orgExtUser.setExternalPost((String) jsonResult.get("title"));
            orgExtUser.setOrgId(orgId);
            orgExtUser.setType(Constant.EXTERNAL_DING_FLAG);
            orgExtUser.setDingDelete(Constant.DING_DATA_STATUS_0);
            orgExtUser.setCreateTime(LocalDateTime.now());


            //通过手机号查询中间表是否已有此钉钉用户
            LambdaQueryWrapper<OrgExternalUser> orgExtUserQw=new LambdaQueryWrapper<>();
            orgExtUserQw.eq(OrgExternalUser::getExternalMobile,jsonResult.get("mobile"));
            orgExtUserQw.eq(OrgExternalUser::getOrgId,orgId);
            List<OrgExternalUser> userList=dingUserDao.selectList(orgExtUserQw);
            if(userList.size()>0){//防止用户多部门重复创建用户
                orgExtUser.setId(userList.get(0).getId());
                orgExtUser.setTenantId(userList.get(0).getTenantId());
                this.dingUserManager.update(orgExtUser);
            }else{
                orgExtUser.setId("");
                this.dingUserManager.save(orgExtUser);
            }
            addDingUserDept(userId,extDeptId,orgId);
        }
    }
    /**
     * @description  获取钉钉用户详细信息
     * @author  yangzibin
     * @date    2024/1/10 10:09
     * @param	userId
     * @return  cn.hutool.json.JSONObject
     */
    private cn.hutool.json.JSONObject getDingUserInfo(String userId,String orgId){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, getAccessToken(orgId));
            System.out.println(rsp.getBody());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
            int errorCode= (int) jsonObject.get("errcode");
            if(errorCode==0){
                cn.hutool.json.JSONObject jsonResult= (JSONObject) jsonObject.get("result");
                return jsonResult;
            }
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    private void addDingUserDept(String dingUserId,String dingDeptId,String orgId){
        LambdaQueryWrapper<OrgExternalUserDept> userDeptQw=new LambdaQueryWrapper<>();
        userDeptQw.eq(OrgExternalUserDept::getExternalUserId,dingUserId);
        userDeptQw.eq(OrgExternalUserDept::getExternaldDeptId,dingDeptId);
        userDeptQw.eq(OrgExternalUserDept::getOrgId,orgId);
        List<OrgExternalUserDept> orgExternalUserDeptList= dingUserDeptDao.selectList(userDeptQw);
        if(orgExternalUserDeptList.size()==0){
            OrgExternalUserDept orgUserDept=new OrgExternalUserDept();
            orgUserDept.setExternaldDeptId(dingDeptId);
            orgUserDept.setExternalUserId(dingUserId);
            orgUserDept.setOrgId(orgId);
            orgUserDept.setCreateTime(LocalDateTime.now());
            this.dingUserDeptManager.saveOrUpdate(orgUserDept);
        }
    }
    private void updateDeptaData(OrgExternalDept entity, Org org){
        org.setName(entity.getExternalName());
        org.setPathName(entity.getPathName());
        if(entity.getDingDelete().equals(Constant.DING_DATA_STATUS_1)){
            org.setIsDelete(Constant.DING_DATA_STATUS_1);
            orgManager.removeByIds(org.getId());
        }else{
            orgManager.update(org);
        }
    }

    /**
     * @description  钉钉同步部门不存在进行创建中台部门
     * @author  yangzibin
     * @date    2024/1/3 10:15
     * @param
     * @return  void
     */
    private String  addOrgData(OrgExternalDept entity, Org org){
        String pathName=entity.getPathName();
        String[] tempList=pathName.split("/");
        tempList=Arrays.stream(tempList).filter(e->e!=null&&!e.isEmpty()).toArray(String[]::new);
        List<String> haveOrgId=new ArrayList<>();
        String pathNameTemp=org.getPathName();
        for(int i=0;i<tempList.length;i++){
            String name=tempList[i];
            if(StringUtil.isNotEmpty(name)){
                QueryWrapper<Org> extList=new QueryWrapper<>();
                extList.like("PATH_",org.getId());
                extList.eq("NAME_",name);
                extList.eq("ORG_TYPE_",Org.ORG_TYPE_DEP);
                extList.eq("IS_DELE_","0");
                extList.eq("PATH_NAME_",pathNameTemp+"/"+name);
                List<Org> result=orgDao.selectOrgByWrapper(extList);//查询组织中是否有当前名称的部门
                if(result.size()==0){//部门不存在开始创建i=0为跟部门
                    OrgVo orgTemp=new OrgVo();
                    String deptId= UniqueIdUtil.getSuid();
                    orgTemp.setId(deptId);
                    if(i==0){
                        orgTemp.setParentId(org.getId());//部门父id
                    }else{
                        orgTemp.setParentId(haveOrgId.get(i-1));//部门父id
                    }
                    orgTemp.setName(name);//部门名称
                    orgTemp.setCode(deptId);//将id放入code保证唯一
                    orgTemp.setDemId(org.getDemId());
                    orgTemp.setOrgType(Org.ORG_TYPE_DEP);
                    try {
                        orgManager.addOrg(orgTemp);
                        haveOrgId.add(deptId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else{
                    haveOrgId.add(result.get(0).getId());
                    Org orgTemp= result.get(0);
                    orgTemp.setName(name);
                    orgManager.saveOrUpdate(orgTemp);
                }
                pathNameTemp=pathNameTemp+"/"+name;
            }
        }
        return haveOrgId.get(haveOrgId.size()-1);
    }

    private List<OrgExternalDept> getExtDeptList(String externalDeptId){
        LambdaQueryWrapper<OrgExternalDept> extList=new LambdaQueryWrapper<>();
        if(StringUtil.isNotEmpty(externalDeptId)){
            extList.eq(OrgExternalDept::getExternalDeptId,externalDeptId);
        }
        List<OrgExternalDept> resultList=this.baseMapper.selectList(extList);
        return resultList;
    }
    /**
     * @description  处理去除组织名称
     * @author  yangzibin
     * @date    2024/1/3 15:35
     * @param	pathName
     * @return  java.util.List<java.lang.String>
     */
    private List<String> getPathNameList(String pathName){
        String[] tempList =pathName.split("/");
        tempList=Arrays.stream(tempList).filter(e->e!=null&&!e.isEmpty()).toArray(String[]::new);
        tempList=Arrays.copyOfRange(tempList,1,tempList.length);
        List<String> tempIdList= Arrays.asList(tempList);
        return tempIdList;
    }

    /**
     * @description  钉钉sdk旧版token
     * @author  yangzibin
     * @date    2024/1/2 10:34
     * @param
     * @return  java.lang.String
     */
    public  String getAccessToken(String orgId){
        OrgExternalSetting setting=null;
        try {
            setting=  orgExternalSettingManager.querySettingByCorpIdReturn(orgId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(setting==null){
            return "没有配置";
        }
        String token=dingTokenManager.getDingToken(orgId,setting.getDingAgentId(),"0");
        if(BeanUtils.isNotEmpty(token)){
            return  token;
        }
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(setting.getDingAppClientId());
        request.setAppsecret(setting.getDingAppSecret());
        request.setHttpMethod("GET");
        OapiGettokenResponse response = null;
        try {
            response = client.execute(request);
            String body=response.getBody();
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(body);
            if(jsonObject!=null){
                String tokenTemp= (String) jsonObject.get("access_token");
                dingTokenManager.saveDingToken(orgId,setting.getDingAgentId(),tokenTemp,"0");
                return  tokenTemp;
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return  null;
    }
    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public  com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }
    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalktodo_1_0.Client createClient1() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalktodo_1_0.Client(config);
    }
    /**
     * @description 新版钉钉 获取token
     * @author  yangzibin
     * @date    2024/3/1 17:42
     * @param	orgId
     * @return  java.lang.String
     */
    public  String getAccessTokenNew (String orgId){
        OrgExternalSetting setting=null;
        try {
            setting=  orgExternalSettingManager.querySettingByCorpIdReturn(orgId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(setting==null){
            return "没有配置";
        }
        String token=dingTokenManager.getDingToken(orgId,setting.getDingAgentId(),"1");
        if(BeanUtils.isNotEmpty(token)){
            return  token;
        }
        String dingAppkey=setting.getDingAppKey();
        String dingAppSecret=setting.getDingAppSecret();
        com.aliyun.dingtalkoauth2_1_0.Client client = null;
        try {
            client = createClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey(dingAppkey)
                .setAppSecret(dingAppSecret);
        try {
            GetAccessTokenResponse gs=client.getAccessToken(getAccessTokenRequest);
            System.out.println(gs.getBody().accessToken);
            dingTokenManager.saveDingToken(orgId,setting.getDingAgentId(),gs.getBody().accessToken,"1");
            return gs.getBody().accessToken;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                System.out.println(err.message);
                return "";
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.message);
                return "";
            }
        }
        return "";
    }

    /**
     * @description  开启流接收数据
     * @author  yangzibin
     * @date    2024/1/9 17:19
     * @param
     * @return  void
     */
    @Override
    public  CommonResult<String> startDingStreamData(String orgId,String open){
        try {
            //拆查询本组织的钉钉配置
            OpenDingTalkClient client=
                    OpenDingTalkStreamClientBuilder
                            .custom()
                            .credential(new AuthClientCredential(clientId, appSecret))
                            //注册事件监听
                            .registerAllEventListener(new GenericEventListener() {
                                public EventAckStatus onEvent(GenericOpenDingTalkEvent event) {
                                    try {
                                        //事件唯一Id
                                        String eventId = event.getEventId();
                                        //事件类型
                                        String eventType = event.getEventType();
                                        System.out.println(eventType);
                                        //事件产生时间
                                        Long bornTime = event.getEventBornTime();
                                        //获取事件体
                                        shade.com.alibaba.fastjson2.JSONObject bizData = event.getData();
                                        //处理事件
                                        productData(orgId,"-1",bizData,eventType);
                                        //消费成功
                                        return EventAckStatus.SUCCESS;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        //消费失败
                                        return EventAckStatus.LATER;
                                    }
                                }
                            })
                            .build();
            if(open.equals("0")){
                client.start();
            }else{
                client.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult<String>(true, "开启钉钉stream接收数据成功！", "");
    }

    @Override
    public CommonResult<List<OrgExternalDept>> queryExtDeptList(String orgId, String parentId) {
        LambdaQueryWrapper<OrgExternalDept> orgQw=new LambdaQueryWrapper<>();
        orgQw.eq(OrgExternalDept::getOrgId,orgId);
        orgQw.eq(OrgExternalDept::getExternalParentId,parentId);
        List<OrgExternalDept> orgExtDeptList=this.baseMapper.selectList(orgQw);
        return new CommonResult<List<OrgExternalDept>>(true, "获取外部系统部门成功！", orgExtDeptList);
    }

    @Override
    public Map<String, Object> getDingPushData(String msg_signature, String timeStamp, String nonce, JSONObject json,String corpId) {
        try {
            // 1. 从http请求中获取加解密参数

            // 2. 使用加解密类型
            // Constant.OWNER_KEY 说明：
            // 1、开发者后台配置的订阅事件为应用级事件推送，此时OWNER_KEY为应用的APP_KEY。
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，
            //      此时OWNER_KEY为：企业的appkey（企业内部应用）或SUITE_KEY（三方应用）
            OrgExternalSetting orgExternalSetting=null;
            try {
                orgExternalSetting=orgExternalSettingManager.queryByCorpId(corpId);
                Map<String, Object> successMap =new HashMap<>();
                successMap.put("msg","不存在的配置");
                if(orgExternalSetting==null){
                    return successMap;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(orgExternalSetting.getPushSignToken(), orgExternalSetting.getPushAseKey(),orgExternalSetting.getDingAppKey());
            String encryptMsg = (String) json.get("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);

            // 3. 反序列化回调事件json数据
            shade.com.alibaba.fastjson2.JSONObject eventJson = shade.com.alibaba.fastjson2.JSON.parseObject(decryptMsg);
            String eventType = eventJson.getString("EventType");
//            String corpId = eventJson.getString("CorpId");
            // 4. 根据EventType分类处理
            if ("check_url".equals(eventType)) {
                // 测试回调url的正确性
                System.out.println("测试回调url的正确性");
                Map<String, Object> successMap = callbackCrypto.getEncryptedMap("success");
                return successMap;

            } else if ("user_add_org".equals(eventType)) {
                // 处理通讯录用户增加事件
                System.out.println("发生了：" + eventType + "事件");
            } else {
                // 添加其他已注册的
                System.out.println("发生了：" + eventType + "事件");
            }
//            if(getOrgSynDir(orgExternalSetting.getOrgId())){
            productData(orgExternalSetting.getOrgId(),orgExternalSetting.getTenantId(),eventJson,eventType);
//            }

//
            // 5. 返回success的加密数据
            Map<String, Object> successMap = callbackCrypto.getEncryptedMap("success");
            return successMap;

        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public Map<String, Object> deleteDingDept(Org org) {
        LambdaQueryWrapper<OrgExternalDept> orgExternalDeptQw =new LambdaQueryWrapper<>();
        orgExternalDeptQw.eq(OrgExternalDept::getDeptId,org.getId());
        List<OrgExternalDept>  orgExtDeptList=this.baseMapper.selectList(orgExternalDeptQw);

        if(orgExtDeptList.size()>0&&orgExtDeptList.get(0).getExternalDeptId()!=null){
            Org orgIndex=orgDao.get(orgExtDeptList.get(0).getOrgId());
            if(orgIndex.getJoinExtSystemType().equals(Org.ORG_SYN_TYPE_1)&&orgIndex.getJoinExtSystemSyndir()!=null&&orgIndex.getJoinExtSystemSyndir().equals(Org.ORG_SYN_DIR_0)){
                String[] result=deleteDingDeptApi(orgExtDeptList.get(0).getExternalDeptId(),orgExtDeptList.get(0).getOrgId());
                if(result[0].equals("0")){//删除成功
                    orgExtDeptList.get(0).setDingDelete(Constant.DING_DATA_STATUS_1);
                    this.saveOrUpdate(orgExtDeptList.get(0));
                }
            }
        }


        return null;
    }

    @Override
    public String getDingTokenNew(String orgId,String tokenType) {
        if(tokenType.equals("0")){
            return  getAccessToken(orgId);
        }else{
            return  getAccessTokenNew(orgId);
        }
    }

    @Override
    public String getDingUserUnionId(String orgId, String dingUserId) {
        cn.hutool.json.JSONObject jsonObject=getDingUserInfo(dingUserId,orgId);
        if(jsonObject!=null){
            String unionid= (String) jsonObject.get("unionid");
            return unionid;
        }
        return null;
    }
    public static com.aliyun.dingtalktodo_1_0.Client createDingToDoClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalktodo_1_0.Client(config);
    }
    @Override
    public boolean updateDingToTask(String taskId) {

        ArrayNode arrayNode= portalFeignService.queryEntityById(taskId);
        if(arrayNode==null){
            return false;
        }
        for(int i=0;i<arrayNode.size();i++){
            JsonNode   jsonNode=arrayNode.get(i);

            String dingTodoTaskId=jsonNode.get("dingTodoTaskId").asText();///钉钉待办id
            String orgId=jsonNode.get("orgId").asText();///组织id

            String dingUserUnionId=jsonNode.get("dingUserUnionId").asText();///执行人钉钉unionid

            String token=getDingTokenNew(orgId,"1");

            com.aliyun.dingtalktodo_1_0.Client client = null;
            try {
                client = createDingToDoClient();
            } catch (Exception e) {
                e.printStackTrace();
            }
            UpdateTodoTaskExecutorStatusHeaders updateTodoTaskExecutorStatusHeaders = new UpdateTodoTaskExecutorStatusHeaders();
            updateTodoTaskExecutorStatusHeaders.xAcsDingtalkAccessToken = token;
            UpdateTodoTaskExecutorStatusRequest.UpdateTodoTaskExecutorStatusRequestExecutorStatusList executorStatusList0 = new UpdateTodoTaskExecutorStatusRequest.UpdateTodoTaskExecutorStatusRequestExecutorStatusList()
                    .setId(dingUserUnionId)
                    .setIsDone(true);
            UpdateTodoTaskExecutorStatusRequest updateTodoTaskExecutorStatusRequest = new UpdateTodoTaskExecutorStatusRequest()
                    .setExecutorStatusList(java.util.Arrays.asList(
                            executorStatusList0
                    ));
            try {
                UpdateTodoTaskExecutorStatusResponse rsp= client.updateTodoTaskExecutorStatusWithOptions(dingUserUnionId, dingTodoTaskId, updateTodoTaskExecutorStatusRequest, updateTodoTaskExecutorStatusHeaders, new RuntimeOptions());
                cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
                if(jsonObject!=null){
                    System.out.println("是否更新==================="+jsonObject.get("result"));
//                    return true;
                }

            } catch (TeaException err) {

                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return false;
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public JSONObject sendDingMessage(String userId,String todoId,String content,JSONArray formJson,String isPushType) {
        OrgExternalUser orgExternalUser=dingUserManager.queryExtUserInfoById(userId);//获取钉钉系统用户id
        if(orgExternalUser==null){
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject("{\"errcode\":500,\"errmsg\":\"该用户没有钉钉参数\"}");

            return jsonObject;
        }
        String dingtalkIds="";
        String orgId="";
        String dingToken="";
        String dingAgentId="";
        String userDingUnionId="";//unionId
        String dingCorpId="";//钉钉企业id
        if(orgExternalUser!=null){
            dingtalkIds=orgExternalUser.getExternalUserId();//获取组织钉钉userId
            orgId=orgExternalUser.getOrgId();
            if(orgExternalUser.getExternalUnionId()!=null){
                userDingUnionId=orgExternalUser.getExternalUnionId();//获取组织钉钉unionId
            }
            if(BeanUtils.isEmpty(userDingUnionId)&&BeanUtils.isNotEmpty(dingtalkIds)&&BeanUtils.isNotEmpty(orgId)){
                String  unionJson=getDingUserUnionId(orgId,dingtalkIds);
                if(unionJson!=null){
                    userDingUnionId=unionJson;
                }
            }
        }
        if(BeanUtils.isNotEmpty(orgId)){
            CommonResult<OrgExternalSetting> dingSetting= null;
            try {
                dingSetting = orgExtSettingService.querySettingByCorpId(orgId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(BeanUtils.isNotEmpty(dingSetting)){
                dingAgentId=dingSetting.getValue().getDingAgentId();
                dingCorpId=dingSetting.getValue().getDingCorpId();

            }
        }
        dingToken=this.getDingTokenNew(orgId,"0");

        DingTalkClient client = new DefaultDingTalkClient(DingTalkConsts.getMsgSendUrl());
        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        req.setAgentId(Long.valueOf(dingAgentId));
        req.setUseridList(dingtalkIds);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("oa");
        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText("eip审批");
        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
        msg.getOa().getBody().setContent(content);//待办内容

        if(formJson!=null){
            List<OapiMessageCorpconversationAsyncsendV2Request.Form> fomLists=new ArrayList<>();
            for(int i=0;i<formJson.size();i++){
               Map<String,Object> json= (Map<String, Object>) formJson.get(i);
                OapiMessageCorpconversationAsyncsendV2Request.Form foromEntity=new OapiMessageCorpconversationAsyncsendV2Request.Form();
                foromEntity.setKey(json.get("key").toString());
                foromEntity.setValue(json.get("value").toString());
                fomLists.add(foromEntity);
            }
            msg.getOa().getBody().setForm(fomLists);
        }
        req.setMsg(msg);
        String url = dingPcTodoUrl+"?messageId="+todoId+"&corpId="+dingCorpId;
        String result = url + "&ddtab=true";
        result = "dingtalk://dingtalkclient/page/link?url=" + URLEncoder.encode(result);
        String mobilurl = dingAppTodoUrl+"/home?messageId="+todoId+"&corpId="+dingCorpId;
        if(StringUtil.isNotEmpty(isPushType)){
            if(isPushType.equals("0")){
                msg.getOa().setPcMessageUrl(result);
                msg.getOa().setMessageUrl(mobilurl);
            }
            if(isPushType.equals("1")){
                msg.getOa().setPcMessageUrl(result);
            }
            if(isPushType.equals("2")){
                msg.getOa().setMessageUrl(mobilurl);
            }
        }
        req.setMsg(msg);
        try {
            OapiMessageCorpconversationAsyncsendV2Response rsp1 = client.execute(req, dingToken);
            System.out.println(rsp1.getBody());
            //rsp: {"errcode":0,"task_id":211776512894,"request_id":"6ov1uwi1x0lg"}
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp1.getBody());
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public JSONObject sendDingTodoTask(String userId, String todoId, String title,String isPushType) {
        OrgExternalUser orgExternalUser=dingUserManager.queryExtUserInfoById(userId);//获取钉钉系统用户id
        String dingtalkIds="";
        String orgId="";
        String dingToken="";
        String dingAgentId="";
        String userDingUnionId="";//unionId
        String dingCorpId="";//钉钉企业id
        if(orgExternalUser!=null){
            dingtalkIds=orgExternalUser.getExternalUserId();//获取组织钉钉userId
            orgId=orgExternalUser.getOrgId();
            if(orgExternalUser.getExternalUnionId()!=null){
                userDingUnionId=orgExternalUser.getExternalUnionId();//获取组织钉钉unionId
            }
            if(BeanUtils.isEmpty(userDingUnionId)&&BeanUtils.isNotEmpty(dingtalkIds)&&BeanUtils.isNotEmpty(orgId)){
                String  unionJson=getDingUserUnionId(orgId,dingtalkIds);
                if(unionJson!=null){
                    userDingUnionId=unionJson;
                }
            }
        }
        if(BeanUtils.isNotEmpty(orgId)){
            CommonResult<OrgExternalSetting> dingSetting= null;
            try {
                dingSetting = orgExtSettingService.querySettingByCorpId(orgId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(BeanUtils.isNotEmpty(dingSetting)){
                dingAgentId=dingSetting.getValue().getDingAgentId();
                dingCorpId=dingSetting.getValue().getDingCorpId();

            }
        }
        String jsonTokenOld=getDingTokenNew(orgId,"0");
        if(jsonTokenOld!=null){
            dingToken=jsonTokenOld;
        }
        com.aliyun.dingtalktodo_1_0.Client client = null;
        try {
            client = createClient1();
        } catch (Exception e) {
            e.printStackTrace();
        }
        CreateTodoTaskHeaders createTodoTaskHeaders = new CreateTodoTaskHeaders();
        createTodoTaskHeaders.xAcsDingtalkAccessToken = dingToken;

        String mobilurl = dingAppTodoUrl+"/home?todoId="+todoId+"&corpId="+dingCorpId;
        String url = dingPcTodoUrl+"?todoId="+todoId+"&corpId="+dingCorpId;

        String result = url + "&ddtab=true";
        result = "dingtalk://dingtalkclient/page/link?url=" + URLEncoder.encode(result);
        CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs notifyConfigs = new CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs()
                .setDingNotify("1");
        CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl detailUrl = new CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl();
        if(StringUtil.isNotEmpty(isPushType)){
            if(isPushType.equals("0")){
                detailUrl.setAppUrl(mobilurl);
                detailUrl.setPcUrl(result);
            }
            if(isPushType.equals("1")){
                detailUrl.setAppUrl("");
                detailUrl.setPcUrl(result);
            }
            if(isPushType.equals("2")){
                detailUrl.setAppUrl(mobilurl);
                detailUrl.setPcUrl("");
            }
        }


        CreateTodoTaskRequest createTodoTaskRequest = new CreateTodoTaskRequest()
                .setOperatorId(userDingUnionId)//当前操作者用户的unionId
                .setSourceId(todoId+dingtalkIds)//业务id
                .setSubject(title)//待办标题
                .setCreatorId(userDingUnionId)//创建者的unionId。
				.setDescription("测试待办显示")
//				.setDueTime(1617675000000L)//截止时间
                .setExecutorIds(java.util.Arrays.asList(
                        userDingUnionId
                ))//执行者iunionId
                .setParticipantIds(java.util.Arrays.asList(
                        userDingUnionId
                ))//参与者iunionId
                .setDetailUrl(detailUrl)
                .setIsOnlyShowExecutor(true)//生成的待办是否仅展示在执行者的待办列表中。
                .setPriority(20)//优先级 10=较低 20=普通 30=紧急 40=非常紧急
                .setNotifyConfigs(notifyConfigs);//通知配置，是否发钉

        try {
            CreateTodoTaskResponse resultRsp= client.createTodoTaskWithOptions(userDingUnionId, createTodoTaskRequest, createTodoTaskHeaders, new RuntimeOptions());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(resultRsp.getBody());

            if(jsonObject!=null){
                String dingTodoTaskId= (String) jsonObject.get("id");
                portalFeignService.saveTodoDataEntity(dingTodoTaskId,dingtalkIds,userDingUnionId,todoId,orgId);//保存待办和数据的关联关系
                return jsonObject;
            }

            return jsonObject;
        } catch (TeaException err) {
            err.printStackTrace();

            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            _err.printStackTrace();
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
        return null;
    }

    @Override
    public Map<String, Object> getWelcomeDage(String orgId) {
        return this.baseMapper.getWelcomeDage(orgId);
    }

    @Override
    public JSONObject sendDingMessageByZabbix(String userId, String content) {
        OrgExternalUser orgExternalUser=dingUserManager.queryExtUserInfoById(userId);//获取钉钉系统用户id
        if(orgExternalUser==null){
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject("{\"errcode\":500,\"errmsg\":\"该用户没有钉钉参数\"}");

            return jsonObject;
        }
        String dingtalkIds="";
        String orgId="";
        String dingToken="";
        String dingAgentId="";
        String userDingUnionId="";//unionId
        String dingCorpId="";//钉钉企业id
        if(orgExternalUser!=null){
            dingtalkIds=orgExternalUser.getExternalUserId();//获取组织钉钉userId
            orgId=orgExternalUser.getOrgId();
            if(orgExternalUser.getExternalUnionId()!=null){
                userDingUnionId=orgExternalUser.getExternalUnionId();//获取组织钉钉unionId
            }
            if(BeanUtils.isEmpty(userDingUnionId)&&BeanUtils.isNotEmpty(dingtalkIds)&&BeanUtils.isNotEmpty(orgId)){
                String  unionJson=getDingUserUnionId(orgId,dingtalkIds);
                if(unionJson!=null){
                    userDingUnionId=unionJson;
                }
            }
        }
        if(BeanUtils.isNotEmpty(orgId)){
            CommonResult<OrgExternalSetting> dingSetting= null;
            try {
                dingSetting = orgExtSettingService.querySettingByCorpId(orgId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(BeanUtils.isNotEmpty(dingSetting)){
                dingAgentId=dingSetting.getValue().getDingAgentId();
                dingCorpId=dingSetting.getValue().getDingCorpId();

            }
        }
        dingToken=this.getDingTokenNew(orgId,"0");

        DingTalkClient client = new DefaultDingTalkClient(DingTalkConsts.getMsgSendUrl());
        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        req.setAgentId(Long.valueOf(dingAgentId));
        req.setUseridList(dingtalkIds);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("oa");
        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText("eip审批");
        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
        msg.getOa().getBody().setContent(content);//待办内容

        req.setMsg(msg);
        try {
            OapiMessageCorpconversationAsyncsendV2Response rsp1 = client.execute(req, dingToken);
            System.out.println(rsp1.getBody());
            //rsp: {"errcode":0,"task_id":211776512894,"request_id":"6ov1uwi1x0lg"}
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp1.getBody());
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @description  删除钉钉部门
     * @author  yangzibin
     * @date    2024/1/17 14:27
     * @param	extDeptId
     * @param	orgId
     * @return  java.lang.String
     */
    private String[] deleteDingDeptApi(String extDeptId,String orgId){
        String[] resultArr=new String[3];
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/delete");
        OapiV2DepartmentDeleteRequest req = new OapiV2DepartmentDeleteRequest();
        req.setDeptId(Long.parseLong(extDeptId));
        OapiV2DepartmentDeleteResponse rsp = null;
        try {
            rsp = client.execute(req, getAccessToken(orgId));
            System.out.println(rsp.getBody());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
            int errorCode= (int) jsonObject.get("errcode");
            String errmsg= (String) jsonObject.get("errmsg");
            resultArr[0]=errorCode+"";
            resultArr[1]=errmsg;
            return resultArr;
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return resultArr;
    }

    private boolean getOrgSynDir(String orgId){
        Org orgIndex=orgDao.get(orgId);
        String type=orgIndex.getJoinExtSystemType();
        if(StringUtil.isEmpty(type)){
            return false;
        }
        String dir=orgIndex.getJoinExtSystemSyndir();
        if(StringUtil.isEmpty(dir)){
            return false;
        }
        if(dir.equals(Org.ORG_SYN_DIR_1)){//钉钉-》中台，开启推送接收
            return true;
        }
        return false;
    }

    /**
     * @description  处理通讯录事件
     * @author  yangzibin
     * @date    2024/1/10 9:42
     * @param	bizData
     * @param	eventType
     * @return  void
     */
    private synchronized void productData(String orgId,String tenantId,shade.com.alibaba.fastjson2.JSONObject bizData,String eventType){
        System.out.println(eventType);
        System.out.println(bizData);
        if(StringUtil.isNotEmpty(eventType)){
            if(eventType.equals("user_add_org")){//新增
                disposeDingUser(orgId,tenantId,bizData,"0");
            }else if(eventType.equals("user_modify_org")){//修改
                disposeDingUser(orgId,tenantId,bizData,"1");
            }else if(eventType.equals("user_leave_org")){//离职
                disposeDingUser(orgId,tenantId,bizData,"2");
            }else if(eventType.equals("user_active_org")){//新用户激活
                disposeDingUser(orgId,tenantId,bizData,"3");
            }else if(eventType.equals("org_dept_create")){//部门新增
                disposeDingDept(orgId,bizData,"0");
            }else if(eventType.equals("org_dept_modify")){//部门修改
                disposeDingDept(orgId,bizData,"1");
            }else if(eventType.equals("org_dept_remove")){//部门删除
                disposeDingDept(orgId,bizData,"2");
            }
        }
    }
    /**
     * @description  处理钉钉推送的用户事件
     * @author  yangzibin
     * @date    2024/1/10 10:04
     * @param
     * @return  void
     */
    private void disposeDingUser(String orgId,String tenantId,shade.com.alibaba.fastjson2.JSONObject bizData,String type){
        shade.com.alibaba.fastjson2.JSONArray jsonArray=null;
        if(bizData.get("userId")==null){
            jsonArray=bizData.getJSONArray("UserId");
        }else{
            jsonArray= bizData.getJSONArray("userId");
        }
        List<String> userIdList=new ArrayList<>();
        jsonArray.stream().forEach(item->{
            userIdList.add(item.toString());
        });

        userIdList.stream().forEach(item->{
            cn.hutool.json.JSONObject jsonResult= getDingUserInfo(item,orgId);
            if(jsonResult!=null){
                if(type.equals("0")||type.equals("1")||type.equals("3")){//用户新增和编辑
                    String mobile=(String) jsonResult.get("mobile");
                    OrgExternalUser orgExtUser=new OrgExternalUser();
                    orgExtUser.setExternalUserId(item);
                    orgExtUser.setExternalUserName((String) jsonResult.get("name"));
                    orgExtUser.setExternalMobile(mobile);
                    orgExtUser.setExternalJobNumber((String) jsonResult.get("job_number"));
                    orgExtUser.setExternalPost((String) jsonResult.get("title"));
                    orgExtUser.setOrgId(orgId);
                    orgExtUser.setType(Constant.EXTERNAL_DING_FLAG);
                    orgExtUser.setDingDelete(Constant.DING_DATA_STATUS_0);

                    //1.更新用户信息
                    LambdaQueryWrapper<OrgExternalUser> userQw=new LambdaQueryWrapper<>();
                    userQw.eq(OrgExternalUser::getExternalMobile,mobile);//手机号判断唯一
                    userQw.eq(OrgExternalUser::getOrgId,orgId);
                    List<OrgExternalUser> extUserList=dingUserDao.selectList(userQw);
                    if(extUserList.size()>0){//存在更新
                        orgExtUser.setId(extUserList.get(0).getId());
                        orgExtUser.setTenantId(extUserList.get(0).getTenantId());
                        dingUserManager.update(orgExtUser);
                    }else{
//                        orgExtUser.setTenantId(tenantId);
                        dingUserManager.saveOrUpdate(orgExtUser);
                    }
                    List<CommonResult<String>> resultList=new ArrayList<>();
                    orgExtUser.setTenantId(tenantId);
                    resultList.add(dingUserManager.dingToSystemUser(orgId,orgExtUser));
                    //2.更新用户信息关联表
                    JSONArray deptIdList=jsonResult.getJSONArray("dept_id_list");//用户所属部门
                    //先删除所有的此用户的关联关系
                    deleteDingUserDept(orgExtUser);
                    deptIdList.stream().forEach(itemDept->{
                        addDingUserDept(item,itemDept.toString(),orgId);
                    });
                    //记录日志
                    extOrgLogManager.saveSynExtOrgLog(resultList,orgId,Org.ORG_SYN_TYPE_1,Org.ORG_SYN_DIR_1,"1");
                }
            }
            if(type.equals("2")){//删除
                OrgExternalUser user= deleteDingUser(item,orgId);
                deleteSystemUser(item,orgId);
                List<CommonResult<String>> resultList=new ArrayList<>();
                CommonResult<String> result = new CommonResult<String>(true,user.getExternalUserName()+"用户删除成功",user.getExternalUserName()+"用户删除成功");
                resultList.add(result);
                extOrgLogManager.saveSynExtOrgLog(resultList,orgId,Org.ORG_SYN_TYPE_1,Org.ORG_SYN_DIR_1,"1");
            }

        });

    }
    /**
     * @description  批量更新删除钉钉用户标记
     * @author  yangzibin
     * @date    2024/1/11 14:46
     * @param	dingUserId
     * @param	orgId
     * @return  void
     */
    private OrgExternalUser deleteDingUser(String dingUserId,String orgId){
        LambdaQueryWrapper<OrgExternalUser> dingUserQw=new LambdaQueryWrapper<>();
        dingUserQw.eq(OrgExternalUser::getExternalUserId,dingUserId);
        dingUserQw.eq(OrgExternalUser::getOrgId,orgId);
        List<OrgExternalUser> dingUserList= dingUserDao.selectList(dingUserQw);
        if(dingUserList.size()>0){
            dingUserList.stream().forEach(item->{
                item.setDingDelete(Constant.DING_DATA_STATUS_1);
                dingUserManager.saveOrUpdate(item);
                deleteDingUserDept(item);
            });
            return dingUserList.get(0);
        }
        return null;
    }
    /**
     * @description   批量更新删除系统用户标记
     * @author  yangzibin
     * @date    2024/1/11 14:47
     * @param	dingUserId
     * @param	orgId
     * @return  void
     */
    private void deleteSystemUser(String dingUserId,String orgId){
        LambdaQueryWrapper<OrgExternalUser> dingUserQw=new LambdaQueryWrapper<>();
        dingUserQw.eq(OrgExternalUser::getExternalUserId,dingUserId);
        dingUserQw.eq(OrgExternalUser::getOrgId,orgId);
        List<OrgExternalUser> dingUserList= dingUserDao.selectList(dingUserQw);
        if(dingUserList.size()>0){
            List<String> userIdList=dingUserList.stream().filter(e->e.getUserId()!=null).map(e->e.getUserId()).collect(Collectors.toList());
            if(userIdList.size()>0){
                userManager.removeByIds(userIdList);
            }
        }
    }

    /**
     * @description  删除DingUserDept关联关系
     * @author  yangzibin
     * @date    2024/1/11 14:32
     * @param	orgExtUser
     * @return  void
     */
    private void deleteDingUserDept(OrgExternalUser orgExtUser){
        LambdaQueryWrapper<OrgExternalUserDept> orgExtUserDeptLam=new LambdaQueryWrapper<>();
        orgExtUserDeptLam.eq(OrgExternalUserDept::getExternalUserId,orgExtUser.getExternalUserId());
        orgExtUserDeptLam.eq(OrgExternalUserDept::getOrgId,orgExtUser.getOrgId());
        List<OrgExternalUserDept>  extUserDeptList=dingUserDeptDao.selectList(orgExtUserDeptLam);
        if(extUserDeptList.size()>0){
            List<String> idList=extUserDeptList.stream().map(e->e.getId()).collect(Collectors.toList());
            this.dingUserDeptManager.removeByIds(idList);
        }
    }

    /**
     * @description 钉钉事件推送部门处理，部门编辑不做修改，如修改还需要修改所有下级
     * @author  yangzibin
     * @date    2024/1/10 11:22
     * @param	orgId
     * @param	bizData
     * @param	type
     * @return  void
     */
    private void disposeDingDept(String orgId,shade.com.alibaba.fastjson2.JSONObject bizData,String type){
        shade.com.alibaba.fastjson2.JSONArray jsonArray=null;
        if(bizData.get("deptId")==null){
            jsonArray=bizData.getJSONArray("DeptId");
        }else{
            jsonArray= bizData.getJSONArray("deptId");
        }
        List<String> deptIdList=new ArrayList<>();
        jsonArray.stream().forEach(item->{
            deptIdList.add(item.toString());
        });

        deptIdList.stream().forEach(item->{
            if(type.equals("0")||type.equals("1")){//新增和编辑
                LambdaQueryWrapper<OrgExternalDept> extDeptQw=new LambdaQueryWrapper<>();
                extDeptQw.eq(OrgExternalDept::getExternalDeptId,item);
                extDeptQw.eq(OrgExternalDept::getOrgId,orgId);
                List<OrgExternalDept> extDeptList=this.baseMapper.selectList(extDeptQw);
                cn.hutool.json.JSONObject dingDeptInfo=getDingDeptInfo(item,orgId);
                OrgExternalDept externalDeptTemp=null;
                if(extDeptList!=null&&extDeptList.size()>0){
                    externalDeptTemp=extDeptList.get(0);
                    String tempPathName=externalDeptTemp.getPathName().substring(0,externalDeptTemp.getPathName().lastIndexOf("/")+1);
                    externalDeptTemp.setPathName(tempPathName+(String) dingDeptInfo.get("name"));
                }else{
                    externalDeptTemp=new OrgExternalDept();
                    externalDeptTemp.setOrgId(orgId);
                    externalDeptTemp.setType(Constant.EXTERNAL_DING_FLAG);
                    externalDeptTemp.setDingDelete(Constant.DING_DATA_STATUS_0);
                    externalDeptTemp.setExternalDeptId(item);
                    externalDeptTemp.setCreateTime(LocalDateTime.now());
                    if((int) dingDeptInfo.get("parent_id")==1){
                        externalDeptTemp.setPathName("/"+(String) dingDeptInfo.get("name"));
                    }else{
                        LambdaQueryWrapper<OrgExternalDept> orgExtDeptQw=new LambdaQueryWrapper<>();
                        orgExtDeptQw.eq(OrgExternalDept::getExternalDeptId,(int) dingDeptInfo.get("parent_id")+"");
                        List<OrgExternalDept> orgExtDept=this.baseMapper.selectList(orgExtDeptQw);
                        if(orgExtDept.size()>0){
                            externalDeptTemp.setPathName(orgExtDept.get(0).getPathName()+"/"+(String) dingDeptInfo.get("name"));
                        }
                    }
                    externalDeptTemp.setExternalParentId((int) dingDeptInfo.get("parent_id")+"");
                }
                externalDeptTemp.setExternalName((String) dingDeptInfo.get("name"));
                this.saveOrUpdate(externalDeptTemp);
                updateOrgDept(externalDeptTemp);
                //记录日志
                List<CommonResult<String>> resultList=new ArrayList<>();
                String flagStr="";
                if(type.equals("0")){
                    flagStr="新增";
                }else if(type.equals("1")){
                    flagStr="编辑";
                }
                CommonResult<String> result = new CommonResult<String>(true,externalDeptTemp.getExternalName()+"部门"+flagStr+"成功",externalDeptTemp.getExternalName()+"部门"+flagStr+"成功");
                resultList.add(result);
                extOrgLogManager.saveSynExtOrgLog(resultList,orgId,Org.ORG_SYN_TYPE_1,Org.ORG_SYN_DIR_1,"0");
            }else if(type.equals("2")){//删除
                LambdaQueryWrapper<OrgExternalDept> extDeptQw=new LambdaQueryWrapper<>();
                extDeptQw.eq(OrgExternalDept::getExternalDeptId,item);
                extDeptQw.eq(OrgExternalDept::getOrgId,orgId);
                List<OrgExternalDept> extDeptList=this.baseMapper.selectList(extDeptQw);
                if(extDeptList.size()>0){
                    OrgExternalDept entity= extDeptList.get(0);
                    entity.setDingDelete(Constant.DING_DATA_STATUS_1);//更新删除标记
                    this.saveOrUpdate(entity);
                    deleteOrg(entity);

                    //记录日志
                    List<CommonResult<String>> resultList=new ArrayList<>();
                    String flagStr="删除";
                    CommonResult<String> result = new CommonResult<String>(true,entity.getExternalName()+"部门"+flagStr+"成功",entity.getExternalName()+"部门"+flagStr+"成功");
                    resultList.add(result);
                    extOrgLogManager.saveSynExtOrgLog(resultList,orgId,Org.ORG_SYN_TYPE_1,Org.ORG_SYN_DIR_1,"0");
                }
            }
        });
    }
    /**
     * @description 钉钉部门更新，同时更新系统中的部门
     * @author  yangzibin
     * @date    2024/1/11 10:40
     * @param	externalDeptTemp
     * @return  void
     */
    private void updateOrgDept(OrgExternalDept externalDeptTemp){
        if(externalDeptTemp.getDeptId()!=null){//已经关联了
            Org orgIndex=orgDao.get(externalDeptTemp.getOrgId());
            Org org= orgDao.get(externalDeptTemp.getDeptId());
            org.setName(externalDeptTemp.getExternalName());
            org.setPathName(orgIndex.getPathName()+externalDeptTemp.getPathName());
            orgManager.saveOrUpdate(org);
        }else{
            releDingToSystemDept(externalDeptTemp.getOrgId(),externalDeptTemp.getExternalDeptId());
        }
    }
    /**
     * @description  钉钉删除部门，同步修改系统部门删除标记
     * @author  yangzibin
     * @date    2024/1/11 9:55
     * @param
     * @return  void
     */
    private void deleteOrg( OrgExternalDept entity){
        Org orgIndex=orgDao.get(entity.getOrgId());
        LambdaQueryWrapper<Org> qwOrg=new LambdaQueryWrapper<>();
        qwOrg.eq(Org::getId,entity.getDeptId());
        qwOrg.like(Org::getPathName,orgIndex.getPathName()+entity.getPathName());
        List<Org>  orgList=orgDao.selectList(qwOrg);
        if(orgList.size()>0){
            List<String>  idsList=orgList.stream().map(e->e.getId()).collect(Collectors.toList());
            orgManager.removeByIds(idsList);
        }

    }

    /**
     * @description  获取钉钉部门详情
     * @author  yangzibin
     * @date    2024/1/10 10:45
     * @param	dingDeptId
     * @return  cn.hutool.json.JSONObject
     */
    private cn.hutool.json.JSONObject getDingDeptInfo(String dingDeptId,String orgId){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.setDeptId(Long.parseLong(dingDeptId));
            req.setLanguage("zh_CN");
            OapiV2DepartmentGetResponse rsp = rsp = client.execute(req, getAccessToken(orgId));
            System.out.println(rsp.getBody());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
            int errorCode= (int) jsonObject.get("errcode");
            if(errorCode==0){
                cn.hutool.json.JSONObject jsonResult= (JSONObject) jsonObject.get("result");
                return jsonResult;
            }
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

}
