package com.hotent.portal.persistence.manager.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import com.aliyun.dingtalkmicro_app_1_0.models.CreateInnerAppResponse;
import com.aliyun.dingtalkmicro_app_1_0.models.DeleteInnerAppResponse;
import com.aliyun.dingtalkmicro_app_1_0.models.UpdateInnerAppResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonObject;
import com.hotent.base.exception.BaseException;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.*;
import com.hotent.file.model.DefaultFile;
import com.hotent.file.persistence.manager.FileManager;
import com.hotent.portal.model.AppDingModel;
import com.hotent.portal.model.AppModelList;
import com.hotent.portal.model.dto.PortalOrgInfoDto;
import com.hotent.portal.model.dto.PortalUserInfoDto;
import com.hotent.portal.params.AppTree;
import com.hotent.portal.persistence.manager.AppDingModelManager;
import com.hotent.portal.util.HttpClientUtil;
import com.hotent.sys.persistence.dao.SysAuthUserDao;
import com.hotent.sys.persistence.manager.CurrentUserService;
import com.hotent.sys.persistence.manager.SysAuthUserManager;
import com.hotent.sys.persistence.manager.SysCategoryManager;
import com.hotent.sys.persistence.manager.SysTypeManager;
import com.hotent.sys.persistence.model.SysAuthUser;
import com.hotent.sys.persistence.model.SysCategory;
import com.hotent.sys.persistence.model.SysType;
import com.hotent.sys.util.SysPropertyUtil;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.portal.model.AppModel;
import com.hotent.portal.persistence.dao.AppModelDao;
import com.hotent.portal.persistence.manager.AppModelManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * <pre> 
 * 描述：移动端应用 处理实现类
 * 构建组：x7
 * 作者:pangq
 * 邮箱:pangq@jee-soft.cn
 * 日期:2020-07-06 15:23:30
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@Service("appModelManager")
public class AppModelManagerImpl extends BaseManagerImpl<AppModelDao, AppModel> implements AppModelManager{
	@Resource
	SysTypeManager sysTypeManager;
	@Resource
	SysAuthUserManager sysAuthUserManager;
	@Resource
	SysAuthUserDao sysAuthUserDao;
	@Resource
	UCFeignService ucFeignService;
	@Resource
	SysCategoryManager sysCategoryManager;
	@Resource
	CurrentUserService currentUserService;

	@Value("${dingSetting.dingAppIndexUrl}")
	private String dingAppIndexUrl;//移动端钉钉应用根路径

	@Autowired
	private AppDingModelManager appDingModelManager;
	@Autowired
	private FileManager fileManager;

	@Value("${dingSetting.dingFilePath}")
	private String dingFilePath;//移动端钉钉应用根路径

	@Override
	public List<AppModel> getByTypeId(String typeId) {
		QueryWrapper<AppModel> queryWrapper = new QueryWrapper<AppModel>();
		queryWrapper.and(i -> i.eq("TYPE_ID_", typeId).eq("ENABLE_", 1));
		queryWrapper.orderByAsc("SN_");
		queryWrapper.orderByDesc("CREATE_TIME_");
		return this.list(queryWrapper);
	}

	@Override
	public List<AppModel> getByTypeId(String typeId, String appName) {
		QueryWrapper<AppModel> queryWrapper = new QueryWrapper<AppModel>();
		if(StringUtil.isNotEmpty(appName)){
			queryWrapper.and(i -> i.eq("TYPE_ID_", typeId).eq("ENABLE_", 1).like("NAME_",appName));
		}else{
			queryWrapper.and(i -> i.eq("TYPE_ID_", typeId).eq("ENABLE_", 1));
		}
		queryWrapper.orderByAsc("SN_");
		queryWrapper.orderByDesc("CREATE_TIME_");
		return this.list(queryWrapper);
	}

	@Override
	public Map<String, String> exportData(List<String> ids) throws Exception {
		Map<String, String> map = new HashMap<>();
		AppModelList appModelList = new AppModelList();
		for (String id : ids) {
			AppModel appModel = this.get(id);
			SysType sysType = sysTypeManager.get(appModel.getTypeId());
			if (sysType == null){
				sysType = sysTypeManager.getByTypeKeyAndGroupKey("appType","mrfl");
				if (sysType == null){
					sysType = sysTypeManager.getByTypeKeyAndGroupKey("appType","default");
				}
			}
			appModel.setTypeKey(sysType.getTypeKey());
			Map<String,Object> condition = new HashMap<>();
			condition.put("authorize_id_", id);
			List<SysAuthUser> sysAuthUserList = sysAuthUserDao.selectByMap(condition);
			for (SysAuthUser sysAuthUser : sysAuthUserList){
				String rightType = sysAuthUser.getRightType();
				String ownerId = sysAuthUser.getOwnerId();
				if ("user".equals(rightType)){
					CommonResult<JsonNode> result = ucFeignService.getUserById(ownerId);
					if (BeanUtils.isNotEmpty(result)){
						JsonNode userNode = result.getValue();
						String account = JsonUtil.getString(userNode, "account");
						sysAuthUser.setOwnerCode(account);
					}
				}else if ("org".equals(rightType)){
					ObjectNode orgObjNode = ucFeignService.getOrgByIdOrCode(ownerId);
					if (BeanUtils.isNotEmpty(orgObjNode)){
						String code = orgObjNode.get("code").asText();
						sysAuthUser.setOwnerCode(code);
					}
				}else if ("pos".equals(rightType)){
					CommonResult<ObjectNode> result = ucFeignService.getPostByIdOrCode(ownerId);
					if (BeanUtils.isNotEmpty(result)){
						ObjectNode posObjNode = result.getValue();
						String code = posObjNode.get("code").asText();
						sysAuthUser.setOwnerCode(code);
					}
				}else if ("role".equals(rightType)){
					CommonResult<ObjectNode> result = ucFeignService.getRoleByIdOrCode(ownerId);
					if (BeanUtils.isNotEmpty(result)){
						ObjectNode roleObjNode = result.getValue();
						String code = roleObjNode.get("code").asText();
						sysAuthUser.setOwnerCode(code);
					}
				}
			}
			appModel.setSysAuthUserList(sysAuthUserList);
			appModelList.addAppModel(appModel);
		}
		try {
			String xml = JAXBUtil.marshall(appModelList, AppModelList.class);
			map.put("appModels.portal.xml", xml);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("导出失败！" + e.getMessage(), e);
		}
		return map;
	}

	@Override
	@Transactional
	public void importData(MultipartFile file) {
		String unZipFilePath = null;
		try {
			String rootRealPath = Paths.get(FileUtil.getIoTmpdir(), "/attachFiles/unZip").toString();
			FileUtil.createFolder(rootRealPath, true);
			ZipUtil.unZipFile(file, rootRealPath);
			String name = file.getOriginalFilename();
			String fileDir = StringUtil.substringBeforeLast(name, ".");
			unZipFilePath = Paths.get(rootRealPath, fileDir).toString();
			String xml = FileUtil.readFile(Paths.get(unZipFilePath, "appModels.portal.xml").toString());
			if (StringUtil.isEmpty(xml)) {
				throw new BaseException("导入的xml文件没有内容！");
			}
			AppModelList list = (AppModelList) JAXBUtil.unmarshall(xml, AppModelList.class);
			List<AppModel> appModelList = list.getAppModelList();
			for (AppModel appModel : appModelList) {
				importData(appModel);
			}
		} catch (Exception e) {
			throw new BaseException(e.getMessage(), e);
		} finally {
			if (StringUtil.isNotEmpty(unZipFilePath)) {
				File formDir = new File(unZipFilePath);
				if (formDir.exists()) {
					FileUtil.deleteDir(formDir);
				}
			}
		}
	}


	@Override
	@Transactional
	public CommonResult<String> importDataByXml(String appModelsPortalXml) {
		try {
			AppModelList list = (AppModelList) JAXBUtil.unmarshall(appModelsPortalXml, AppModelList.class);
			List<AppModel> appModelList = list.getAppModelList();
			for (AppModel appModel : appModelList) {
				importData(appModel);
			}
			return new CommonResult<>("导入成功");
		} catch (Exception e) {
			return new CommonResult<>(false, "导入失败：" + e.getMessage());
		}
	}

	@Override
	public List<AppTree> getApp(String typeKey,String appName) throws Exception {
		SysCategory sysCategory = sysCategoryManager.getByTypeKey(typeKey);
		List<AppTree> appTrees = new ArrayList<>();
		if(BeanUtils.isEmpty(sysCategory)) {
			return appTrees;
		}
		IUser user = ContextUtil.getCurrentUser();
		List<SysType> list = sysTypeManager.getByGroupKey(sysCategory.getGroupKey());

		List<SysType> newList = sysAuthUserManager.getAuthItems(list, SysType::getId, user.getUserId(), SysType::getCreateBy);
		List<String> authList = newList.stream().map(SysType::getId).collect(Collectors.toList());

		for (SysType sysType : list) {
			List<AppModel> appList = this.getByTypeId(sysType.getId(),appName);
			if(!user.isAdmin()) {
				appList = sysAuthUserManager.getAuthItems(appList, AppModel::getId, user.getUserId(), AppModel::getCreateBy);
			}
			//判断是否根据组织进行过滤
			String appExtOrgfilter = SysPropertyUtil.getByAlias("appOrgfilter");
			if("true".equals(appExtOrgfilter)) {
				Map<String,Set<String>> userRightMap = currentUserService.getCurUserOrgAndPosRightMap();
				Set<String> set = userRightMap.get("org");
				String orgIds = String.join(",", set);
				String extAppIds = ucFeignService.queryExtAuthAppIdByOrgIds("3", orgIds);
				if(StringUtil.isNotEmpty(extAppIds)) {
					List<String> extAppIdList = new ArrayList<>(Arrays.asList(extAppIds.split(",")));
					appList = appList.stream()
							.filter(appModel -> extAppIdList.contains(appModel.getId()))
							.collect(Collectors.toList());
				} else {
					appList.clear();
				}
			}
			AppTree appItem = new AppTree();
			appItem.setTypeId(sysType.getId());
			appItem.setTypeName(sysType.getName());
			appItem.setPid(sysType.getParentId());
			appItem.setAppList(appList);
			appTrees.add(appItem);
		}
		List<AppTree> rtnList= BeanUtils.listToTree(appTrees);
		if(!user.isAdmin()) {
			rtnList = traversalTree(rtnList, authList, false);
		}

		return rtnList;
	}

	@Override
	public List<AppTree> getAppByNoAuth(String typeKey, String appName) throws Exception {
		SysCategory sysCategory = sysCategoryManager.getByTypeKey(typeKey);
		List<AppTree> appTrees = new ArrayList<>();
		if(BeanUtils.isEmpty(sysCategory)) {
			return appTrees;
		}
		List<SysType> list = sysTypeManager.getByGroupKey(sysCategory.getGroupKey());
		for (SysType sysType : list) {
			List<AppModel> appList = this.getByTypeId(sysType.getId(),appName);
			AppTree appItem = new AppTree();
			appItem.setTypeId(sysType.getId());
			appItem.setTypeName(sysType.getName());
			appItem.setPid(sysType.getParentId());
			appItem.setAppList(appList);
			appTrees.add(appItem);
		}
		List<AppTree> rtnList= BeanUtils.listToTree(appTrees);
		return rtnList;
	}

	@Override
	public CommonResult<String> importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			CommonResult<String> message = new CommonResult<>("导入成功");
			this.importData(request.getFile("file"));
			// 移动端应用 导入成功！
			LinkedHashSet<String> appModelsSaved = ThreadMsgUtil.getMapMsg2("appModelsSaved");
			// 移动端应用 已存在故跳过！
			LinkedHashSet<String> appModelsSkipped = ThreadMsgUtil.getMapMsg2("appModelsSkipped");
			StringBuilder sb = new StringBuilder();
			if (BeanUtils.isNotEmpty(appModelsSkipped)){
				sb.append("<div style='font-weight:bold;'>以下移动端应用已存在故跳过：</div>");
				String msg =  String.format( "%s", String.join("", appModelsSkipped));
				sb.append(msg);
			}
			String msg = sb.toString();
			if(StringUtil.isNotEmpty(msg)){
				message.setMessage(msg);
			}
			return message;
		} catch (Exception e) {
			return new CommonResult<>(false, "导入失败：" + e.getMessage());
		}
	}

	@Override
	public CommonResult<String> createOrUpdate(AppModel appModel) {
		String msg = "添加移动端应用成功";
		IUser user = ContextUtil.getCurrentUser();
		if(StringUtil.isEmpty(appModel.getId())){
			appModel.setCreateBy(user.getUserId());
			appModel.setCreateTime(LocalDateTime.now());
			this.create(appModel);
			sysAuthUserManager.createDefault(appModel.getId());
		}else{
			appModel.setUpdateBy(user.getUserId());
			appModel.setUpdateTime(LocalDateTime.now());
			this.update(appModel);
			msg = "更新移动端应用成功";
		}
		return new CommonResult<>(true,msg);
	}

	@Override
	public CommonResult<String> pushDingApp( AppDingModel appDingModel) {
		//1.查询移动端app的权限，根据权限 获取组织id，根据组织id获取组织钉钉参数配置
		try {
			ArrayNode arrayNode=sysAuthUserManager.getRights(appDingModel.getAppId(),"app");
			List<SysAuthUser> bpmDefUserList = toBpmDefUserList(arrayNode.toString(),appDingModel.getAppId());
			System.out.println(bpmDefUserList.size());

			return getBpmOrgIdList(bpmDefUserList,appDingModel);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//2.获取到组织钉钉参数配置，进行调用钉钉api创建钉钉应用

		CommonResult<String> message = new CommonResult<>("发布成功");
		return message;
	}

	@Override
	public CommonResult<JsonNode> getDingUserInfo(String code, String corpId, String appId) {

		JsonNode jsonNode=ucFeignService.getOrgExtSettingByCorpId(corpId);
		String orgId=jsonNode.get("orgId").asText();

		String token=getAccessTokenNew(orgId);
		String tokenOld=getAccessTokenOld(orgId);

		cn.hutool.json.JSONObject result=getDingUserInfoByCode(code,token);
		if(result!=null){
			String dingUserId= (String) result.get("userid");
			cn.hutool.json.JSONObject userInfoJson =getDingUserInfoDetail(dingUserId,tokenOld);
			if(userInfoJson!=null){
				String mobile= (String) userInfoJson.get("mobile");
				CommonResult<JsonNode> user=ucFeignService.getUserByMobile(mobile);
				return user;
			}
		}
		return null;
	}

	@Override
	public AppModel getAppById(String id) {
		LambdaQueryWrapper<AppModel> appQw=new LambdaQueryWrapper<>();
		appQw.eq(AppModel::getId,id);
		return this.baseMapper.selectOne(appQw);
	}

	/**
	 * @description  根据免登授权码获取用户信息
	 * @author  yangzibin
	 * @date    2024/3/6 8:53
	 * @param	code
	 * @param	accessToken
	 * @return  cn.hutool.json.JSONObject
	 */
	private cn.hutool.json.JSONObject getDingUserInfoByCode(String code,String accessToken){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
		OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
		req.setCode(code);
		OapiV2UserGetuserinfoResponse rsp = null;
		try {
			rsp = client.execute(req, accessToken);
			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 jsonObjectResult= new cn.hutool.json.JSONObject(jsonObject.get("result"));
				return jsonObjectResult;
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	private CommonResult<String> getBpmOrgIdList(List<SysAuthUser> bpmDefUserList,AppDingModel appDingModel){
		List<String> userIdList=new ArrayList<>();
		List<String> orgIdList=new ArrayList<>();
		List<String> posIdList=new ArrayList<>();
		List<String> roleIdList=new ArrayList<>();
		bpmDefUserList.forEach(item->{
			String rightType=item.getRightType();

			if(rightType.equals("user")){
				userIdList.add(item.getOwnerId());
			}else if(rightType.equals("org")){
				orgIdList.add(item.getOwnerId());
			}else if(rightType.equals("pos")){
				posIdList.add(item.getOwnerId());
			}else if(rightType.equals("role")){
				roleIdList.add(item.getOwnerId());
			}else if(rightType.equals("everyone")){//所有人
//				orgIdList.add();
				ArrayNode jsonList=ucFeignService.getAllUserByList();
				for(int i=0;i<jsonList.size();i++){
					String id=jsonList.get(i).get("id").asText();
					userIdList.add(id);
				}
			}


		});
		List<PortalUserInfoDto> allUserInfo=new ArrayList<>();
		if(userIdList.size()>0){
			List<PortalUserInfoDto> portalUserList=getPersUserList(userIdList);//用户权限获取到的用户
			allUserInfo.addAll(portalUserList);
		}
		if(roleIdList.size()>0){
			List<PortalUserInfoDto> portalUserListByRole= getRoleUserByRoleId(roleIdList);//角色权限获取到的用户
			allUserInfo.addAll(portalUserListByRole);
		}
		if(posIdList.size()>0){
			List<PortalUserInfoDto> portalUserListByPost= getPostUserByPostId(posIdList);//岗位权限获取到的用户
			allUserInfo.addAll(portalUserListByPost);
		}
		if(orgIdList.size()>0){
			List<PortalUserInfoDto> portalUserListByOrg= getPostUserByOrgId(orgIdList);//组织权限获取到的用户
			allUserInfo.addAll(portalUserListByOrg);
		}
		List<PortalUserInfoDto> userListTemp=new ArrayList<>();
		userListTemp=allUserInfo.stream()
				.collect(Collectors.collectingAndThen(Collectors.toCollection(
						() -> new TreeSet<>(Comparator.comparing(PortalUserInfoDto::getId))), ArrayList::new));


		List<PortalOrgInfoDto> allOrgList=getAllPerssionOrg(userListTemp);//所有的授权组织包含授权组织下的用户
		if(StringUtil.isNotEmpty(appDingModel.getDeleteFlag())&&appDingModel.getDeleteFlag().equals("1")){//删除
			deleteDingApp(allOrgList, appDingModel);

			CommonResult<String> message = new CommonResult<>("取消成功");
			return message;
		}else{//新增编辑
			createDingApp(allOrgList, appDingModel);
			CommonResult<String> message = new CommonResult<>("发布成功");
			return message;
		}
	}
	/**
	 * @description  删除应用
	 * @author  yangzibin
	 * @date    2024/3/5 17:27
	 * @param	allOrgList
	 * @param	appDingModel
	 * @return  void
	 */
	private void deleteDingApp(List<PortalOrgInfoDto> allOrgList,AppDingModel appDingModel){
		allOrgList.forEach(item->{
			String token=getAccessTokenNew(item.getId());
			String tokenOld=getAccessTokenOld(item.getId());
			if(StringUtil.isEmpty(tokenOld)){
				return;
			}
			List<AppDingModel> appDingList=appDingModelManager.getDingApp(appDingModel.getAppId(),item.getId());
			String adminDingUserId=getDingAdminUserId(tokenOld);//获取钉钉adminUserId,发布钉钉应用
			if(appDingList.size()>0){
				if(StringUtil.isEmpty(token)){
					return;
				}
				boolean flag=deleteDingAppApi(adminDingUserId,appDingList.get(0).getDingAppAgentId(),token);
				if(flag){
					appDingModelManager.remove(appDingList.get(0).getId());
				}
			}

		});
	}
	private boolean deleteDingAppApi(String sysAdminUserId,String appAgentId,String token){
		try {
			com.aliyun.dingtalkmicro_app_1_0.Client client = createDingAppClient();
			com.aliyun.dingtalkmicro_app_1_0.models.DeleteInnerAppHeaders deleteInnerAppHeaders = new com.aliyun.dingtalkmicro_app_1_0.models.DeleteInnerAppHeaders();
			deleteInnerAppHeaders.xAcsDingtalkAccessToken = token;
			com.aliyun.dingtalkmicro_app_1_0.models.DeleteInnerAppRequest deleteInnerAppRequest = new com.aliyun.dingtalkmicro_app_1_0.models.DeleteInnerAppRequest()
					.setOpUnionId(sysAdminUserId);

			DeleteInnerAppResponse result= client.deleteInnerAppWithOptions(appAgentId, deleteInnerAppRequest, deleteInnerAppHeaders, new com.aliyun.teautil.models.RuntimeOptions());
			cn.hutool.json.JSONObject jsonObject1= new cn.hutool.json.JSONObject(result.getBody());
			boolean flag= (boolean) jsonObject1.get("result");
			return  flag;
		} catch (TeaException err) {
			if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
			}
		} 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)) {
			}
		}
		return  false;
	}
	/**
	 * @description  循环的创建钉钉微应用
	 * @author  yangzibin
	 * @date    2024/3/1 16:34
	 * @param
	 * @return  void
	 */
	private void createDingApp(List<PortalOrgInfoDto> allOrgList,AppDingModel appDingModel){
		allOrgList.forEach(item->{
			String flag="0";
			String token=getAccessTokenNew(item.getId());
			String tokenOld=getAccessTokenOld(item.getId());
			if(StringUtil.isEmpty(tokenOld)){
				return;
			}
			String adminDingUserId=getDingAdminUserId(tokenOld);//获取钉钉adminUserId,发布钉钉应用
			List<AppDingModel> appDingList=appDingModelManager.getDingApp(appDingModel.getAppId(),item.getId());
			if(appDingList.size()>0){
				flag="1";
			}else{
				flag="0";
			}
			if(flag.equals("0")){//新增
				cn.hutool.json.JSONObject createAppResult=createDingAppFun(item.getId(),tokenOld,adminDingUserId,token,appDingModel);//获取发布钉钉app结果
				if(createAppResult!=null){
					saveOrUpdateDingAppInfo(token,tokenOld,item,item.getId(),appDingModel,flag,createAppResult,adminDingUserId);
				}
			}else{//编辑应用
				appDingModel.setDingAppAgentId(appDingList.get(0).getDingAppAgentId());
				cn.hutool.json.JSONObject updateAppResult=updateDingAppFun(item.getId(),tokenOld,adminDingUserId,token,appDingModel);
				if(updateAppResult!=null){
					saveOrUpdateDingAppInfo(token,tokenOld,item,item.getId(),appDingModel,flag,updateAppResult,adminDingUserId);
				}
			}
		});
	}
	/**
	 * @description  保存创建的钉钉应用
	 * @author  yangzibin
	 * @date    2024/3/5 15:07
	 * @param	token
	 * @param	tokenOld
	 * @param	portalOrgInfoDto
	 * @param	orgId
	 * @param	appDingModel
	 * @param	flag
	 * @param	createAppResult
	 * @param	adminDingUserId
	 * @return  void
	 */
	private void saveOrUpdateDingAppInfo(String token,String tokenOld,PortalOrgInfoDto portalOrgInfoDto,String orgId,AppDingModel appDingModel,String flag,cn.hutool.json.JSONObject createAppResult,String adminDingUserId){
		List<AppDingModel> appDing=appDingModelManager.getDingApp(appDingModel.getAppId(),orgId);
		if(appDing.size()>0) {//新增数据
			AppDingModel appDingModelTemp=appDing.get(0);
			appDingModelTemp.setDingAppName(appDingModel.getDingAppName());
			appDingModelTemp.setDingAppDesc(appDingModel.getDingAppDesc());
			appDingModelTemp.setDingAppIcon(appDingModel.getDingAppIcon());
			appDingModel=appDingModelTemp;
		}else{
			Long agentId= (Long) createAppResult.get("agentId");
			String appKey= (String) createAppResult.get("appKey");
			String appSecret= (String) createAppResult.get("appSecret");
			String appUrl= (String) createAppResult.get("appUrl");
			appDingModel.setOrgId(orgId);
			appDingModel.setDingAppKey(appKey);
			appDingModel.setDingAppSecret(appSecret);
			appDingModel.setDingAppAgentId(agentId+"");
			appDingModel.setDingOpUnionId(adminDingUserId);
			appDingModel.setCreateTime(LocalDateTime.now());
			appDingModel.setDingAppUrl(appUrl);
		}
		List<PortalUserInfoDto> userList=portalOrgInfoDto.getUserList();
		String userIdStr=userList.stream().map(item->item.getId()).collect(Collectors.joining(","));
		appDingModel.setUserId(userIdStr);

		List<String> userIdList=userList.stream().map(item->item.getMobile()).collect(Collectors.toList());
		List<String> dingUserIdList=new ArrayList<>();
		userIdList.stream().forEach(item->{
			if(StringUtil.isNotEmpty(item)){
				String dingUserId=getDingUserUserId(item,tokenOld);
				if(StringUtil.isNotEmpty(dingUserId)){
					dingUserIdList.add(dingUserId);
				}
			}
		});
		if(userIdList.size()>0){
			appDingModel.setDingUserId(dingUserIdList.stream().collect(Collectors.joining(",")));
		}
		appDingModelManager.saveOrUpdate(appDingModel);
		//设置应用可见范围
		if(appDingModel.getDingUserId()!=null&&appDingModel.getDingAppAgentId()!=null){
			cn.hutool.json.JSONObject getSetting=getDingAppPerssion(appDingModel.getDingAppAgentId(),token);
			if(getSetting!=null){
				boolean flagSetLook= setDingAppPerssion(appDingModel,token,getSetting);
			}
		}
	}
	/**
	 * @description  设置钉钉应用可见范围
	 * @date    2024/3/5 14:49
	 * @param	agentId
	 * @param	token
	 * @param	getSettingJson
	 * @return  cn.hutool.json.JSONObject
	 */
	private Boolean setDingAppPerssion(AppDingModel appDingModel,String token,cn.hutool.json.JSONObject getSettingJson){

		String url="https://api.dingtalk.com/v1.0/microApp/apps/"+appDingModel.getDingAppAgentId()+"/scopes";
		try {
			List<String> delUserIdList= (List<String>)getSettingJson.get("userIds");
//			List<String> delUserIdList= Arrays.asList(getSettingJson.get("userIds").toString().split(","));
			List<String> addUserIdList= Arrays.asList(appDingModel.getDingUserId().split(","));
			List<String> delUserIdListTemp=new ArrayList<>();
			for(int i=0;i<delUserIdList.size();i++){
				boolean flag=false;
				for(int j=0;j<addUserIdList.size();j++){
                   if(delUserIdList.get(i).equals(addUserIdList.get(j))){
					   flag=true;
				   }
				}
				if(!flag){
					delUserIdListTemp.add(delUserIdList.get(i));
				}
			}

			cn.hutool.json.JSONObject jsonObjectParams=new JSONObject();
			jsonObjectParams.put("onlyAdminVisible",false);
			jsonObjectParams.put("addUserIds",appDingModel.getDingUserId().split(","));
			jsonObjectParams.put("delUserIds",delUserIdListTemp);
			JSONObject jsonObject=HttpClientUtil.useDingApiPost(url,jsonObjectParams.toString(),token);
			String code= (String) jsonObject.get("code");
			//{"msg":"获取成功","code":"200","data":"{\"result\":{\"onlyAdminVisible\":false,\"userIds\":[\"manager7551\"]}}"}
			if(code.equals("200")){
				String data= (String) jsonObject.get("data");
				cn.hutool.json.JSONObject jsonObject1= new cn.hutool.json.JSONObject(data);
				boolean flag= (boolean) jsonObject1.get("result");
				return flag;
			}
			System.out.println(jsonObject);
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
	/**
	 * @description 获取应用的可见范围权限
	 * @date    2024/3/5 14:48
	 * @param	agentId
	 * @param	token
	 * @return  cn.hutool.json.JSONObject
	 */
	private cn.hutool.json.JSONObject getDingAppPerssion(String agentId,String token){

		String url="https://api.dingtalk.com/v1.0/microApp/apps/"+agentId+"/scopes";
		try {
			JSONObject jsonObject=HttpClientUtil.useDingApiGet(url,"",token);
			String code= (String) jsonObject.get("code");
			//{"msg":"获取成功","code":"200","data":"{\"result\":{\"onlyAdminVisible\":false,\"userIds\":[\"manager7551\"]}}"}
			if(code.equals("200")){
				String data= (String) jsonObject.get("data");
				cn.hutool.json.JSONObject jsonObject1= new cn.hutool.json.JSONObject(data);

				cn.hutool.json.JSONObject jsonObject2= new cn.hutool.json.JSONObject(jsonObject1.get("result"));
				List<String> userIdsList= (List<String>) jsonObject2.get("userIds");
				List<String> deptIdsList= (List<String>) jsonObject2.get("deptIds");
				List<String> roleIdsList= (List<String>) jsonObject2.get("roleIds");
				return jsonObject2;
			}
			System.out.println(jsonObject);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}


	/**
	 * @description  根据手机号获取钉钉用户UserId
	 * @author  yangzibin
	 * @date    2024/3/5 11:35
	 * @param	mobile
	 * @param	tokenOld
	 * @return  java.lang.String
	 */
	private String getDingUserUserId(String mobile,String tokenOld){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
		OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
		req.setMobile(mobile);
		OapiV2UserGetbymobileResponse rsp = null;
		try {
			rsp = client.execute(req, tokenOld);
			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 jsonObject1= new cn.hutool.json.JSONObject(jsonObject.get("result"));
				String userid= (String) jsonObject1.get("userid");
				return userid;
			}else{
				return "";
			}
		} catch (ApiException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * @description  获取钉钉组织的主管理员userId
	 * @author  yangzibin
	 * @date    2024/3/2 9:33
	 * @param
	 * @return  void
	 */
	private String  getDingAdminUserId(String access_token){
		String adminUserId="";
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listadmin");
		OapiUserListadminRequest req = new OapiUserListadminRequest();
		OapiUserListadminResponse rsp = null;
		try {
			rsp = client.execute(req, access_token);
			cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(rsp.getBody());
			System.out.println(rsp.getBody());
			//{"errcode":0,"errmsg":"ok","result":[{"sys_level":1,"userid":"manager7551"},{"sys_level":2,"userid":"18234122067"},{"sys_level":2,"userid":"012136306163840081"},{"sys_level":2,"userid":"18734588654"}],"request_id":"16mn4jk6va3ng"}
			int errcode= (int) jsonObject.get("errcode");
			if(errcode==0){
				cn.hutool.json.JSONArray jsonArray= (cn.hutool.json.JSONArray) jsonObject.get("result");
				for (int i =0;i<jsonArray.size();i++){
					cn.hutool.json.JSONObject jsonObjectTemp= new cn.hutool.json.JSONObject(jsonArray.get(i));
					int sys_level= (int) jsonObjectTemp.get("sys_level");
					String userid= (String) jsonObjectTemp.get("userid");
					if(StringUtil.isNotEmpty(userid)&&sys_level==1){//主管理员
						adminUserId=userid;
						cn.hutool.json.JSONObject userInfoJson =getDingUserInfoDetail(adminUserId,access_token);
						if(userInfoJson!=null){
							String unionId= (String) userInfoJson.get("unionid");
							return  unionId;
						}
					}
				}
				return  adminUserId;
			}

		} catch (ApiException e) {
			e.printStackTrace();
			return "";
		}
		return "";
	}
	/**
	 * @description  获取钉钉用户详情
	 * @author  yangzibin
	 * @date    2024/3/6 14:08
	 * @param	dingUserId
	 * @param	token
	 * @return  cn.hutool.json.JSONObject
	 */
	private cn.hutool.json.JSONObject getDingUserInfoDetail(String dingUserId,String token){
		DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
		OapiV2UserGetRequest req1 = new OapiV2UserGetRequest();
		req1.setUserid(dingUserId);
		req1.setLanguage("zh_CN");
		OapiV2UserGetResponse rsp1 = null;
		try {
			rsp1 = client1.execute(req1, token);
			System.out.println(rsp1.getBody());
			cn.hutool.json.JSONObject jsonObject1= new cn.hutool.json.JSONObject(rsp1.getBody());
			int errcode1= (int) jsonObject1.get("errcode");
			if(errcode1==0){
				cn.hutool.json.JSONObject userInfoJson= new cn.hutool.json.JSONObject(jsonObject1.get("result"));
				return userInfoJson;
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * @description  上传图片icon
	 * @author  yangzibin
	 * @date    2024/3/2 10:13
	 * @param	filePath
	 * @param	access_token
	 * @return  java.lang.String
	 */
	private String uploadDingIcon(String filePath,String access_token){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
		OapiMediaUploadRequest req = new OapiMediaUploadRequest();
		req.setType("image");
// 要上传的媒体文件
		FileItem item = new FileItem(filePath);
		req.setMedia(item);
		OapiMediaUploadResponse rsp = null;
		try {
			rsp = client.execute(req, access_token);
			cn.hutool.json.JSONObject fileJson= new cn.hutool.json.JSONObject(rsp.getBody());
			int errcode= (int) fileJson.get("errcode");
			if(errcode==0){
				String media_id= (String) fileJson.get("media_id");
				return media_id;
			}
			//{"errcode":0,"errmsg":"ok","media_id":"@lALPDefSADVmcyfNCVzNCc8","created_at":1709625664326,"type":"image"}
			System.out.println(rsp.getBody());
		} catch (ApiException e) {
			e.printStackTrace();
			return  "";
		}
		return  "";
	}
	private cn.hutool.json.JSONObject updateDingAppFun(String orgId,String tokenOld,String sysAdminUserId,String accessToken,AppDingModel appDingModel){
		String media_id="";
		if(StringUtil.isNotEmpty(appDingModel.getDingAppIcon())){
			String tempImg=dingFilePath;
			//处理图片，获取文件并且上传
			DefaultFile file=fileManager.get(appDingModel.getDingAppIcon());
			String path=file.getFilePath();
			System.out.println(path);
			try {
				fileManager.downloadFileToPath(file,tempImg);
				Thread.sleep(1000);
				 media_id=uploadDingIcon(tempImg,tokenOld);
				File file1 = new File(tempImg);
				file1.delete();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		JsonNode jsonNode=ucFeignService.getOrgExtSetting(orgId);
		String state=jsonNode.get("state").asText();
		String message=jsonNode.get("message").asText();
		if(state.equals("false")){
			return null;
		}
		if(message.contains("失败")){
			return null;
		}
		ObjectNode jsonContent= (ObjectNode) jsonNode.get("value");
		String dingAppkey=jsonContent.get("dingAppKey").asText();
		String dingAppSecret=jsonContent.get("dingAppSecret").asText();
		String dingCorpId=jsonContent.get("dingCorpId").asText();
		return updateDingAppApi(dingCorpId,sysAdminUserId,accessToken,appDingModel,media_id);
	}

	private cn.hutool.json.JSONObject createDingAppFun(String orgId,String tokenOld,String sysAdminUserId,String accessToken,AppDingModel appDingModel){
		String media_id="";
		if(StringUtil.isNotEmpty(appDingModel.getDingAppIcon())){
			String tempImg=dingFilePath;
			//处理图片，获取文件并且上传
			DefaultFile file=fileManager.get(appDingModel.getDingAppIcon());
			String path=file.getFilePath();
			System.out.println(path);
			try {
				fileManager.downloadFileToPath(file,tempImg);
				Thread.sleep(1000);
				media_id=uploadDingIcon(tempImg,tokenOld);
				File file1 = new File(tempImg);
				file1.delete();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		JsonNode jsonNode=ucFeignService.getOrgExtSetting(orgId);
		String state=jsonNode.get("state").asText();
		String message=jsonNode.get("message").asText();
		if(state.equals("false")){
			return null;
		}
		if(message.contains("失败")){
			return null;
		}
		ObjectNode jsonContent= (ObjectNode) jsonNode.get("value");
		String dingAppkey=jsonContent.get("dingAppKey").asText();
		String dingAppSecret=jsonContent.get("dingAppSecret").asText();
		String dingCorpId=jsonContent.get("dingCorpId").asText();
		return createDingAppApi(dingCorpId,sysAdminUserId,accessToken,appDingModel,media_id);
	}
	private cn.hutool.json.JSONObject updateDingAppApi(String dingCorpId,String sysAdminUserId,String accessToken,AppDingModel appDingModel,String media_id){
		cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject();
		try {
			com.aliyun.dingtalkmicro_app_1_0.Client client = null;
			try {
				client = createDingAppClient();
			} catch (Exception e) {
				e.printStackTrace();
			}
			com.aliyun.dingtalkmicro_app_1_0.models.UpdateInnerAppHeaders createInnerAppHeaders = new com.aliyun.dingtalkmicro_app_1_0.models.UpdateInnerAppHeaders();
			createInnerAppHeaders.xAcsDingtalkAccessToken = accessToken;
			com.aliyun.dingtalkmicro_app_1_0.models.UpdateInnerAppRequest createInnerAppRequest = new com.aliyun.dingtalkmicro_app_1_0.models.UpdateInnerAppRequest()
					.setOpUnionId(sysAdminUserId)
					.setName(appDingModel.getDingAppName())
					.setDesc(appDingModel.getDingAppDesc())
				   .setIcon(media_id)
					.setHomepageLink(dingAppIndexUrl+"?corpId="+dingCorpId+"&appId="+appDingModel.getAppId());
			UpdateInnerAppResponse clientResult= client.updateInnerAppWithOptions(appDingModel.getDingAppAgentId(),createInnerAppRequest, createInnerAppHeaders, new com.aliyun.teautil.models.RuntimeOptions());
			jsonObject= new cn.hutool.json.JSONObject(clientResult.getBody());
			if(jsonObject!=null){
				jsonObject.put("appUrl",dingAppIndexUrl+"?corpId="+dingCorpId+"&appId="+appDingModel.getAppId());
			}
			return jsonObject;
		} catch (Exception err) {
			err.printStackTrace();
		}
		return null;
	}
	private cn.hutool.json.JSONObject createDingAppApi(String dingCorpId,String sysAdminUserId,String accessToken,AppDingModel appDingModel,String media_id){

		try {

			com.aliyun.dingtalkmicro_app_1_0.Client client = null;
			try {
				client = createDingAppClient();
			} catch (Exception e) {
				e.printStackTrace();
			}
			com.aliyun.dingtalkmicro_app_1_0.models.CreateInnerAppHeaders createInnerAppHeaders = new com.aliyun.dingtalkmicro_app_1_0.models.CreateInnerAppHeaders();
			createInnerAppHeaders.xAcsDingtalkAccessToken = accessToken;
			com.aliyun.dingtalkmicro_app_1_0.models.CreateInnerAppRequest createInnerAppRequest = new com.aliyun.dingtalkmicro_app_1_0.models.CreateInnerAppRequest()
					.setOpUnionId(sysAdminUserId)
					.setName(appDingModel.getDingAppName())
					.setDesc(appDingModel.getDingAppDesc())
				    .setIcon(media_id)
					.setHomepageLink(dingAppIndexUrl+"?corpId="+dingCorpId+"&appId="+appDingModel.getAppId())
					.setScopeType("BASE");

			CreateInnerAppResponse clientResult= client.createInnerAppWithOptions(createInnerAppRequest, createInnerAppHeaders, new com.aliyun.teautil.models.RuntimeOptions());
			cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(clientResult.getBody());
			if(jsonObject!=null){
				jsonObject.put("appUrl",dingAppIndexUrl+"?corpId="+dingCorpId+"&appId="+appDingModel.getAppId());
			}
			return jsonObject;
		} catch (Exception err) {
			err.printStackTrace();
		}
		return null;
	}
	/**
	 * @description  设置钉钉应用可见使用范围
	 * @author  yangzibin
	 * @date    2024/3/1 16:36
	 * @param
	 * @return  void
	 */
	private void  setDingAppUseFw(String accessToken){

	}

	/**
	 * @description  获取钉钉应用可见使用范围
	 * @author  yangzibin
	 * @date    2024/3/1 16:36
	 * @param
	 * @return  void
	 */
	private void  getDingAppUseFw(){

	}
	/**
	 * 使用 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  com.aliyun.dingtalkmicro_app_1_0.Client createDingAppClient() throws Exception {
		com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
		config.protocol = "https";
		config.regionId = "central";
		return new com.aliyun.dingtalkmicro_app_1_0.Client(config);
	}
	/**
	 * @description 旧版钉钉获取token
	 * @author  yangzibin
	 * @date    2024/3/1 17:50
	 * @param	orgId
	 * @return  java.lang.String
	 */
	public  String getAccessTokenOld (String orgId){
		JsonNode jsonNode=ucFeignService.getOrgExtSetting(orgId);
		String state=jsonNode.get("state").asText();
		String message=jsonNode.get("message").asText();
		if(state.equals("false")){
			return "";
		}
		if(message.contains("失败")){
			return "";
		}
		ObjectNode jsonContent= (ObjectNode) jsonNode.get("value");
		String dingAppkey=jsonContent.get("dingAppKey").asText();
		String dingAppSecret=jsonContent.get("dingAppSecret").asText();

		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setAppkey(dingAppkey);
		request.setAppsecret(dingAppSecret);
		request.setHttpMethod("GET");
		OapiGettokenResponse response = null;
		try {
			response = client.execute(request);
			cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(response.getBody());
			int errcode= (int) jsonObject.get("errcode");
			if(errcode==0){
				String accessToken= (String) jsonObject.get("access_token");
				return accessToken;
			}
//			System.out.println(response.getBody());
			//{"errcode":0,"access_token":"5f2f7b25149532a78e9368f3b62bfada","errmsg":"ok","expires_in":7200}
		} catch (ApiException e) {
			e.printStackTrace();
		}

		return "";
	}
	/**
	 * @description 新版钉钉 获取token
	 * @author  yangzibin
	 * @date    2024/3/1 17:42
	 * @param	orgId
	 * @return  java.lang.String
	 */
	public  String getAccessTokenNew (String orgId){
		JsonNode jsonNode=ucFeignService.getOrgExtSetting(orgId);
		String state=jsonNode.get("state").asText();
		String message=jsonNode.get("message").asText();
		if(state.equals("false")){
			return "";
		}
		if(message.contains("失败")){
			return "";
		}
		ObjectNode jsonContent= (ObjectNode) jsonNode.get("value");
		String dingAppkey=jsonContent.get("dingAppKey").asText();
		String dingAppSecret=jsonContent.get("dingAppSecret").asText();
//		java.util.List<String> args = java.util.Arrays.asList(args_);
		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);
			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/3/1 13:56
	 * @param	allUserInfo
	 * @return  java.util.List<com.hotent.portal.model.dto.PortalOrgInfoDto>
	 */
	private  List<PortalOrgInfoDto> getAllPerssionOrg(List<PortalUserInfoDto> allUserInfo){
		List<PortalOrgInfoDto> orgList=new ArrayList<>();
		allUserInfo.stream().forEach(item->{
			String userId=item.getId().replace("\"","");
			ArrayNode jsonList=ucFeignService.getOrgListByUserId(userId);
			List<String> userOrgIdList=new ArrayList<>();
			for(int i=0;i<jsonList.size();i++){
				PortalOrgInfoDto orgInfoDto=new PortalOrgInfoDto();
				JsonNode json =jsonList.get(i);
				String name=json.get("name").asText();
				String id=json.get("id").asText();
				String orgType=json.get("orgType").asText();
				if(orgType.equals("0")||orgType.equals("2")){//组织或者关联组织
					userOrgIdList.add(id.replaceAll("\"",""));
					orgInfoDto.setId(id.replaceAll("\"",""));
					orgInfoDto.setOrgName(name);
					orgList.add(orgInfoDto);
				}
			}
			userOrgIdList = userOrgIdList.stream().collect(
					Collectors.collectingAndThen(Collectors.toCollection(
							() -> new TreeSet<>(Comparator.comparing(String::toString))), ArrayList::new));
			item.setOrgId(userOrgIdList);
		});
		List<PortalOrgInfoDto> orgListTemp=new ArrayList<>();
		orgListTemp=orgList.stream()
				.collect(Collectors.collectingAndThen(Collectors.toCollection(
						() -> new TreeSet<>(Comparator.comparing(PortalOrgInfoDto::getId))), ArrayList::new));

		orgListTemp.stream().forEach(item->{
			List<PortalUserInfoDto> userTemp=new ArrayList<>();
			allUserInfo.stream().forEach(itemUser->{
				List<String> userOrgIdList=itemUser.getOrgId();
				for(int i=0;i<userOrgIdList.size();i++){
					String orgId=userOrgIdList.get(i);
					if(item.getId().equals(orgId)){
						userTemp.add(itemUser);
					}
				}
			});
			item.setUserList(userTemp);
		});

		return orgListTemp;
	}

	/**
	 * @description  获取到授权用户
	 * @author  yangzibin
	 * @date    2024/2/29 17:32
	 * @param	userIdList
	 * @return  java.util.List<com.hotent.portal.model.dto.PortalUserInfoDto>
	 */
	private List<PortalUserInfoDto> getPersUserList(List<String> userIdList){
		List<PortalUserInfoDto> portalUserList=new ArrayList<>();
		userIdList.stream().forEach(item->{
			CommonResult<JsonNode> userInfo=ucFeignService.getUserById(item);
			JsonNode json=userInfo.getValue();
			portalUserList.add(getUserInfoJson(json));
		});
		return  portalUserList;
	}

	private List<PortalUserInfoDto> getRoleUserByRoleId(List<String> roleIdList){
		List<PortalUserInfoDto> portalUserList=new ArrayList<>();

		ArrayNode  objectNode=ucFeignService.getUsersByRoleCode(roleIdList.stream().collect(Collectors.joining(",")));//角色id查询角色数据
		for(int i=0;i<objectNode.size();i++){
			portalUserList.add(getUserInfoJson(objectNode.get(i)));
		}
		return  portalUserList;
	}

	private List<PortalUserInfoDto> getPostUserByPostId(List<String> postIdList){
		List<PortalUserInfoDto> portalUserList=new ArrayList<>();

		ArrayNode  objectNode=ucFeignService.getUserByPost(postIdList.stream().collect(Collectors.joining(",")));//岗位id查询角色数据
		for(int i=0;i<objectNode.size();i++){
			portalUserList.add(getUserInfoJson(objectNode.get(i)));
		}
		return  portalUserList;
	}

	private List<PortalUserInfoDto> getPostUserByOrgId(List<String> orgIdList){
		List<PortalUserInfoDto> portalUserList=new ArrayList<>();

		orgIdList.stream().forEach(item->{
			ArrayNode objectNode=ucFeignService.getAllOrgUsersByOrgId(item);
			for(int i=0;i<objectNode.size();i++){
				portalUserList.add(getUserInfoJson(objectNode.get(i)));
			}

		});
		return  portalUserList;
	}

	private PortalUserInfoDto getUserInfoJson(JsonNode json){
		PortalUserInfoDto  portalUser=new PortalUserInfoDto();
		String id=json.get("id").asText();
		String account=json.get("account").asText();
		String fullName=json.get("fullname").asText();
		String mobile=json.get("mobile").asText();
		portalUser.setFullName(fullName);
		portalUser.setId(id);
		portalUser.setAccount(account);
		portalUser.setMobile(mobile);
		return portalUser;
	}
	/**
	 * 授权人员JSON转成授权人员列表
	 * @param ownNameJson
	 * @param authorizeId
	 * @return
	 * List<BpmDefUser>
	 * 以下为JSON格式：
	 * [{type:"everyone"},{type:"user",id:"",name:""}]
	 * @throws IOException
	 * @exception
	 * @since  1.0.0
	 */
	private List<SysAuthUser> toBpmDefUserList(String ownNameJson,String authorizeId) throws IOException{
		List<SysAuthUser> userList = new ArrayList<SysAuthUser>();
		if(StringUtil.isEmpty(ownNameJson)){
			return userList;
		}

		ArrayNode aryJson=(ArrayNode) JsonUtil.toJsonNode(ownNameJson);
		for(Object obj:aryJson){
			ObjectNode jsonObject=(ObjectNode)obj;
			List<SysAuthUser>  list= getList(jsonObject, authorizeId);
			userList.addAll(list);
		}
		return userList;
	}
	private List<SysAuthUser> getList(ObjectNode json,String authorizeId){
		List<SysAuthUser> bpmDefUsers = new ArrayList<SysAuthUser>();
		String type=json.get("type").asText();

		if("everyone".equals(type)){
			SysAuthUser defUser = new SysAuthUser();
			defUser.setId(UniqueIdUtil.getSuid());
			defUser.setAuthorizeId(authorizeId);
			defUser.setRightType(type);
			bpmDefUsers.add(defUser);
		}
		else{
			String ids=json.get("id").asText();
			String names=json.get("name").asText();

			String[] aryId=ids.split(",");
			String[] aryName=names.split(",");
			for(int i=0;i<aryId.length;i++){
				SysAuthUser defUser = new SysAuthUser();
				defUser.setId(UniqueIdUtil.getSuid());
				defUser.setAuthorizeId(authorizeId);
				defUser.setRightType(type);
				defUser.setOwnerId(aryId[i]);
				defUser.setOwnerName(aryName[i]);

				bpmDefUsers.add(defUser);
			}
		}
		return bpmDefUsers;
	}
	private List<AppTree> traversalTree(List<AppTree> appTrees, List<String> authList, boolean isShow) {
		List<AppTree> trees = new ArrayList<>();
		for (AppTree tree: appTrees) {
			if (authList.contains(tree.getId())) {
				List<AppTree> children = traversalTree(tree.getChildren(), authList, true);
				tree.setChildren(children);
				trees.add(tree);
			}else {
				QueryWrapper wrapper = new QueryWrapper();
				wrapper.eq("authorize_id_", tree.getId());
				wrapper.eq("obj_type_", "app");
				if (sysAuthUserManager.count(wrapper)<=0 && isShow) {
					List<AppTree> children = traversalTree(tree.getChildren(), authList, true);
					tree.setChildren(children);
					trees.add(tree);
				}
			}
		}
		return trees;
	}

	private void importData(AppModel appModel) {
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("name_", appModel.getName());
		List<AppModel> appModelList = baseMapper.selectList(wrapper);
		if (appModelList != null && !appModelList.isEmpty()) {
			ThreadMsgUtil.addMapMsg2("appModelsSkipped", String.format("<div style='margin-left:12px; margin-top:6px;'>%s</div>", appModel.getName() + ""));
			return;
		}
		String appId = UniqueIdUtil.getSuid();
		appModel.setId(appId);
		SysType sysType = sysTypeManager.getByTypeKeyAndGroupKey("appType", appModel.getTypeKey());
		if (sysType == null){
			sysType = sysTypeManager.getByTypeKeyAndGroupKey("appType","mrfl");
			if (sysType == null){
				sysType = sysTypeManager.getByTypeKeyAndGroupKey("appType","default");
			}
		}
		appModel.setTypeId(sysType.getId());
		appModel.setTypeName(sysType.getName());
		List<SysAuthUser> sysAuthUserList = appModel.getSysAuthUserList();
		if (BeanUtils.isEmpty(sysAuthUserList)){
			sysAuthUserManager.createDefault(appId);
		}else{
			for (SysAuthUser sysAuthUser : sysAuthUserList){
				String authId = UniqueIdUtil.getSuid();
				sysAuthUser.setId(authId);
				sysAuthUser.setAuthorizeId(appId);
				String rightType = sysAuthUser.getRightType();
				String ownerCode = sysAuthUser.getOwnerCode();
				if ("user".equals(rightType)){
					JsonNode userNode = ucFeignService.getUser(ownerCode, null);
					if (BeanUtils.isNotEmpty(userNode)){
						String ownerId = JsonUtil.getString(userNode, "id");
						String ownerName = JsonUtil.getString(userNode, "fullname");
						sysAuthUser.setOwnerId(ownerId);
						sysAuthUser.setOwnerName(ownerName);
					}
				}else if ("org".equals(rightType)){
					ObjectNode orgObjNode = ucFeignService.getOrgByIdOrCode(ownerCode);
					if (BeanUtils.isNotEmpty(orgObjNode)){
						String ownerId = orgObjNode.get("id").asText();
						String ownerName = orgObjNode.get("name").asText();
						sysAuthUser.setOwnerId(ownerId);
						sysAuthUser.setOwnerName(ownerName);
					}
				}else if ("pos".equals(rightType)){
					CommonResult<ObjectNode> result = ucFeignService.getPostByIdOrCode(ownerCode);
					if (BeanUtils.isNotEmpty(result)){
						ObjectNode posObjNode = result.getValue();
						String ownerId = posObjNode.get("id").asText();
						String ownerName = posObjNode.get("name").asText();
						sysAuthUser.setOwnerId(ownerId);
						sysAuthUser.setOwnerName(ownerName);
					}
				}else if ("role".equals(rightType)){
					CommonResult<ObjectNode> result = ucFeignService.getRoleByIdOrCode(ownerCode);
					if (BeanUtils.isNotEmpty(result)){
						ObjectNode roleObjNode = result.getValue();
						String ownerId = roleObjNode.get("id").asText();
						String ownerName = roleObjNode.get("name").asText();
						sysAuthUser.setOwnerId(ownerId);
						sysAuthUser.setOwnerName(ownerName);
					}
				}
				sysAuthUserDao.insert(sysAuthUser);
			}
		}
		this.create(appModel);
		ThreadMsgUtil.addMapMsg2("appModelsSaved", String.format("<div style='margin-left:12px; margin-top:6px;'>%s</div>", appModel.getName() + ""));
	}

	@Override
	public  List<Map<String, Object>> getAppStatic() {
		return baseMapper.getAppStatic();
	}
}
