package com.hotent.uc.manager.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.FieldRelation;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.PinyinUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.uc.dao.*;
import com.hotent.uc.manager.*;
import com.hotent.uc.model.*;
import com.hotent.uc.params.org.OrgVo;
import com.hotent.uc.params.user.UserVo;
import com.hotent.uc.util.Constant;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

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

    @Value("${dingSetting.appkey}")
    private String clientId;//钉钉应用key
    @Value("${dingSetting.appSecret}")
    private String appSecret;//钉钉应用密钥

    @Autowired
    private com.hotent.uc.dao.UserDao userDao;
    @Autowired
    private OrgManager orgManager;
    @Autowired
    private DIngUserDeptDao dingUserDeptDao;
    @Autowired
    private DIngApiDao dingApiDao;
    @Autowired
    private DIngUserDao dingUserDao;
    @Autowired
    private UserManager userManager;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    PwdStrategyManager pwdStrategyManager;
    @Autowired
    private OrgUserManager orgUserManager;
    @Autowired
    private OrgUserDao orgUserDao;
    @Autowired
    private DingUserManager dingUserManager;
    @Autowired
    private DingUserDeptManager dingUserDeptManager;
    @Autowired
    private OrgDao orgDao;
    @Autowired
    private OrgExternalSettingManager orgExternalSettingManager;
    @Autowired
    private OrgJobManager orgJobService;
    @Autowired
    private OrgPostManager orgPostManager;
    @Autowired
    UserRoleManager userRoleManager;
    @Autowired
    RoleManager roleManager;
    @Override
    public CommonResult<String> dingToSystemUser(String orgId,OrgExternalUser orgExternalUser) {
        //同步钉钉中间表数据到系统中
        //1.查询系统中当前组织是否有对应的用户

        String extMobile=orgExternalUser.getExternalMobile();
        QueryWrapper<User> qwOrgUser=new QueryWrapper<>();
        if(StringUtil.isEmpty(extMobile)){
            return new CommonResult<String>(true, "钉钉用户"+orgExternalUser.getExternalUserName()+"没有手机号码", "");
        }
//        Wrapper<User> wrapper =new
        qwOrgUser.eq("MOBILE_",extMobile);
//        qwOrgUser.eq(User::getIsDelete,User.DELETE_NO);
        User user=userDao.queryOrgUserALl(qwOrgUser);
        boolean flag=false;
        //查询是否有部门
        List<String> orgIdList=new ArrayList<>();
        LambdaQueryWrapper<OrgExternalUserDept> orgExtUserDeptQw=new LambdaQueryWrapper<>();
        orgExtUserDeptQw.eq(OrgExternalUserDept::getExternalUserId,orgExternalUser.getExternalUserId());
        List<OrgExternalUserDept> extUserDept=dingUserDeptDao.selectList(orgExtUserDeptQw);
        if(extUserDept!=null&&extUserDept.size()>0){//查询部门关联
            LambdaQueryWrapper<OrgExternalDept> orgExtDeptQw=new LambdaQueryWrapper<>();
            orgExtDeptQw.in(OrgExternalDept::getExternalDeptId,extUserDept.stream().map(e->e.getExternaldDeptId()).collect(Collectors.toList()));
            List<OrgExternalDept> orgExternalDeptEntity=dingApiDao.selectList(orgExtDeptQw);
            if(orgExternalDeptEntity!=null&&orgExternalDeptEntity.size()>0){
                orgIdList=orgExternalDeptEntity.stream().map(e->e.getDeptId()).collect(Collectors.toList());//获取关联系统部门id
            }
        }else{
            orgIdList.add(orgId);
        }
        if(user!=null){//有对应用户，更新基本信息
            user.setFullname(orgExternalUser.getExternalUserName());//修改姓名
            if(orgExternalUser.getDingDelete().equals(Constant.DING_DATA_STATUS_1)){//如果是删除得删除用户
                userManager.removeByIds(user.getId());
            }else{
                user.setIsDelete(User.DELETE_NO);
                userDao.updateUser(user);
            }
            orgExternalUser.setUserId(user.getId());//更新钉钉用户表，添加关联系统用户id
            dingUserManager.saveOrUpdate(orgExternalUser);
            if(StringUtil.isNotEmpty(orgExternalUser.getExternalPost())){
                savaPostJob(orgExternalUser);//处理岗位数据
            }
            //保存用户部门关系
            orgIdList.stream().forEach(item->{
                if(!isOrgUserEff(item,user.getId())){
                    OrgUser orgUser=new OrgUser();
                    orgUser.setIsMaster(1);
                    orgUser.setOrgId(item);
                    orgUser.setIsCharge(0);
                    orgUser.setUserId(user.getId());
                    orgUser.setIsRelActive(1);
//            orgUser.setRelId();
                    orgUser.setIsDelete(Constant.DING_DATA_STATUS_0);
                    orgUser.setCreateTime(LocalDateTime.now());
                    orgUserManager.saveOrUpdate(orgUser);
                }

            });

            return new CommonResult<String>(true, "钉钉用户"+orgExternalUser.getExternalUserName()+"向中台更新", "钉钉用户"+orgExternalUser.getExternalUserName()+"向中台更新");
        }else{//2.没有此用户进行新增创建
//            orgIdList.add(orgId);
            addNewDingUser(orgExternalUser,orgIdList);
            flag=true;
            return new CommonResult<String>(true, "钉钉用户"+orgExternalUser.getExternalUserName()+"向中台新增", "钉钉用户"+orgExternalUser.getExternalUserName()+"向中台新增");
        }
//        return new CommonResult<String>(true, "完成钉钉用户"+orgExternalUser.getExternalUserName()+"向中台同步关联！状态："+flag, "");
    }
    /**
     * @description  钉钉导入以后处理钉钉职位数据
     * @author  yangzibin
     * @date    2024/8/1 15:47
     * @param	extUser
     * @return  void
     */
    private void savaPostJob(OrgExternalUser extUser){
        //处理职务数据
        List<OrgJob> databaseJobs = orgJobService.getAll();//获取所有职务
        List<String> jobNameList = new ArrayList<>(Arrays.asList(extUser.getExternalPost().split("、")));

        for(int i=0;i<jobNameList.size();i++){
            String jobNameDing=jobNameList.get(i);
            OrgJob orgJob=databaseJobs.stream().filter(s->s.getName().equals(jobNameDing)).findFirst().orElse(null);
            if(orgJob==null){//没有此职务，进行新增职务
                orgJob = new OrgJob();
                orgJob.setId(UniqueIdUtil.getSuid());
                String code = PinyinUtil.getPinYinHeadChar(jobNameDing);
                int count = orgJobService.getCountByCode(code);
                if(count>0){//处理逻辑删除的数据
                    code=code+"_"+orgJob.getId().substring(orgJob.getId().length()-3);
                }
                orgJob.setCode(code);
                orgJob.setName(jobNameDing);
                orgJobService.save(orgJob);
            }

            //处理岗位数据
            String relId = UniqueIdUtil.getSuid();
            String relCode = PinyinUtil.getPinYinHeadChar(jobNameDing);
            String jobCode = orgJob.getCode();
            Org org=orgManager.get(extUser.getOrgId());

            LambdaQueryWrapper<OrgExternalUserDept> orgUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
            orgUserLambdaQueryWrapper.eq(OrgExternalUserDept::getExternalUserId,extUser.getExternalUserId());
            List<OrgExternalUserDept> list=dingUserDeptDao.selectList(orgUserLambdaQueryWrapper);
            String orgId=org.getId();

            if(list.size()>0){
                LambdaQueryWrapper<OrgExternalDept> orgExternalDeptLambdaQueryWrapper=new LambdaQueryWrapper<>();
                orgExternalDeptLambdaQueryWrapper.eq(OrgExternalDept::getExternalDeptId,list.get(0).getExternaldDeptId());
                List<OrgExternalDept> listExtDept=dingApiDao.selectList(orgExternalDeptLambdaQueryWrapper);
                if(listExtDept.size()>0){
                    Org orgDept=orgDao.get(listExtDept.get(0).getDeptId());
                    if(orgDept!=null){
                        org=orgDept;
                        orgId=orgDept.getId();
                    }

                }
            }

            String postCode = org.getCode()+"_"+jobCode+"_"+relCode;//职务编码+组织编码+名称拼音首字母
            List<OrgPost> databasePost=  orgPostManager.getAll();//获取所有的岗位
            OrgPost orgPost=databasePost.stream().filter(s->s.getCode().equals(postCode)).findFirst().orElse(null);
            if(orgPost==null){//新建岗位
                orgPost=new OrgPost();
                orgPost.setId(relId);
                int count=orgPostManager.getCountByCode(postCode);
                String tempPost=postCode;
                if(count>0){//有删除标记的数据
                    tempPost=postCode+"_"+orgPost.getId().substring(orgPost.getId().length()-3);
                }
                orgPost.setRelDefId(orgJob.getId());
                orgPost.setOrgId(orgId);
                orgPost.setCode(tempPost);
                orgPost.setName(jobNameDing);
                orgPostManager.save(orgPost);
            }
            //处理添加用户和岗位的关联数据
            OrgUser orgUser = new OrgUser();
            QueryFilter filter = QueryFilter.build();
            //filter.setClazz(OrgUser.class);
            filter.addFilter("orgId", orgId, QueryOP.EQUAL, FieldRelation.AND);
            filter.addFilter("userId", extUser.getUserId(), QueryOP.EQUAL,FieldRelation.AND);
            filter.addFilter("relId", orgPost.getId(), QueryOP.EQUAL,FieldRelation.AND);
            //查询用户在该组织下，是否已存在该岗位。
            List<OrgUser> sysOrgUserList =  orgUserManager.query(filter).getRows();
            if(BeanUtils.isEmpty(sysOrgUserList)){//不存在则添组织岗位信息
                orgUser.setId(UniqueIdUtil.getSuid());
                orgUser.setOrgId(orgId);//组织id
                orgUser.setRelId(orgPost.getId());//岗位编号
                orgUser.setUserId(extUser.getUserId());
                if(i==0){
                    orgUser.setIsMaster(1);
                }
                orgUserManager.save(orgUser);
            }
        }

    }

    @Override
    public CommonResult<String> systemToDingUser(String orgId, User user) {
        try {
           if(user.getMobile()==null){
               return new CommonResult<String>(false, "该用户没有手机号无法同步到钉钉", "");
           }
           if(queryDingUser(user,orgId)){//不存在进行创建
              String[] resultArr=addDingUser(user,orgId);
              if(resultArr!=null){
                  if(resultArr[0].equals("0")){
                      addExtUserAndDept(orgId,resultArr[1],user);
                      return new CommonResult<String>(true, user.getFullname()+resultArr[2], user.getFullname()+resultArr[2]);
                  }else{
                      if(resultArr[0].equals("60104")){//已经存在的钉钉，获取userid保存
                          if(user.getMobile()!=null){
                             String dingUserid= getDingUserIdByMobile(user.getMobile(),orgId);
                              addExtUserAndDept(orgId,dingUserid,user);
                          }
                      }else{//不存在的邀请
                          addExtUserAndDept(orgId,"",user);
                      }
                      return new CommonResult<String>(false, user.getFullname()+"-"+resultArr[1], user.getFullname()+"-"+resultArr[1]);
                  }
              }else{
                  return new CommonResult<String>(false, user.getFullname()+"钉钉api创建用户异常", user.getFullname()+"钉钉api创建用户异常");
              }
           }else{//存在进行更新
               updateDingUser(user,orgId);
               return new CommonResult<String>(false, user.getFullname()+"更新用户数据", user.getFullname()+"更新用户数据");
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult<String>(false, "同步失败", "");
    }

    @Override
    public IPage<List<Map<String, Object>>> queryUserComplex(Page page,String type,String userName,String mobile,String orgId,String deptId) {
        Org org=orgDao.get(orgId);
        if(org.getJoinExtSystemType()!=null&&org.getJoinExtSystemType().equals(Org.ORG_SYN_TYPE_1)){//钉钉集成
            if(org.getJoinExtSystemSyndir()!=null&&org.getJoinExtSystemSyndir().equals(Org.ORG_SYN_DIR_0)){//中台-》钉钉
                return  this.baseMapper.queryUserComplexSystemToDing(page,userName,mobile,orgId,deptId,type);
            }
            if(org.getJoinExtSystemSyndir()!=null&&org.getJoinExtSystemSyndir().equals(Org.ORG_SYN_DIR_1)){//钉钉-》中台
                return  this.baseMapper.queryUserComplexDingToSystem(page,userName,mobile,orgId,deptId,type);
            }
        }

        return null;
    }

    @Override
    public Map<String, Object> queryExtUserInfo(String extUserId, String orgId) {
              if(StringUtil.isNotEmpty(orgId)){
                  return this.baseMapper.queryExtUserInfo(extUserId,orgId);
              }else{
                  return this.baseMapper.queryExtUserInfoSystem(extUserId);
              }
    }

    @Override
    public OrgExternalUser queryExtUserInfoById(String userId) {
        LambdaQueryWrapper<OrgExternalUser> qw=new LambdaQueryWrapper<>();
        qw.eq(OrgExternalUser::getUserId,userId);
       List<OrgExternalUser> userList= this.baseMapper.selectList(qw);
        if(userList.size()>0){
            return userList.get(0);
        }
        return null;
    }

    @Override
    public void addExtUserInfo(UserVo userVo) {
        LambdaQueryWrapper<OrgExternalUser> extUserQw=new LambdaQueryWrapper<>();
        extUserQw.eq(OrgExternalUser::getUserId,userVo.getId());
        OrgExternalUser userEnt=this.baseMapper.selectOne(extUserQw);
        if(userEnt==null){
            userEnt=new OrgExternalUser();
        }
        userEnt.setDingDelete("0");
        userEnt.setCreateTime(LocalDateTime.now());
        userEnt.setExternalMobile(userVo.getMobile());
        userEnt.setExternalUserName(userVo.getFullname());
        userEnt.setUserId(userVo.getId());
        userEnt.setType("3");
        userEnt.setOrgId(userVo.getOrgId());
        this.saveOrUpdate(userEnt);
    }

    /**
     * @description  通过手机号查询企业钉钉用户id
     * @author  yangzibin
     * @date    2024/1/11 16:36
     * @param	mobile
     * @param	orgId
     * @return  void
     */
    private  String  getDingUserIdByMobile(String mobile,String orgId){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, getAccessToken(orgId));
            System.out.println(rsp.getBody());
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
           int errcode= (int) jsonObject.get("errcode");
           if(errcode==0){
               cn.hutool.json.JSONObject result= new cn.hutool.json.JSONObject(jsonObject.get("result"));
               String userid= (String) result.get("userid");
             return  userid;
           }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void addExtUserAndDept(String orgId,String dingUserId, User user){
        //保存新增钉钉用户数据到中台
        LambdaQueryWrapper<OrgExternalUser> extUserLam=new LambdaQueryWrapper<>();
        extUserLam.eq(OrgExternalUser::getExternalMobile,user.getMobile());
        extUserLam.eq(OrgExternalUser::getOrgId,orgId);
        List<OrgExternalUser> extUserList= dingUserDao.selectList(extUserLam);
        OrgExternalUser dingUser=null;
        if(extUserList.size()>0){
            dingUser=extUserList.get(0);
            dingUser.setUpdateTime(LocalDateTime.now());
        }else{
            dingUser=new OrgExternalUser();
            dingUser.setCreateTime(LocalDateTime.now());
        }
        dingUser.setUserId(user.getId());
        dingUser.setType(Constant.EXTERNAL_DING_FLAG);
        dingUser.setOrgId(orgId);
        dingUser.setExternalJobNumber(user.getUserNumber());
        dingUser.setExternalUserId(dingUserId);
        dingUser.setExternalUserName(user.getFullname());
        dingUser.setExternalMobile(user.getMobile());
        dingUser.setDingDelete(Constant.DING_DATA_STATUS_0);
        dingUserManager.saveOrUpdate(dingUser);
        //保存新增钉钉用户和钉钉组织关联关系到中台
        if(StringUtil.isNotEmpty(dingUserId)){
            OrgExternalUserDept orgExternalUserDept=new OrgExternalUserDept();
            orgExternalUserDept.setOrgId(orgId);
            orgExternalUserDept.setExternalUserId(dingUserId);
            orgExternalUserDept.setExternaldDeptId("1");//根节点
            orgExternalUserDept.setCreateTime(LocalDateTime.now());
            dingUserDeptManager.saveOrUpdate(orgExternalUserDept);
        }

    }
    private boolean queryDingUser(User user,String orgId){
        LambdaQueryWrapper<OrgExternalUser> extUserQw=new LambdaQueryWrapper<>();
//        extUserQw.eq(OrgExternalUser::getExternalMobile,user.getMobile());
        extUserQw.eq(OrgExternalUser::getOrgId,orgId);
        extUserQw.eq(OrgExternalUser::getUserId,user.getId());
        OrgExternalUser orgExtUser=dingUserDao.selectOne(extUserQw);
        if(orgExtUser!=null){//存在用户，不进行创建
            if((orgExtUser.getExternalUserId()==null||orgExtUser.getExternalUserId().equals(""))){
                return true;
            }else{
                return false;
            }
        }
        return true;
    }

    private String[] addDingUser(User user,String orgId){
//        {
//            "errcode":"0",
//                "result":{
//            "unionId":"xxxx",
//                    "userid":"zhangsan"
//        },
//            "errmsg":"ok"
//        }
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/create");
            OapiV2UserCreateRequest req = new OapiV2UserCreateRequest();
            req.setUserid(user.getId());//用户id
            req.setName(user.getFullname());//姓名
            req.setMobile(user.getMobile());//手机号
//            req.setTitle(user.getp);//职位
            req.setDeptIdList("1");//所属部门 1=根节点
            req.setJobNumber(user.getUserNumber());//工号
//            req.setRemark("备注备注");//备注
            OapiV2UserCreateResponse rsp = client.execute(req, getAccessToken(orgId));
            cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
            System.out.println(rsp.getBody());
            int  errcode= (int) jsonObject.get("errcode");
            String[] resultArr=new String[2];
            resultArr[0]=errcode+"";
            if(errcode==0){
                cn.hutool.json.JSONObject result= new cn.hutool.json.JSONObject(jsonObject.get("result"));
                String userid= (String) result.get("userid");
                resultArr[1]=userid+"";
                resultArr[2]=(String) jsonObject.get("errmsg")+"";
            }else{
               String errmsg= (String) jsonObject.get("errmsg");
                resultArr[1]=errmsg+"";
            }
            return resultArr;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * @description  更新钉钉用户数据
     * @author  yangzibin
     * @date    2024/1/9 18:08
     * @param	user
     * @return  void
     */
    private CommonResult<String>  updateDingUser(User user,String orgId){
        LambdaQueryWrapper<OrgExternalUser> qw=new LambdaQueryWrapper<>();
        qw.eq(OrgExternalUser::getUserId,user.getId());
        qw.eq(OrgExternalUser::getOrgId,orgId);
        OrgExternalUser extUser=dingUserDao.selectOne(qw);
        if(extUser!=null&&extUser.getExternalUserId()==null){
            return new CommonResult<String>(false, "用户"+user.getFullname()+"没有关联钉钉id无法更新钉钉用户信息", "");
        }
        if(extUser!=null){
            try {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/update");
                OapiV2UserCreateRequest req = new OapiV2UserCreateRequest();
                req.setUserid(extUser.getExternalUserId());//用户id
                req.setName(user.getFullname());//姓名
                req.setMobile(user.getMobile());//手机号
                req.setDeptIdList("1");//所属部门 1=根节点
                req.setJobNumber(user.getUserNumber());//工号
                OapiV2UserCreateResponse rsp = client.execute(req, getAccessToken(orgId));
                System.out.println(rsp.getBody());
                cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
                int errcode= (int) jsonObject.get("errcode");
                if(errcode==0){
                    return new CommonResult<String>(true, "用户"+user.getFullname()+"更新钉钉用户数据成功", "");
                }
                return new CommonResult<String>(false, "用户"+user.getFullname()+"更新钉钉用户数据失败", "");
            } catch (ApiException e) {
                e.printStackTrace();
            }
        }
        return new CommonResult<String>(false, "用户"+user.getFullname()+"更新钉钉用户数据失败", "");
    }
    /**
     * @description  用户id和组织id关系是否已经记录
     * @author  yangzibin
     * @date    2024/3/15 14:41
     * @param
     * @return  void
     */
    private boolean isOrgUserEff(String orgId,String userId){
        List<OrgUser>  orgUserList=orgUserManager.getListByOrgIdUserId(orgId,userId);
        if(orgUserList.size()>0){
            return true;
        }
        return false;
    }

    /**
     * @description  添加用户
     * @author  yangzibin
     * @date    2024/1/9 10:25
     * @param	orgExternalUser
     * @return  void
     */
    private void addNewDingUser(OrgExternalUser orgExternalUser,List<String> orgIdList){
        try {
            //保存用户

            User user=new User();
            String userId= UniqueIdUtil.getSuid();
            user.setId(userId);
            user.setFullname(orgExternalUser.getExternalUserName());
            user.setAccount(orgExternalUser.getExternalMobile());
            user.setMobile(orgExternalUser.getExternalMobile());

            String password="";//密码姓名拼音首字母+@+手机号后六位
            String phoneStr=user.getMobile().substring(user.getMobile().length()-5,user.getMobile().length());
            String szm= PinyinUtil.getPinYinHeadChar(user.getFullname());
            password = szm+"@"+phoneStr;
            user.setPassword(passwordEncoder.encode(password));
            user.setStatus(User.STATUS_NORMAL);
            String jobNumber=orgExternalUser.getExternalJobNumber();
            if(StringUtil.isEmpty(jobNumber)){
                jobNumber=orgExternalUser.getExternalMobile().substring(orgExternalUser.getExternalMobile().length()-6,orgExternalUser.getExternalMobile().length());
            }
            user.setUserNumber(jobNumber);
            System.out.println("添加用户："+user.getFullname());
            userManager.saveOrUpdate(user);
            //添加角色
            Role role = roleManager.getByAlias("ybyh");
            String roleId = "1";
            if(BeanUtils.isNotEmpty(role)){
                roleId = role.getId();
            }
            UserRole userRole = new UserRole();
            userRole.setId(UniqueIdUtil.getSuid());
            userRole.setRoleId(roleId);
            userRole.setUserId(user.getId());
            userRoleManager.save(userRole);
            //保存用户部门关系
            orgIdList.stream().forEach(item->{
                if(!isOrgUserEff(item,userId)){
                    OrgUser orgUser=new OrgUser();
                    orgUser.setIsMaster(1);
                    orgUser.setOrgId(item);
                    orgUser.setIsCharge(0);
                    orgUser.setUserId(userId);
                    orgUser.setIsRelActive(1);
//            orgUser.setRelId();
                    orgUser.setIsDelete(Constant.DING_DATA_STATUS_0);
                    orgUser.setCreateTime(LocalDateTime.now());
                    orgUserManager.saveOrUpdate(orgUser);
                }
            });
            orgExternalUser.setUserId(userId);//更新钉钉用户表，添加关联系统用户id
            if(StringUtil.isNotEmpty(orgExternalUser.getExternalPost())){
                savaPostJob(orgExternalUser);//处理岗位数据
            }
            dingUserManager.saveOrUpdate(orgExternalUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @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 "没有配置";
        }
        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 token= (String) jsonObject.get("access_token");
                return  token;
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return  null;
    }
}
