package com.yunzhupaas.onlinedev.util.onlineDevUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.entity.*;
import com.yunzhupaas.base.mapper.FlowFormDataMapper;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.yunzhupaas.base.model.OnlineImport.ExcelImportModel;
import com.yunzhupaas.base.model.OnlineImport.ImportDataModel;
import com.yunzhupaas.base.model.OnlineImport.ImportFormCheckUniqueModel;
import com.yunzhupaas.base.model.OnlineImport.VisualdevModelDataInfoVO;
import com.yunzhupaas.base.model.VisualDevJsonModel;
import com.yunzhupaas.base.model.datainterface.DataInterfaceModel;
import com.yunzhupaas.base.model.datainterface.DataInterfacePage;
import com.yunzhupaas.base.model.flow.DataModel;
import com.yunzhupaas.base.service.*;
import com.yunzhupaas.base.util.*;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.constant.YunzhupaasConst;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.database.model.entity.DbLinkEntity;
import com.yunzhupaas.database.util.DynamicDataSourceUtil;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.flowable.entity.TemplateJsonEntity;
import com.yunzhupaas.model.ExcelColumnAttr;
import com.yunzhupaas.model.ExcelModel;
import com.yunzhupaas.model.OnlineDevData;
import com.yunzhupaas.model.visualJson.*;
import com.yunzhupaas.model.visualJson.config.ConfigModel;
import com.yunzhupaas.model.visualJson.config.RegListModel;
import com.yunzhupaas.model.visualJson.props.PropsModel;
import com.yunzhupaas.onlinedev.model.OnlineDevEnum.CacheKeyEnum;
import com.yunzhupaas.onlinedev.model.OnlineDevEnum.MultipleControlEnum;
import com.yunzhupaas.onlinedev.model.OnlineDevEnum.OnlineDataTypeEnum;
import com.yunzhupaas.onlinedev.model.OnlineDevListModel.InterefaceParamModel;
import com.yunzhupaas.onlinedev.model.OnlineInfoModel;
import com.yunzhupaas.onlinedev.model.PaginationModel;
import com.yunzhupaas.onlinedev.model.VisualErrInfo;
import com.yunzhupaas.onlinedev.model.VisualParamModel;
import com.yunzhupaas.onlinedev.service.VisualDevInfoService;
import com.yunzhupaas.onlinedev.service.VisualdevModelDataService;
import com.yunzhupaas.permission.entity.*;
import com.yunzhupaas.permission.model.authorize.AuthorizeConditionEnum;
import com.yunzhupaas.permission.model.organize.OrganizeConditionModel;
import com.yunzhupaas.permission.model.organize.OrganizeModel;
import com.yunzhupaas.permission.service.*;
import com.yunzhupaas.util.*;
import com.yunzhupaas.util.visiual.YunzhupaasKeyConsts;
import com.yunzhupaas.workflow.service.TaskApi;
import com.yunzhupaas.workflow.service.TemplateApi;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.mybatis.dynamic.sql.BasicColumn;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.SqlTable;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.QueryExpressionDSL;
import org.mybatis.dynamic.sql.select.SelectModel;
import org.mybatis.dynamic.sql.select.join.EqualTo;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 数据解析
 *
 * @author 云筑产品开发平台组
 * @version V3.4.2
 * @copyright 深圳市乐程软件有限公司（http://www.szlecheng.cn）
 * @date 2024/7/18
 */
@Slf4j
@Component
public class OnlineSwapDataUtils {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DictionaryDataService dictionaryDataApi;
    @Autowired
    private UserService userApi;
    @Autowired
    private PositionService positionApi;
    @Autowired
    private ProvinceService areaApi;
    @Autowired
    private OrganizeService organizeApi;
    @Autowired
    private OrganizeAdministratorService organizeAdministratorService;
    @Autowired
    private VisualdevService visualdevService;
    @Autowired
    private VisualdevModelDataService visualdevModelDataService;
    @Autowired
    private DataInterfaceService dataInterFaceApi;
    @Autowired
    private VisualDevInfoService visualDevInfoService;
    @Autowired
    private RoleService roleApi;
    @Autowired
    private GroupService groupApi;
    @Autowired
    private DbLinkService dataSourceApi;
    @Autowired
    private OnlineDevInfoUtils onlineDevInfoUtils;
    @Autowired
    private FlowFormDataMapper flowFormDataMapper;
    @Autowired
    private UserRelationService userRelationApi;
    @Autowired
    private OrganizeRelationService organizeRelationApi;
    @Autowired
    private FlowFormDataUtil flowDataUtil;
    @Autowired
    private OnlineExecutor executor;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private FormCheckUtils formCheckUtils;

    @Autowired
    private TemplateApi templateApi;
    @Autowired
    private TaskApi taskApi;

    public final static long DEFAULT_CACHE_TIME = 60 * 5;

    // 后期将是否缓存转到前端控件配置
    // 缓存系统权限数据, 组织、岗位、分组、角色、用户
    public final static boolean NEEDCACHE_SYS = true;
    // 缓存远端数据, 静态、字典、接口、弹窗选择
    public final static boolean NEEDCACHE_REMOTE = true;
    // 缓存关联数据, 关联表单
    public final static boolean NEEDCACHE_RELATION = true;

    public List<Map<String, Object>> getSwapList(List<Map<String, Object>> list, List<FieLdsModel> swapDataVoList,
            String visualDevId, Boolean inlineEdit) {
        if (list.isEmpty()) {
            return list;
        }
        return getSwapList(list, swapDataVoList, visualDevId, inlineEdit, null, true, null);
    }

    public List<Map<String, Object>> getSwapInfo(List<Map<String, Object>> list, List<FieLdsModel> swapDataVoList,
            String visualDevId, Boolean inlineEdit, Map<String, Object> mainAndMast) {
        if (list.isEmpty()) {
            return list;
        }
        return getSwapList(list, swapDataVoList, visualDevId, inlineEdit, null, false, mainAndMast);
    }

    public List<Map<String, Object>> getSwapList(List<Map<String, Object>> list, List<FieLdsModel> swapDataVoList,
            String visualDevId, Boolean inlineEdit,
            Map<String, Object> localCacheParent, boolean isList, Map<String, Object> mainAndMast) {
        try {
            DynamicDataSourceUtil.switchToDataSource(null);
            if (list.isEmpty()) {
                return list;
            }
            // 主表的缓存数据继续使用, 不重新初始化
            Map<String, Object> localCache = Optional.ofNullable(localCacheParent).orElse(new ConcurrentHashMap<>());
            // 初始化系统缓存
            // sysNeedSwapData(swapDataVoList, visualDevId, localCache);
            // 初始化系统缓存-多线程
            executor.executorRedis(localCache, swapDataVoList, visualDevId, inlineEdit, list, mainAndMast);
            // redis key
            String dsName = Optional.ofNullable(TenantHolder.getDatasourceId()).orElse("");
            writeRedisAndList(localCache, swapDataVoList, dsName, visualDevId, inlineEdit, list, isList, mainAndMast);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DynamicDataSourceUtil.clearSwitchDataSource();
        }
        return list;
    }

    private List<Map<String, Object>> writeRedisAndList(Map<String, Object> localCache,
            List<FieLdsModel> swapDataVoList, String dsName, String visualDevId, Boolean inlineEdit,
            List<Map<String, Object>> list, boolean isList, Map<String, Object> mainAndMast) {

        Map<String, Object> userMap = (Map<String, Object>) localCache.get("__user_map");
        Map<String, Object> orgMap = (Map<String, Object>) localCache.get("__org_map");
        Map<String, Object> posMap = (Map<String, Object>) localCache.get("__pos_map");
        Map<String, Object> orgTreeMap = (Map<String, Object>) localCache.get("__orgTree_map");
        Map<String, Object> roleMap = (Map<String, Object>) localCache.get("__role_map");
        Map<String, Object> groupMap = (Map<String, Object>) localCache.get("__group_map");

        List<Map<String, String>> proMapList = (List<Map<String, String>>) localCache.get("__pro_maplist");

        List<String> arrYunzhupaasKey = new ArrayList() {
            {
                add(YunzhupaasKeyConsts.UPLOADFZ);
                add(YunzhupaasKeyConsts.UPLOADIMG);
            }
        };
        for (int x = 0; x < list.size(); x++) {
            Map<String, Object> dataMap = list.get(x);
            if (dataMap == null) {
                dataMap = new HashMap<>();
                list.set(x, dataMap);
            }
            Map<String, Object> dataCopyMap = new HashMap<>(dataMap);
            for (FieLdsModel swapDataVo : swapDataVoList) {
                String yunzhupaasKey = swapDataVo.getConfig().getYunzhupaasKey();
                if (StringUtil.isEmpty(swapDataVo.getVModel())) {
                    continue;
                }
                String swapVModel = swapDataVo.getVModel();
                String vModel = inlineEdit && isList ? swapDataVo.getVModel() + "_name" : swapDataVo.getVModel();
                String dataType = swapDataVo.getConfig().getDataType();
                Boolean isMultiple = Objects.nonNull(swapDataVo.getMultiple()) ? swapDataVo.getMultiple() : false;

                // clob字段转换
                FormInfoUtils.swapClob(dataMap, swapDataVo.getVModel());

                try {
                    Map<String, Map<String, Object>> dataDetailMap = new HashMap<>();
                    // 关联表单获取原字段数据
                    FormPublicUtils.relationGetYunzhupaasId(dataMap, yunzhupaasKey, dataMap.get(swapVModel),
                            swapVModel);
                    if (StringUtil.isEmpty(String.valueOf(dataMap.get(swapVModel)))
                            || String.valueOf(dataMap.get(swapVModel)).equals("[]")
                            || String.valueOf(dataMap.get(swapVModel)).equals("null")) {
                        if (yunzhupaasKey.equals(YunzhupaasKeyConsts.CHILD_TABLE)) {
                            dataMap.put(vModel, new ArrayList<>());
                        } else if (arrYunzhupaasKey.contains(yunzhupaasKey)) {
                            dataMap.put(swapVModel, new ArrayList<>());
                        } else {
                            // dataCopyMap.putAll(dataMap);
                            if (inlineEdit) {
                                dataMap.put(swapVModel, null);
                            }
                            dataMap.put(vModel, null);
                        }
                        continue;
                    } else {
                        // 是否联动
                        boolean DynamicNeedCache;
                        String redisKey;
                        String separator = swapDataVo.getSeparator();
                        switch (yunzhupaasKey) {
                            case YunzhupaasKeyConsts.CALCULATE:
                            case YunzhupaasKeyConsts.NUM_INPUT:
                                Object decimalValue = dataCopyMap.get(swapDataVo.getVModel());
                                Integer precision = swapDataVo.getPrecision();
                                if (decimalValue instanceof BigDecimal) {
                                    BigDecimal bd = (BigDecimal) decimalValue;
                                    String value = bd.toPlainString();
                                    List<Integer> IntegerType = ImmutableList.of(3, 4);
                                    if (!IntegerType.contains(swapDataVo.getRoundType())) {
                                        if (precision != null && precision > 0) {
                                            String formatZ = "000000000000000";
                                            String format = formatZ.substring(0, precision);
                                            DecimalFormat decimalFormat = new DecimalFormat("0." + format);
                                            value = decimalFormat.format(bd);
                                        } else {
                                            value = String.valueOf(bd.stripTrailingZeros().toPlainString());
                                        }
                                    } else {
                                        // 向上（下）取整，去掉末尾0
                                        value = bd.stripTrailingZeros().toPlainString();
                                    }
                                    dataMap.put(vModel, value);
                                } else {
                                    dataMap.put(vModel, decimalValue);
                                }
                                break;
                            // 公司组件
                            case YunzhupaasKeyConsts.COMSELECT:
                                // 部门组件
                            case YunzhupaasKeyConsts.DEPSELECT:
                                // 所属部门
                            case YunzhupaasKeyConsts.CURRDEPT:
                                dataMap.put(vModel,
                                        OnlinePublicUtils.getDataInMethod(orgMap, dataMap.get(swapVModel), isMultiple));
                                break;
                            // 所属组织
                            case YunzhupaasKeyConsts.CURRORGANIZE:
                                // 多级组织
                                String orgIds = String.valueOf(dataMap.get(swapVModel));
                                String orgName = " ";
                                List<String> jsonToList = new ArrayList<>();
                                try {
                                    jsonToList = JsonUtil.getJsonToList(orgIds, String.class);
                                } catch (Exception e) {
                                    jsonToList.add(orgIds);
                                }
                                if (!jsonToList.isEmpty()) {
                                    if ("all".equals(swapDataVo.getShowLevel())) {
                                        orgName = orgTreeMap.get(StringUtils.join(jsonToList, ",")) != null
                                                ? orgTreeMap.get(StringUtils.join(jsonToList, ",")).toString()
                                                : "";
                                    } else {
                                        String orgId = jsonToList.get(jsonToList.size() - 1);
                                        OrganizeEntity organizeEntity = StringUtil.isNotEmpty(orgId)
                                                ? organizeApi.getInfo(orgId)
                                                : null;
                                        if (organizeEntity != null
                                                && "department".equals(organizeEntity.getCategory())) {
                                            orgName = organizeEntity.getFullName();
                                        }
                                    }
                                }
                                dataMap.put(vModel, orgName);
                                break;

                            // 岗位组件
                            case YunzhupaasKeyConsts.POSSELECT:
                                // 所属岗位
                            case YunzhupaasKeyConsts.CURRPOSITION:
                                String posData = OnlinePublicUtils.getDataInMethod(posMap, dataMap.get(swapVModel),
                                        isMultiple);
                                if (ObjectUtil.isEmpty(dataMap.get(swapVModel))) {
                                    dataMap.put(vModel, " ");
                                } else {
                                    dataMap.put(vModel, posData);
                                }
                                break;

                            // 用户组件
                            case YunzhupaasKeyConsts.USERSELECT:
                                // 创建用户
                            case YunzhupaasKeyConsts.CREATEUSER:
                                // 修改用户
                            case YunzhupaasKeyConsts.MODIFYUSER:
                                String userData = OnlinePublicUtils.getDataInMethod(userMap, dataMap.get(swapVModel),
                                        isMultiple);
                                dataMap.put(vModel, userData);
                                break;
                            case YunzhupaasKeyConsts.CUSTOMUSERSELECT:
                                List<String> dataNoSwapInMethod = OnlinePublicUtils
                                        .getDataNoSwapInMethod(dataMap.get(swapVModel));
                                StringJoiner valueJoin = new StringJoiner(",");
                                for (String data : dataNoSwapInMethod) {
                                    String id = data.contains("--") ? data.substring(0, data.lastIndexOf("--")) : data;
                                    String type = data.contains("--") ? data.substring(data.lastIndexOf("--") + 2) : "";
                                    Map<String, Object> cacheMap;
                                    switch (type) {
                                        case "role":
                                            cacheMap = roleMap;
                                            break;
                                        case "position":
                                            cacheMap = posMap;
                                            break;
                                        case "company":
                                        case "department":
                                            cacheMap = orgMap;
                                            break;
                                        case "group":
                                            cacheMap = groupMap;
                                            break;
                                        case "user":
                                        default:
                                            cacheMap = userMap;
                                            break;
                                    }
                                    valueJoin.add(Optional.ofNullable(cacheMap.get(id)).orElse("").toString());
                                }
                                dataMap.put(vModel, valueJoin.toString());
                                break;
                            // 角色选择
                            case YunzhupaasKeyConsts.ROLESELECT:
                                String roleData = OnlinePublicUtils.getDataInMethod(roleMap, dataMap.get(swapVModel),
                                        isMultiple);
                                dataMap.put(vModel, roleData);
                                break;

                            case YunzhupaasKeyConsts.GROUPSELECT:
                                String groupData = OnlinePublicUtils.getDataInMethod(groupMap, dataMap.get(swapVModel),
                                        isMultiple);
                                dataMap.put(vModel, groupData);
                                break;

                            // 省市区联动
                            case YunzhupaasKeyConsts.ADDRESS:
                                String addressValue = String.valueOf(dataMap.get(swapVModel));
                                if (OnlinePublicUtils.getMultiple(addressValue,
                                        MultipleControlEnum.MULTIPLE_JSON_TWO.getMultipleChar())) {
                                    String[][] data = JsonUtil.getJsonToBean(addressValue, String[][].class);
                                    List<String> proDataS = Arrays.stream(data)
                                            .flatMap(Arrays::stream)
                                            .collect(Collectors.toList());
                                    Map<String, String> provinceNames = provinceService.getProList(proDataS).stream()
                                            .collect(Collectors.toMap(
                                                    ProvinceEntity::getId, ProvinceEntity::getFullName, (k1, k2) -> k2,
                                                    () -> new LinkedHashMap<>(proDataS.size(), 1.0F)));
                                    List<String> addList = new ArrayList<>();
                                    for (String[] AddressData : data) {
                                        List<String> adList = new ArrayList<>();
                                        for (int i = 0; i < AddressData.length; i++) {
                                            String addressDatum = AddressData[i];
                                            String value = provinceNames.getOrDefault(addressDatum, "");
                                            adList.add(value);
                                        }
                                        addList.add(String.join("/", adList));
                                    }
                                    dataMap.put(vModel, String.join(";", addList));
                                } else if (OnlinePublicUtils.getMultiple(addressValue,
                                        MultipleControlEnum.MULTIPLE_JSON_ONE.getMultipleChar())) {
                                    List<String> proDataS = JsonUtil
                                            .getJsonToList(String.valueOf(dataMap.get(swapVModel)), String.class);
                                    Map<String, String> provinceNames = provinceService.getProList(proDataS).stream()
                                            .collect(Collectors.toMap(
                                                    ProvinceEntity::getId, ProvinceEntity::getFullName, (k1, k2) -> k2,
                                                    () -> new LinkedHashMap<>(proDataS.size(), 1.0F)));
                                    List<String> adList = new ArrayList<>();
                                    for (int i = 0; i < proDataS.size(); i++) {
                                        String addressDatum = proDataS.get(i);
                                        String value = provinceNames.getOrDefault(addressDatum, "");
                                        adList.add(value);
                                    }
                                    dataMap.put(vModel, String.join("/", adList));
                                }
                                break;
                            // 开关
                            case YunzhupaasKeyConsts.SWITCH:
                                String switchValue = String.valueOf(dataMap.get(swapVModel)).equals("1")
                                        ? swapDataVo.getActiveTxt()
                                        : swapDataVo.getInactiveTxt();
                                dataMap.put(vModel, switchValue);
                                break;

                            case YunzhupaasKeyConsts.CASCADER:
                            case YunzhupaasKeyConsts.RADIO:
                            case YunzhupaasKeyConsts.CHECKBOX:
                            case YunzhupaasKeyConsts.SELECT:
                            case YunzhupaasKeyConsts.TREESELECT:
                                if (StringUtil.isEmpty(separator)) {
                                    separator = "/";
                                }
                                if (YunzhupaasKeyConsts.CHECKBOX.equals(yunzhupaasKey)) {
                                    isMultiple = true;
                                }
                                DynamicNeedCache = swapDataVo.getConfig().getTemplateJson().size() == 0;
                                String interfacelabel = swapDataVo.getProps().getLabel() != null
                                        ? swapDataVo.getProps().getLabel()
                                        : "";
                                String interfaceValue = swapDataVo.getProps().getValue() != null
                                        ? swapDataVo.getProps().getValue()
                                        : "";
                                String interfaceChildren = swapDataVo.getProps().getChildren() != null
                                        ? swapDataVo.getProps().getChildren()
                                        : "";
                                if (DynamicNeedCache) {
                                    if (OnlineDataTypeEnum.STATIC.getType().equals(dataType)) {
                                        redisKey = String.format("%s-%s-%s", visualDevId,
                                                swapDataVo.getConfig().getRelationTable() + swapDataVo.getVModel(),
                                                OnlineDataTypeEnum.STATIC.getType());
                                    } else if (dataType.equals(OnlineDataTypeEnum.DYNAMIC.getType())) {
                                        redisKey = String.format("%s-%s-%s-%s-%s-%s", dsName,
                                                OnlineDataTypeEnum.DYNAMIC.getType(),
                                                swapDataVo.getConfig().getPropsUrl(), interfaceValue, interfacelabel,
                                                interfaceChildren);
                                    } else {
                                        redisKey = String.format("%s-%s-%s", dsName,
                                                OnlineDataTypeEnum.DICTIONARY.getType(),
                                                swapDataVo.getConfig().getDictionaryType());
                                    }
                                    Map<String, Object> cascaderMap;
                                    if (dataType.equals(OnlineDataTypeEnum.DICTIONARY.getType())) {
                                        List<Map<String, Object>> checkBoxList = (List<Map<String, Object>>) localCache
                                                .get(redisKey);
                                        cascaderMap = OnlinePublicUtils.getDataMap(checkBoxList, swapDataVo);
                                    } else {
                                        cascaderMap = (Map<String, Object>) localCache.get(redisKey);
                                    }
                                    dataMap.put(vModel, FormPublicUtils.getDataConversion(cascaderMap,
                                            dataMap.get(swapVModel), isMultiple, separator));

                                } else {
                                    List<TemplateJsonModel> templateJsonModels = JsonUtil.getJsonToList(
                                            swapDataVo.getConfig().getTemplateJson(), TemplateJsonModel.class);
                                    Map<String, String> paramMap = new HashMap<>();
                                    for (TemplateJsonModel templateJsonModel : templateJsonModels) {
                                        String relationField = Objects.isNull(templateJsonModel.getRelationField()) ? ""
                                                : templateJsonModel.getRelationField();
                                        String Field = templateJsonModel.getField();
                                        String obj = inlineEdit ? ""
                                                : Optional.ofNullable(dataCopyMap.get(relationField)).orElse("")
                                                        .toString();
                                        if (templateJsonModel.getSourceType() != null
                                                && !Objects.equals(templateJsonModel.getSourceType(), 1)) {
                                            String dataValue = paramSourceTypeReplaceValue(templateJsonModel,
                                                    dataCopyMap);
                                            paramMap.put(Field, dataValue);
                                            continue;
                                        }
                                        if (relationField.toLowerCase()
                                                .contains(YunzhupaasKeyConsts.CHILD_TABLE_PREFIX)) {
                                            String childField = relationField.split("-")[1];
                                            obj = Optional.ofNullable(dataCopyMap.get(childField)).orElse("")
                                                    .toString();
                                        } else if (mainAndMast != null) {
                                            obj = Optional.ofNullable(mainAndMast.get(relationField)).orElse("")
                                                    .toString();
                                        }
                                        paramMap.put(Field, obj);
                                    }
                                    List<Map<String, Object>> dataList = null;
                                    List<Map<String, Object>> options = new ArrayList<>();
                                    Map<String, Object> dataInterfaceMap = new HashMap();
                                    // 缓存Key 租户-远端数据-id-base64({params})
                                    redisKey = String.format("%s-%s-%s-%s", dsName,
                                            OnlineDataTypeEnum.DYNAMIC.getType(), swapDataVo.getConfig().getPropsUrl(),
                                            Base64.getEncoder().encodeToString(JsonUtil.getObjectToString(paramMap)
                                                    .getBytes(StandardCharsets.UTF_8)));
                                    if (localCache.containsKey(redisKey) || redisUtil.exists(redisKey)) {
                                        if (localCache.containsKey(redisKey)) {
                                            dataList = (List<Map<String, Object>>) localCache.get(redisKey);
                                        } else {
                                            List<Object> tmpList = redisUtil.get(redisKey, 0, -1);
                                            List<Map<String, Object>> tmpMapList = new ArrayList<>();
                                            tmpList.forEach(item -> {
                                                tmpMapList.add(JsonUtil.entityToMap(item));
                                            });
                                            dataList = tmpMapList;
                                            localCache.put(redisKey, dataList);
                                        }
                                    } else {
                                        ActionResult data = dataInterFaceApi
                                                .infoToId(swapDataVo.getConfig().getPropsUrl(), null, paramMap);
                                        if (data != null && data.getData() != null) {
                                            if (data.getData() instanceof List) {
                                                dataList = (List<Map<String, Object>>) data.getData();
                                                if (NEEDCACHE_REMOTE && CollectionUtils.isNotEmpty(dataList)
                                                        && !YunzhupaasKeyConsts.TREESELECT.equals(yunzhupaasKey)
                                                        && swapDataVo.getConfig().getUseCache()) {
                                                    redisUtil.insert(redisKey, dataList, DEFAULT_CACHE_TIME);
                                                }
                                                localCache.put(redisKey, dataList);
                                            }
                                        }
                                    }
                                    if (dataList != null) {
                                        JSONArray dataAll = JsonUtil.getListToJsonArray(dataList);
                                        treeToList(interfacelabel, interfaceValue, interfaceChildren, dataAll, options);
                                        options.stream().forEach(o -> {
                                            dataInterfaceMap.put(String.valueOf(o.get(interfaceValue)),
                                                    String.valueOf(o.get(interfacelabel)));
                                        });
                                    }
                                    dataMap.put(vModel, FormPublicUtils.getDataConversion(dataInterfaceMap,
                                            dataMap.get(swapVModel), isMultiple, separator));
                                }
                                break;
                            case YunzhupaasKeyConsts.RELATIONFORM:
                                // 取关联表单数据 按绑定功能加字段区分数据
                                redisKey = String.format("%s-%s-%s-%s-%s", dsName, YunzhupaasKeyConsts.RELATIONFORM,
                                        swapDataVo.getModelId(), swapDataVo.getRelationField(),
                                        dataMap.get(swapDataVo.getVModel()));
                                VisualdevModelDataInfoVO infoVO = null;
                                if (localCache.containsKey(redisKey) || redisUtil.exists(redisKey)) {
                                    infoVO = new VisualdevModelDataInfoVO();
                                    if (localCache.containsKey(redisKey)) {
                                        infoVO.setData(localCache.get(redisKey).toString());
                                    } else {
                                        infoVO.setData(redisUtil.getString(redisKey).toString());
                                        localCache.put(redisKey, infoVO.getData());
                                    }

                                } else {
                                    String keyId = String.valueOf(dataMap.get(swapVModel));
                                    VisualdevEntity entity = visualdevService.getInfo(swapDataVo.getModelId());
                                    String propsValue = StringUtil.isNotEmpty(swapDataVo.getPropsValue())
                                            && swapDataVo.getPropsValue()
                                                    .contains(YunzhupaasConst.FIELD_SUFFIX_YUNZHUPAASID)
                                                            ? swapDataVo.getPropsValue()
                                                                    .split(YunzhupaasConst.FIELD_SUFFIX_YUNZHUPAASID)[0]
                                                            : swapDataVo.getPropsValue();
                                    if (Objects.nonNull(entity)) {
                                        if (!StringUtil.isEmpty(entity.getVisualTables())
                                                && !OnlineDevData.TABLE_CONST.equals(entity.getVisualTables())) {
                                            infoVO = visualDevInfoService.getDetailsDataInfo(keyId, entity,
                                                    OnlineInfoModel.builder().needSwap(true).needRlationFiled(false)
                                                            .propsValue(propsValue).build());
                                        } else {
                                            infoVO = visualdevModelDataService.infoDataChange(keyId, entity);
                                        }
                                    }
                                    String data = infoVO == null ? StringUtil.EMPTY : infoVO.getData();
                                    if (NEEDCACHE_RELATION) {
                                        redisUtil.insert(redisKey, data, DEFAULT_CACHE_TIME);
                                    }
                                    localCache.put(redisKey, data);
                                }
                                if (infoVO != null && StringUtil.isNotEmpty(infoVO.getData())) {
                                    Map<String, Object> formDataMap = JsonUtil.stringToMap(infoVO.getData());
                                    String relationField = swapDataVo.getRelationField();
                                    if (formDataMap != null && formDataMap.size() > 0) {
                                        dataMap.put(swapDataVo.getVModel() + "_id", dataMap.get(swapVModel));
                                        dataMap.put(vModel, formDataMap.get(relationField));
                                        dataDetailMap.put(vModel, formDataMap);
                                    }
                                }
                                break;
                            case YunzhupaasKeyConsts.POPUPSELECT:
                            case YunzhupaasKeyConsts.POPUPTABLESELECT:
                                // 是否联动
                                List<TemplateJsonModel> templateJsonModels = JsonUtil
                                        .getJsonToList(swapDataVo.getTemplateJson(), TemplateJsonModel.class);
                                // DynamicNeedCache = templateJsonModels.size() == 0;
                                List<Map<String, Object>> mapList;
                                Map<String, Object> popMaps = new HashMap<>();
                                String value = String.valueOf(dataMap.get(swapVModel));

                                List<DataInterfaceModel> listParam = new ArrayList<>();
                                for (TemplateJsonModel templateJsonModel : templateJsonModels) {
                                    String relationField = templateJsonModel.getRelationField();
                                    DataInterfaceModel dataInterfaceModel = JsonUtil.getJsonToBean(templateJsonModel,
                                            DataInterfaceModel.class);
                                    if (templateJsonModel.getSourceType() != null
                                            && !Objects.equals(templateJsonModel.getSourceType(), 1)) {
                                        String dataValue = paramSourceTypeReplaceValue(templateJsonModel, dataCopyMap);
                                        dataInterfaceModel.setDefaultValue(dataValue);
                                        listParam.add(dataInterfaceModel);
                                        continue;
                                    }
                                    String obj = inlineEdit ? ""
                                            : Optional.ofNullable(dataCopyMap.get(relationField)).orElse("").toString();
                                    if (relationField.toLowerCase().contains(YunzhupaasKeyConsts.CHILD_TABLE_PREFIX)) {
                                        String childField = relationField.split("-")[1];
                                        obj = Optional.ofNullable(dataCopyMap.get(childField)).orElse("").toString();
                                    } else if (mainAndMast != null) {
                                        obj = Optional.ofNullable(mainAndMast.get(relationField)).orElse("").toString();
                                    }
                                    dataInterfaceModel.setDefaultValue(obj);
                                    listParam.add(dataInterfaceModel);
                                }
                                DataInterfacePage dataInterfacePage = new DataInterfacePage();
                                dataInterfacePage.setParamList(listParam);
                                dataInterfacePage.setInterfaceId(swapDataVo.getInterfaceId());
                                List<String> ids = new ArrayList<>();
                                if (value.startsWith("[")) {
                                    ids = JsonUtil.getJsonToList(value, String.class);
                                } else {
                                    ids.add(value);
                                }
                                dataInterfacePage.setIds(ids);
                                // 缓存Key 租户-远端数据-base64({id, params, ids})
                                redisKey = String.format("%s-%s-%s-%s", dsName, OnlineDataTypeEnum.DYNAMIC.getType(),
                                        swapDataVo.getInterfaceId(),
                                        Base64.getEncoder().encodeToString(JsonUtil.getObjectToString(dataInterfacePage)
                                                .getBytes(StandardCharsets.UTF_8)));
                                if (localCache.containsKey(redisKey) || redisUtil.exists(redisKey)) {
                                    if (localCache.containsKey(redisKey)) {
                                        mapList = (List<Map<String, Object>>) localCache.get(redisKey);
                                    } else {
                                        List<Object> tmpList = redisUtil.get(redisKey, 0, -1);
                                        List<Map<String, Object>> tmpMapList = new ArrayList<>();
                                        tmpList.forEach(item -> {
                                            tmpMapList.add(JsonUtil.entityToMap(item));
                                        });
                                        mapList = tmpMapList;
                                        localCache.put(redisKey, mapList);
                                    }
                                } else {
                                    dataInterfacePage.setPropsValue(swapDataVo.getPropsValue());
                                    dataInterfacePage.setRelationField(swapDataVo.getRelationField());
                                    mapList = dataInterFaceApi.infoToInfo(swapDataVo.getInterfaceId(),
                                            dataInterfacePage);
                                    if (NEEDCACHE_REMOTE && swapDataVo.getConfig().getUseCache()) {
                                        redisUtil.insert(redisKey, mapList, DEFAULT_CACHE_TIME);
                                    }
                                    localCache.put(redisKey, mapList);
                                }

                                StringJoiner stringJoiner = new StringJoiner(",");
                                List<String> popList = new ArrayList<>();
                                if (value.startsWith("[")) {
                                    popList = JsonUtil.getJsonToList(value, String.class);
                                } else {
                                    popList.add(value);
                                }
                                for (String va : popList) {
                                    if (popMaps.size() > 0) {
                                        stringJoiner.add(String.valueOf(popMaps.get(va)));
                                    } else {
                                        Map<String, Object> PopMap = mapList.stream()
                                                .filter(map -> Objects.equals(
                                                        String.valueOf(map.get(swapDataVo.getPropsValue())), va))
                                                .findFirst().orElse(new HashMap<>());
                                        if (PopMap.size() > 0) {
                                            dataMap.put(vModel + "_id", dataMap.get(swapVModel));
                                            stringJoiner.add(String.valueOf(PopMap.get(swapDataVo.getRelationField())));
                                            dataDetailMap.put(vModel, PopMap);
                                        }
                                    }
                                }
                                dataMap.put(vModel, String.valueOf(stringJoiner));
                                break;
                            case YunzhupaasKeyConsts.MODIFYTIME:
                            case YunzhupaasKeyConsts.CREATETIME:
                                // case YunzhupaasKeyConsts.TIME:
                            case YunzhupaasKeyConsts.DATE:
                                // 判断是否为时间戳格式
                                Object dateObj = dataMap.get(swapVModel);
                                LocalDateTime dateTime = LocalDateTimeUtil
                                        .of(new Date(DateTimeFormatConstant.getDateObjToLong(dateObj)));
                                String format = DateTimeFormatConstant.getFormat(swapDataVo.getFormat());

                                // if (isList && (YunzhupaasKeyConsts.MODIFYTIME.equals(yunzhupaasKey) ||
                                // YunzhupaasKeyConsts.CREATETIME.equals(yunzhupaasKey))) {
                                // format = DateTimeFormatConstant.YEAR_MOnTH_DHM;
                                // }
                                if (StringUtil.isEmpty(format)) {
                                    format = DateTimeFormatConstant.YEAR_MOnTH_DHMS;
                                }
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
                                String date = dateTimeFormatter.format(dateTime);
                                dataMap.put(vModel, date);
                                if (YunzhupaasKeyConsts.MODIFYTIME.equals(yunzhupaasKey)
                                        || YunzhupaasKeyConsts.CREATETIME.equals(yunzhupaasKey)) {
                                    dataMap.put(swapDataVo.getVModel(), date);
                                }
                                break;
                            case YunzhupaasKeyConsts.RATE:
                            case YunzhupaasKeyConsts.SLIDER:
                                // 滑块评分不需要补零转浮点型
                                Double ratevalue = Double.valueOf(0);
                                if (dataMap.get(swapVModel) != null) {
                                    ratevalue = Double.valueOf(dataMap.get(swapVModel).toString());
                                }
                                dataMap.put(vModel, ratevalue);
                                break;
                            case YunzhupaasKeyConsts.UPLOADFZ:
                            case YunzhupaasKeyConsts.UPLOADIMG:
                                // 数据传递-乱塞有bug强行置空
                                List<Map<String, Object>> fileList = new ArrayList<>();
                                try {
                                    fileList = (List) dataMap.get(swapVModel);
                                } catch (Exception e) {
                                    try {
                                        fileList = JsonUtil.getJsonToListMap(String.valueOf(dataMap.get(swapVModel)));
                                    } catch (Exception e1) {
                                        // e1.printStackTrace();
                                    }
                                    // e.printStackTrace();
                                }
                                dataMap.put(vModel, fileList);
                                break;
                            case YunzhupaasKeyConsts.LOCATION:
                                // 定位-列表取全名。
                                if (isList) {
                                    Map omap = JsonUtil.stringToMap(String.valueOf(dataMap.get(swapVModel)));
                                    dataMap.put(vModel, omap.get("fullAddress") != null ? omap.get("fullAddress") : "");
                                }
                                break;
                            case YunzhupaasKeyConsts.CHILD_TABLE:
                                List<FieLdsModel> childrens = swapDataVo.getConfig().getChildren();
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) dataMap
                                        .get(swapDataVo.getVModel());
                                List<Map<String, Object>> swapList = getSwapList(childList, childrens, visualDevId,
                                        inlineEdit, localCache, isList, dataCopyMap);
                                dataMap.put(swapDataVo.getVModel(), swapList);
                                break;
                            default:
                                dataMap.put(vModel, dataMap.get(swapVModel));
                                break;
                        }
                    }
                    // 关联选择属性
                    if (dataDetailMap.size() > 0) {
                        getDataAttr(swapDataVoList, dataMap, dataDetailMap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("在线开发转换数据错误:" + e.getMessage());
                }
            }

            // 二维码 条形码最后处理
            swapCodeDataInfo(swapDataVoList, dataMap, dataCopyMap);
        }
        if (inlineEdit && isList) {
            for (Map<String, Object> map : list) {
                // 行内编辑过滤子表
                swapDataVoList = swapDataVoList.stream().filter(s -> !s.getVModel().contains("tableField"))
                        .collect(Collectors.toList());
                onlineDevInfoUtils.getInitLineData(swapDataVoList, map);
            }
        }
        return list;
    }

    /**
     * 按sourceType替换数据接口参数
     */
    public String paramSourceTypeReplaceValue(TemplateJsonModel item, Map<String, Object> dataMap) {
        String defaultValue = "";
        if (item.getSourceType() != null) {
            switch (item.getSourceType()) {
                case 1:// 字段
                    defaultValue = item.getDefaultValue();
                    break;
                case 2:// 自定义
                    defaultValue = item.getRelationField();
                    break;
                case 3:// 为空
                    defaultValue = "";
                    break;
                case 4:// 系统参数
                    defaultValue = this.getSystemFieldValue(dataMap, item);
                    break;
                default:
                    defaultValue = item.getDefaultValue();
                    break;
            }
        } else {
            defaultValue = item.getDefaultValue();
        }
        return defaultValue;
    }

    /**
     * 获取系统参数值
     *
     * @param dataCopyMap
     * @param templateJsonModel
     * @return
     */
    private String getSystemFieldValue(Map<String, Object> dataCopyMap, TemplateJsonModel templateJsonModel) {
        UserInfo userInfo = UserProvider.getUser();
        String relationField = templateJsonModel.getRelationField();
        String dataValue;
        if (AuthorizeConditionEnum.FORMID.getCondition().equals(relationField)) {
            dataValue = String.valueOf(dataCopyMap.get(FlowFormConstant.ID));
        } else if (AuthorizeConditionEnum.USER.getCondition().equals(relationField)) {
            dataValue = userInfo.getUserId();
        } else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(relationField)) {
            List<String> subOrganizeIds = new ArrayList<>();
            if (userInfo.getSubordinateIds().size() > 0) {
                subOrganizeIds = userInfo.getSubordinateIds();
            }
            subOrganizeIds.add(userInfo.getUserId());
            dataValue = subOrganizeIds.stream().collect(Collectors.joining(","));
        } else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(relationField)) {
            String orgId1 = userInfo.getOrganizeId();
            if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
                orgId1 = userInfo.getDepartmentId();
            }
            dataValue = orgId1;
        } else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(relationField)) {
            String orgId1 = userInfo.getOrganizeId();
            if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
                orgId1 = userInfo.getDepartmentId();
            }
            List<String> underOrganizations = organizeApi.getUnderOrganizations(orgId1, false);
            underOrganizations.add(orgId1);
            dataValue = underOrganizations.stream().collect(Collectors.joining(","));
        } else if (AuthorizeConditionEnum.BRANCHMANAGEORG.getCondition().equals(relationField)) {
            List<String> orgIds1 = organizeAdministratorService.getOrganizeUserList(YunzhupaasConst.CURRENT_ORG_SUB);
            dataValue = orgIds1.stream().collect(Collectors.joining(","));
        } else {
            dataValue = templateJsonModel.getDefaultValue();
        }
        return dataValue;
    }

    /**
     * 保存需要转换的数据到redis(系统控件)
     *
     * @param swapDataVoList
     * @param visualDevId
     * @param localCache
     */
    public void sysNeedSwapData(List<FieLdsModel> swapDataVoList, String visualDevId, Map<String, Object> localCache) {
        // 公共数据
        String dsName = Optional.ofNullable(TenantHolder.getDatasourceId()).orElse("");

        String redisKey;
        try {
            boolean needUser = false, needOrg = false, needPos = false, needRole = false, needGroup = false,
                    needProvince = false;
            for (FieLdsModel swapDataVo : swapDataVoList) {
                String yunzhupaasKey = swapDataVo.getConfig().getYunzhupaasKey();
                String dataType = swapDataVo.getConfig().getDataType();
                switch (yunzhupaasKey) {
                    case YunzhupaasKeyConsts.CHILD_TABLE:
                        List<FieLdsModel> children = swapDataVo.getConfig().getChildren();
                        sysNeedSwapData(children, visualDevId, localCache);
                        break;
                    // 用户组件
                    case YunzhupaasKeyConsts.USERSELECT:
                        // 创建用户
                    case YunzhupaasKeyConsts.CREATEUSER:
                        // 修改用户
                    case YunzhupaasKeyConsts.MODIFYUSER:
                        needUser = true;
                        break;
                    // 公司组件
                    case YunzhupaasKeyConsts.COMSELECT:
                        // 部门组件
                    case YunzhupaasKeyConsts.DEPSELECT:
                        // 所属部门
                    case YunzhupaasKeyConsts.CURRDEPT:
                        // 所属组织
                    case YunzhupaasKeyConsts.CURRORGANIZE:
                        needOrg = true;
                        break;
                    // 岗位组件
                    case YunzhupaasKeyConsts.POSSELECT:
                        // 所属岗位
                    case YunzhupaasKeyConsts.CURRPOSITION:
                        needPos = true;
                        break;
                    // 角色选择
                    case YunzhupaasKeyConsts.ROLESELECT:
                        needRole = true;
                        break;
                    // 分组选择
                    case YunzhupaasKeyConsts.GROUPSELECT:
                        needGroup = true;
                        break;
                    // 用户选择组件
                    case YunzhupaasKeyConsts.CUSTOMUSERSELECT:
                        needUser = needOrg = needPos = needGroup = needRole = true;
                        break;
                    // 省市区选择组件
                    case YunzhupaasKeyConsts.ADDRESS:
                        needProvince = true;
                        break;
                    default:
                        break;
                }
                if (dataType != null) {
                    // 数据接口的数据存放
                    String label = swapDataVo.getProps().getLabel() != null ? swapDataVo.getProps().getLabel() : "";
                    String value = swapDataVo.getProps().getValue() != null ? swapDataVo.getProps().getValue() : "";
                    String children = swapDataVo.getProps().getChildren() != null ? swapDataVo.getProps().getChildren()
                            : "";
                    List<Map<String, Object>> options = new ArrayList<>();
                    if (swapDataVo.getConfig().getYunzhupaasKey().equals(YunzhupaasKeyConsts.POPUPSELECT)
                            || swapDataVo.getConfig().getYunzhupaasKey().equals(YunzhupaasKeyConsts.POPUPTABLESELECT)) {
                        label = swapDataVo.getRelationField();
                        value = swapDataVo.getPropsValue();
                    }
                    Map<String, String> dataInterfaceMap = new HashMap<>(16);
                    String finalValue = value;
                    String finalLabel = label;
                    // 静态数据
                    if (dataType.equals(OnlineDataTypeEnum.STATIC.getType())) {
                        redisKey = String.format("%s-%s-%s", visualDevId,
                                swapDataVo.getConfig().getRelationTable() + swapDataVo.getVModel(),
                                OnlineDataTypeEnum.STATIC.getType());
                        if (!localCache.containsKey(redisKey)) {
                            if (!redisUtil.exists(redisKey)) {
                                if (swapDataVo.getOptions() != null) {
                                    options = JsonUtil.getJsonToListMap(swapDataVo.getOptions());
                                    JSONArray data = JsonUtil.getListToJsonArray(options);
                                    getOptions(label, value, children, data, options);
                                } else {
                                    options = JsonUtil.getJsonToListMap(swapDataVo.getOptions());
                                }

                                options.stream().forEach(o -> {
                                    dataInterfaceMap.put(String.valueOf(o.get(finalValue)),
                                            String.valueOf(o.get(finalLabel)));
                                });
                                if (NEEDCACHE_REMOTE) {
                                    redisUtil.insert(redisKey, dataInterfaceMap, DEFAULT_CACHE_TIME);
                                }
                                localCache.put(redisKey, dataInterfaceMap);
                            } else {
                                localCache.put(redisKey, redisUtil.getMap(redisKey));
                            }
                        }
                    }
                    // 远端数据
                    if (dataType.equals(OnlineDataTypeEnum.DYNAMIC.getType())) {
                        // 联动状态下不做缓存， 具体查数据时做缓存
                        boolean dynamicIsNeedCache = swapDataVo.getConfig().getTemplateJson().size() == 0;
                        if (dynamicIsNeedCache) {
                            redisKey = String.format("%s-%s-%s-%s-%s-%s", dsName, OnlineDataTypeEnum.DYNAMIC.getType(),
                                    swapDataVo.getConfig().getPropsUrl(), value, label, children);
                            if (!localCache.containsKey(redisKey)) {
                                if (!redisUtil.exists(redisKey)) {
                                    ActionResult data = dataInterFaceApi.infoToId(swapDataVo.getConfig().getPropsUrl(),
                                            null, null);
                                    if (data != null && data.getData() != null) {
                                        List<Map<String, Object>> dataList = new ArrayList<>();
                                        if (data.getData() instanceof List) {
                                            dataList = (List<Map<String, Object>>) data.getData();
                                        }
                                        JSONArray dataAll = JsonUtil.getListToJsonArray(dataList);
                                        treeToList(label, value, children, dataAll, options);
                                        options.stream().forEach(o -> {
                                            dataInterfaceMap.put(String.valueOf(o.get(finalValue)),
                                                    String.valueOf(o.get(finalLabel)));
                                        });
                                        if (NEEDCACHE_REMOTE && CollectionUtils.isNotEmpty(dataList)
                                                && !YunzhupaasKeyConsts.TREESELECT.equals(yunzhupaasKey)
                                                && swapDataVo.getConfig().getUseCache()) {
                                            redisUtil.insert(redisKey, dataInterfaceMap, DEFAULT_CACHE_TIME);
                                        }
                                        localCache.put(redisKey, dataInterfaceMap);
                                    }
                                } else {
                                    localCache.put(redisKey, redisUtil.getMap(redisKey));
                                }
                            }
                        }
                    }
                    // 数据字典
                    if (dataType.equals(OnlineDataTypeEnum.DICTIONARY.getType())) {
                        redisKey = String.format("%s-%s-%s", dsName, OnlineDataTypeEnum.DICTIONARY.getType(),
                                swapDataVo.getConfig().getDictionaryType());
                        if (!localCache.containsKey(redisKey)) {
                            if (!redisUtil.exists(redisKey)) {
                                List<DictionaryDataEntity> list = dictionaryDataApi
                                        .getDicList(swapDataVo.getConfig().getDictionaryType());
                                options = list.stream().map(dic -> {
                                    Map<String, Object> dictionaryMap = new HashMap<>(16);
                                    dictionaryMap.put("id", dic.getId());
                                    dictionaryMap.put("enCode", dic.getEnCode());
                                    dictionaryMap.put("fullName", dic.getFullName());
                                    return dictionaryMap;
                                }).collect(Collectors.toList());
                                String dictionaryData = JsonUtil.getObjectToString(options);
                                if (NEEDCACHE_REMOTE) {
                                    redisUtil.insert(redisKey, dictionaryData, DEFAULT_CACHE_TIME);
                                }
                                localCache.put(redisKey, options);
                            } else {
                                String dictionaryStringData = redisUtil.getString(redisKey).toString();
                                localCache.put(redisKey, JsonUtil.getJsonToListMap(dictionaryStringData));
                            }
                        }
                    }
                }
            }
            // 有使用相关组件的情况才初始化数据
            if (needUser && !localCache.containsKey("__user_map")) {
                // 人员
                redisKey = dsName + CacheKeyEnum.USER.getName();
                Map<String, Object> userMap;
                if (redisUtil.exists(redisKey)) {
                    userMap = redisUtil.getMap(redisKey);
                    userMap = Optional.ofNullable(userMap).orElse(new HashMap<>(20));
                } else {
                    userMap = userApi.getUserMap();
                    if (NEEDCACHE_SYS) {
                        redisUtil.insert(redisKey, userMap, DEFAULT_CACHE_TIME);
                    }
                }
                localCache.put("__user_map", userMap);
            }
            if (needOrg && !localCache.containsKey("__org_map")) {
                // 组织
                redisKey = dsName + CacheKeyEnum.ORG.getName();
                Map<String, Object> orgMap;
                if (redisUtil.exists(redisKey)) {
                    orgMap = redisUtil.getMap(redisKey);
                    orgMap = Optional.ofNullable(orgMap).orElse(new HashMap<>(20));
                } else {
                    orgMap = organizeApi.getOrgMap();
                    if (NEEDCACHE_SYS) {
                        redisUtil.insert(redisKey, orgMap, DEFAULT_CACHE_TIME);
                    }
                }
                localCache.put("__org_map", orgMap);
            }
            /*
             * if(needOrg && !localCache.containsKey("__allOrg_map")){
             * //组织需要递归显示
             * Map<Object, Object> allOrgMap = redisUtil.getMap(dsName +
             * CacheKeyEnum.AllORG.getName());
             * allOrgMap = Optional.ofNullable(allOrgMap).orElse(new HashMap<>(20));
             * localCache.put("__allOrg_map", allOrgMap);
             * }
             */
            if (needPos && !localCache.containsKey("__pos_map")) {
                // 岗位
                redisKey = dsName + CacheKeyEnum.POS.getName();
                Map<String, Object> posMap;
                if (redisUtil.exists(redisKey)) {
                    posMap = redisUtil.getMap(redisKey);
                    posMap = Optional.ofNullable(posMap).orElse(new HashMap<>(20));
                } else {
                    posMap = positionApi.getPosMap();
                    if (NEEDCACHE_SYS) {
                        redisUtil.insert(redisKey, posMap, DEFAULT_CACHE_TIME);
                    }
                }
                localCache.put("__pos_map", posMap);
            }
            if (needRole && !localCache.containsKey("__role_map")) {
                // 角色
                redisKey = dsName + CacheKeyEnum.ROLE.getName();
                Map<String, Object> roleMap;
                if (redisUtil.exists(redisKey)) {
                    roleMap = redisUtil.getMap(redisKey);
                    roleMap = Optional.ofNullable(roleMap).orElse(new HashMap<>(20));
                } else {
                    roleMap = roleApi.getRoleMap();
                    if (NEEDCACHE_SYS) {
                        redisUtil.insert(redisKey, roleMap, DEFAULT_CACHE_TIME);
                    }
                }
                localCache.put("__role_map", roleMap);
            }
            if (needGroup && !localCache.containsKey("__group_map")) {
                // 分组
                redisKey = dsName + CacheKeyEnum.GROUP.getName();
                Map<String, Object> groupMap;
                if (redisUtil.exists(redisKey)) {
                    groupMap = redisUtil.getMap(redisKey);
                    groupMap = Optional.ofNullable(groupMap).orElse(new HashMap<>(20));
                } else {
                    groupMap = groupApi.getGroupMap();
                    if (NEEDCACHE_SYS) {
                        redisUtil.insert(redisKey, groupMap, DEFAULT_CACHE_TIME);
                    }
                }
                localCache.put("__group_map", groupMap);
            }
            if (needProvince && !localCache.containsKey("__pro_maplist")) {
                // 省市区
                Map<Object, Object> proMap = redisUtil.getMap(String.format("%s-%s-%d", dsName, "province", 1));
                List<Map<String, String>> proMapList = new ArrayList<>();
                if (proMap.size() == 0) {
                    proMapList = fillProMap(dsName);
                } else {
                    for (int i = 1; i <= 4; i++) {
                        proMapList.add(redisUtil.getMap(String.format("%s-%s-%d", dsName, "province", i)));
                    }
                }
                localCache.put("__pro_maplist", proMapList);
            }
        } catch (Exception e) {
            log.error("在线开发转换数据异常:" + e.getMessage(), e);
        }
    }

    private List<Map<String, String>> fillProMap(String dsName) {
        List<Map<String, String>> proMapList = new ArrayList<>();
        // 分级存储
        for (int i = 1; i <= 4; i++) {
            String redisKey = String.format("%s-%s-%d", dsName, "province", i);
            if (!redisUtil.exists(redisKey)) {
                List<ProvinceEntity> provinceEntityList = areaApi.getProListBytype(String.valueOf(i));
                Map<String, String> provinceMap = new HashMap<>(16);
                if (provinceEntityList != null) {
                    provinceEntityList.stream().forEach(p -> provinceMap.put(p.getId(), p.getFullName()));
                }
                proMapList.add(provinceMap);
                // 区划基本不修改 不做是否缓存判断
                redisUtil.insert(redisKey, provinceMap, RedisUtil.CAHCEWEEK);
            }
        }
        return proMapList;
    }

    /**
     * 级联递归
     *
     * @param value
     * @param label
     * @param children
     * @param data
     * @param result
     */
    public static void treeToList(String value, String label, String children, JSONArray data,
            List<Map<String, Object>> result) {
        for (int i = 0; i < data.size(); i++) {
            JSONObject ob = data.getJSONObject(i);
            Map<String, Object> tree = new HashMap<>(16);
            tree.put(value, String.valueOf(ob.get(value)));
            tree.put(label, String.valueOf(ob.get(label)));
            result.add(tree);
            if (ob.get(children) != null) {
                JSONArray childArray = ob.getJSONArray(children);
                treeToList(value, label, children, childArray, result);
            }
        }
    }

    /**
     * 递归查询
     *
     * @param label
     * @param value
     * @param Children
     * @param data
     * @param options
     */
    public static void getOptions(String label, String value, String Children, JSONArray data,
            List<Map<String, Object>> options) {
        for (int i = 0; i < data.size(); i++) {
            JSONObject ob = data.getJSONObject(i);
            Map<String, Object> tree = new HashMap<>(16);
            tree.put(value, String.valueOf(ob.get(value)));
            tree.put(label, String.valueOf(ob.get(label)));
            options.add(tree);
            if (ob.get(Children) != null) {
                JSONArray childrenArray = ob.getJSONArray(Children);
                getOptions(label, value, Children, childrenArray, options);
            }
        }
    }

    /**
     * 生成关联属性（弹窗选择属性,关联表单属性）
     *
     * @param fieLdsModelList
     * @param dataMap
     * @param dataDetailMap
     */
    private static void getDataAttr(List<FieLdsModel> fieLdsModelList, Map<String, Object> dataMap,
            Map<String, Map<String, Object>> dataDetailMap) {
        for (FieLdsModel fieLdsModel : fieLdsModelList) {
            if (ObjectUtil.isEmpty(fieLdsModel)) {
                continue;
            }
            ConfigModel config = fieLdsModel.getConfig();
            String yunzhupaasKey = config.getYunzhupaasKey();
            if (yunzhupaasKey.equals(YunzhupaasKeyConsts.RELATIONFORM_ATTR)
                    || yunzhupaasKey.equals(YunzhupaasKeyConsts.POPUPSELECT_ATTR)) {
                // 0展示数据 ? 1存储数据
                boolean isShow = fieLdsModel.getIsStorage() == 0;
                if (isShow) {
                    String relationField = fieLdsModel.getRelationField();
                    if (relationField.contains("_yunzhupaasTable_")) {
                        relationField = relationField.split("_yunzhupaasTable_")[0];
                    }
                    String showField = fieLdsModel.getShowField();
                    Map<String, Object> formDataMap = dataDetailMap.get(relationField);
                    if (formDataMap != null) {
                        dataMap.put(relationField + "_" + showField, formDataMap.get(showField));
                    }
                }
            }
        }
    }

    /**
     * 二维码 条形码详情数据
     *
     * @param codeList    控件集合
     * @param swapDataMap 转换后的数据
     * @param dataMap     转换前
     * @return
     */
    public static void swapCodeDataInfo(List<FieLdsModel> codeList, Map<String, Object> swapDataMap,
            Map<String, Object> dataMap) {
        for (FieLdsModel formModel : codeList) {
            String yunzhupaasKey = formModel.getConfig().getYunzhupaasKey();
            if (yunzhupaasKey.equals(YunzhupaasKeyConsts.QR_CODE)
                    || yunzhupaasKey.equals(YunzhupaasKeyConsts.BARCODE)) {
                String codeDataType = formModel.getDataType();
                if (OnlineDataTypeEnum.RELATION.getType().equals(codeDataType)) {
                    String relationFiled = formModel.getRelationField();
                    if (StringUtil.isNotEmpty(relationFiled)) {
                        Object relationValue = dataMap.get(relationFiled);
                        if (ObjectUtil.isNotEmpty(relationValue)) {
                            swapDataMap.put(relationFiled + "_id", relationValue);
                        }
                    }
                }
            }
        }
    }

    public ExcelImportModel createExcelData(List<Map<String, Object>> dataList, VisualDevJsonModel visualJsonModel,
            VisualdevEntity visualdevEntity) throws WorkFlowException {
        ExcelImportModel excelImportModel = new ExcelImportModel();
        Integer primaryKeyPolicy = visualJsonModel.getFormData().getPrimaryKeyPolicy();

        String uploaderTemplateJson = visualJsonModel.getColumnData().getUploaderTemplateJson();
        UploaderTemplateModel uploaderTemplateModel = JsonUtil.getJsonToBean(uploaderTemplateJson,
                UploaderTemplateModel.class);
        String dataType = uploaderTemplateModel.getDataType();
        ImportFormCheckUniqueModel uniqueModel = new ImportFormCheckUniqueModel();
        uniqueModel.setMain(true);
        uniqueModel.setDbLinkId(visualJsonModel.getDbLinkId());
        uniqueModel.setUpdate(dataType.equals("2"));
        uniqueModel.setPrimaryKeyPolicy(primaryKeyPolicy);
        uniqueModel.setLogicalDelete(visualJsonModel.getFormData().getLogicalDelete());
        uniqueModel.setTableModelList(visualJsonModel.getVisualTables());
        DbLinkEntity linkEntity = dataSourceApi.getInfo(visualJsonModel.getDbLinkId());
        uniqueModel.setLinkEntity(linkEntity);
        // 流程表单导入，传流程大id查询小idlist用于过滤数据
        String mainFlowID = null;
        if (StringUtil.isNotEmpty(visualJsonModel.getFlowId())) {
            List<TemplateJsonEntity> flowVersionIds = templateApi.getFlowIdsByTemplate(visualJsonModel.getFlowId());
            uniqueModel.setFlowId(visualJsonModel.getFlowId());
            uniqueModel.setFlowIdList(
                    flowVersionIds.stream().map(TemplateJsonEntity::getId).distinct().collect(Collectors.toList()));
            mainFlowID = flowVersionIds.stream().filter(t -> Objects.equals(t.getState(), 1)).findFirst()
                    .orElse(new TemplateJsonEntity()).getId();
        }

        // 获取缓存
        Map<String, Object> localCache = getlocalCache();
        List<Map<String, Object>> failResult = new ArrayList<>();

        List<VisualdevModelDataInfoVO> dataInfo = new ArrayList<>();
        try {
            for (int i = 0, len = dataList.size(); i < len; i++) {
                Map<String, Object> data = dataList.get(i);
                // 导入时默认第一个流程
                data.put(FlowFormConstant.FLOWID, mainFlowID);
                Map<String, Object> resultMap = new HashMap<>(data);
                StringJoiner errInfo = new StringJoiner(",");
                Map<String, Object> errorMap = new HashMap<>(data);

                List<String> errList = this.checkExcelData(visualJsonModel.getFormListModels(), data, localCache,
                        resultMap, errorMap, uniqueModel);

                // 业务主键判断--导入新增或者跟新
                VisualErrInfo visualErrInfo;
                try {
                    DynamicDataSourceUtil.switchToDataSource(linkEntity);
                    visualErrInfo = formCheckUtils.checkBusinessKey(visualJsonModel.getFormListModels(), resultMap,
                            visualJsonModel.getVisualTables(), visualJsonModel.getFormData(), null);
                } finally {
                    DynamicDataSourceUtil.clearSwitchDataSource();
                }

                if (uniqueModel.isUpdate()) {
                    if (ObjectUtil.isNotEmpty(visualErrInfo) && StringUtil.isNotEmpty(visualErrInfo.getId())) {
                        uniqueModel.setId(visualErrInfo.getId());
                        // 判断流程是否已发起
                        if (StringUtil.isNotEmpty(visualErrInfo.getFlowTaskId())) {
                            String finalTaskId = visualErrInfo.getFlowTaskId();
                            List<String> flowIdList = new ArrayList<>();
                            flowIdList.add(finalTaskId);
                            List<TaskEntity> tasks = taskApi.getInfosSubmit(flowIdList.toArray(new String[] {}),
                                    TaskEntity::getStatus, TaskEntity::getId);
                            if (tasks.size() > 0) {
                                boolean errorMsg = tasks.stream().filter(t -> Objects.equals(t.getStatus(), 0))
                                        .count() == 0;
                                String msg = "已发起流程，导入失败";
                                if (errorMsg) {
                                    errorMap.put("errorsInfo", msg);
                                    failResult.add(errorMap);
                                    continue;
                                }
                            }
                        }
                    }
                } else {
                    if (ObjectUtil.isNotEmpty(visualErrInfo) && StringUtil.isNotEmpty(visualErrInfo.getErrMsg())) {
                        errorMap.put("errorsInfo", visualErrInfo.getErrMsg());
                        failResult.add(errorMap);
                        continue;
                    }
                }
                this.checkUnique(visualJsonModel.getFormListModels(), data, errList, uniqueModel);

                errList.stream().forEach(t -> {
                    if (StringUtil.isNotEmpty(t)) {
                        errInfo.add(t);
                    }
                });
                if (errInfo.length() > 0) {
                    errorMap.put("errorsInfo", errInfo.toString());
                    failResult.add(errorMap);
                } else {
                    VisualdevModelDataInfoVO infoVO = new VisualdevModelDataInfoVO();

                    if (StringUtil.isNotEmpty(uniqueModel.getId())) {
                        visualdevModelDataService.visualUpdate(
                                VisualParamModel.builder().visualdevEntity(visualdevEntity).data(resultMap)
                                        .id(uniqueModel.getId()).isUpload(true).build());
                        infoVO.setId(uniqueModel.getId());
                        infoVO.setIntegrateId(uniqueModel.getId());
                        infoVO.setData(JsonUtil.getObjectToString(resultMap));
                    } else {
                        DataModel dataModel = visualdevModelDataService.visualCreate(
                                VisualParamModel.builder().visualdevEntity(visualdevEntity).data(resultMap)
                                        .isUpload(true).build());
                        infoVO.setId(dataModel.getMainId());
                        infoVO.setData(JsonUtil.getObjectToString(resultMap));
                    }
                    dataInfo.add(infoVO);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new WorkFlowException(MsgCode.IMP004.get());
        } finally {
            DynamicDataSourceUtil.clearSwitchDataSource();
        }
        excelImportModel.setFnum(failResult.size());
        excelImportModel.setSnum(dataList.size() - failResult.size());
        excelImportModel.setResultType(failResult.size() > 0 ? 1 : 0);
        excelImportModel.setFailResult(failResult);
        excelImportModel.setDataInfoList(dataInfo);
        return excelImportModel;
    }

    /**
     * 获取系统控件缓存数据
     */
    public Map<String, Object> getlocalCache() {
        Map<String, Object> localCache = new HashMap<>();
        // 读取系统控件 所需编码 id
        Map<String, Object> depMap = organizeApi.getOrgEncodeAndName("department");
        localCache.put("_dep_map", depMap);
        Map<String, Object> comMap = organizeApi.getOrgNameAndId("");
        localCache.put("_com_map", comMap);
        Map<String, Object> posMap = positionApi.getPosEncodeAndName();
        localCache.put("_pos_map", posMap);
        Map<String, Object> userMap = userApi.getUserNameAndIdMap();
        localCache.put("_user_map", userMap);
        Map<String, Object> roleMap = roleApi.getRoleNameAndIdMap();
        localCache.put("_role_map", roleMap);
        Map<String, Object> groupMap = groupApi.getGroupEncodeMap();
        localCache.put("_group_map", groupMap);
        Map<String, Object> allOrgsTreeName = organizeApi.getAllOrgsTreeName();
        localCache.put("_com_tree_map", allOrgsTreeName);

        Map<String, String> orgIdNameMaps = organizeApi.getInfoList();
        List<String> idAll = new ArrayList<>();
        List<String> orgList = orgList(YunzhupaasConst.CURRENT_ORG_TYPE, false, orgIdNameMaps);
        localCache.put("_org_list", orgList);
        List<String> orgSubList = orgList(YunzhupaasConst.CURRENT_ORG_SUB_TYPE, false, orgIdNameMaps);
        localCache.put("_orgSub_list", orgSubList);
        List<String> gradeList = orgList(YunzhupaasConst.CURRENT_GRADE_TYPE, false, orgIdNameMaps);
        localCache.put("_grade_list", gradeList);
        List<String> orgListStr = orgList(YunzhupaasConst.CURRENT_ORG_TYPE, true, orgIdNameMaps);
        localCache.put("_org_listStr", orgListStr);
        List<String> orgSubListStr = orgList(YunzhupaasConst.CURRENT_ORG_SUB_TYPE, true, orgIdNameMaps);
        localCache.put("_orgSub_listStr", orgSubListStr);
        List<String> gradeListStr = orgList(YunzhupaasConst.CURRENT_GRADE_TYPE, true, orgIdNameMaps);
        localCache.put("_grade_listStr", gradeListStr);
        idAll.addAll(orgList);
        idAll.addAll(orgSubList);
        idAll.addAll(gradeList);
        List<OrganizeRelationEntity> relationList = organizeRelationApi.getRelationListByOrganizeId(idAll, "");
        List<UserRelationEntity> listByObjectIdAll = userRelationApi.getListByObjectIdAll(idAll);
        for (UserRelationEntity userRelationEntity : listByObjectIdAll) {
            OrganizeRelationEntity model = new OrganizeRelationEntity();
            model.setObjectType(PermissionConst.USER);
            model.setOrganizeId(userRelationEntity.getObjectId());
            model.setObjectId(userRelationEntity.getUserId());
            relationList.add(model);
        }
        localCache.put("_relation_list", relationList);
        return localCache;
    }

    /**
     * 获取组织id
     *
     * @param type
     * @param isTree true 返回【xxx,xxx】json树形列表 | false 返回 xxx 最后组织id列表
     * @return
     */
    public List<String> orgList(String type, boolean isTree, Map<String, String> orgIdNameMaps) {
        List<String> org = new ArrayList() {
            {
                add(type);
            }
        };
        OrganizeConditionModel orgType = new OrganizeConditionModel();
        orgType.setDepartIds(org);
        orgType.setOrgIdNameMaps(orgIdNameMaps);
        List<String> orgList = new ArrayList<>();
        List<OrganizeModel> orgIdsList = organizeRelationApi.getOrgIdsList(orgType);
        for (OrganizeModel organizeModel : orgIdsList) {
            if (isTree) {
                List<String> treeList = StringUtil.isNotEmpty(organizeModel.getOrganizeIdTree())
                        ? Arrays.asList(organizeModel.getOrganizeIdTree().split(","))
                        : new ArrayList<>();
                orgList.add(JsonUtil.getListToJsonArray(treeList).toJSONString());
            } else {
                orgList.add(organizeModel.getId());
            }
        }
        return orgList;
    }

    public List<String> checkExcelData(List<FieLdsModel> modelList, Map<String, Object> data,
            Map<String, Object> localCache, Map<String, Object> insMap,
            Map<String, Object> errorMap, ImportFormCheckUniqueModel uniqueModel) {
        List<String> errList = new ArrayList<>(modelList.size());
        try {
            UserInfo userInfo = UserProvider.getUser();
            UserEntity userEntity = userApi.getInfo(userInfo.getUserId());

            // 读取系统控件 所需编码 id
            Map<String, Object> depMap = (Map<String, Object>) localCache.get("_dep_map");
            Map<String, Object> comMap = (Map<String, Object>) localCache.get("_com_map");
            Map<String, Object> posMap = (Map<String, Object>) localCache.get("_pos_map");
            Map<String, Object> userMap = (Map<String, Object>) localCache.get("_user_map");
            Map<String, Object> roleMap = (Map<String, Object>) localCache.get("_role_map");
            Map<String, Object> groupMap = (Map<String, Object>) localCache.get("_group_map");
            Map<String, Object> allOrgsTreeName = (Map<String, Object>) localCache.get("_com_tree_map");

            List<String> orgList = (List<String>) localCache.get("_org_list");
            List<String> orgSubList = (List<String>) localCache.get("_orgSub_list");
            List<String> gradeList = (List<String>) localCache.get("_grade_list");
            List<String> orgListStr = (List<String>) localCache.get("_org_listStr");
            List<String> orgSubListStr = (List<String>) localCache.get("_orgSub_listStr");
            List<String> gradeListStr = (List<String>) localCache.get("_grade_listStr");
            List<OrganizeRelationEntity> relationListAll = (List<OrganizeRelationEntity>) localCache
                    .get("_relation_list");

            // 异常数据
            for (int i = 0; i < modelList.size(); i++) {
                FieLdsModel swapDataVo = modelList.get(i);
                errList.add(i, "");
                try {
                    String yunzhupaasKey = swapDataVo.getConfig().getYunzhupaasKey();
                    String dataType = swapDataVo.getConfig().getDataType();
                    Object valueO = data.get(swapDataVo.getVModel());
                    String label = swapDataVo.getConfig().getLabel();
                    // 不支持导入控件
                    if (YunzhupaasKeyConsts.getUploadMaybeNull().contains(yunzhupaasKey)) {
                        insMap.put(swapDataVo.getVModel(), null);
                        continue;
                    }
                    // 是否必填
                    boolean required = swapDataVo.getConfig().isRequired();
                    if (valueO == null || "null".equals(valueO) || StringUtil.isEmpty(String.valueOf(valueO))) {
                        if (required) {
                            errList.set(i, label + "不能为空");
                        }
                        continue;
                    }
                    String value = String.valueOf(valueO);
                    if (StringUtil.isEmpty(value)) {
                        continue;
                    }
                    Boolean multiple = swapDataVo.getMultiple();
                    if (YunzhupaasKeyConsts.CHECKBOX.equals(yunzhupaasKey)) {
                        multiple = true;
                    }
                    if (YunzhupaasKeyConsts.CASCADER.equals(yunzhupaasKey)) {
                        multiple = swapDataVo.getMultiple();
                    }

                    boolean valueMul = value.contains(",");
                    value = value.trim();
                    List<String> valueList = valueMul ? Arrays.asList(value.split(",")) : new ArrayList<>();
                    if (!valueMul) {
                        valueList.add(value);
                    }
                    String ableIds = swapDataVo.getAbleIds() != null ? swapDataVo.getAbleIds() : "[]";
                    OnlineCusCheckModel cusCheckModel = AbleUtil.ableModel(ableIds, yunzhupaasKey);
                    List<String> ableSystemIds = cusCheckModel.getAbleSystemIds();
                    List<String> idList = new ArrayList<>();
                    List<String> idStr = new ArrayList<>();
                    List<String> orgUserList = new ArrayList<>();
                    for (String systemId : ableSystemIds) {
                        if (YunzhupaasConst.CURRENT_ORG_TYPE.equals(systemId)
                                || YunzhupaasConst.CURRENT_ORG.equals(systemId)) {
                            idList.addAll(orgList);
                            idStr.addAll(orgListStr);
                            orgUserList.addAll(orgList);
                        }
                        if (YunzhupaasConst.CURRENT_GRADE_TYPE.equals(systemId)
                                || YunzhupaasConst.CURRENT_GRADE.equals(systemId)) {
                            idList.addAll(gradeList);
                            idStr.addAll(gradeListStr);
                            orgUserList.addAll(gradeList);
                        }
                        if (YunzhupaasConst.CURRENT_ORG_SUB_TYPE.equals(systemId)
                                || YunzhupaasConst.CURRENT_ORG_SUB.equals(systemId)) {
                            idList.addAll(orgSubList);
                            idStr.addAll(orgSubListStr);
                            orgUserList.addAll(orgSubList);
                        }
                    }
                    cusCheckModel.getAbleComIds().addAll(idList);
                    cusCheckModel.getAbleDepIds().addAll(idList);
                    cusCheckModel.getAbleComIdsStr().addAll(idStr);
                    List<OrganizeRelationEntity> relationList = relationListAll.stream()
                            .filter(t -> orgUserList.contains(t.getOrganizeId())).collect(Collectors.toList());
                    Map<String, List<OrganizeRelationEntity>> relationMap = relationList.stream()
                            .collect(Collectors.groupingBy(OrganizeRelationEntity::getObjectType));
                    for (String key : relationMap.keySet()) {
                        List<String> list = relationMap.get(key).stream().map(OrganizeRelationEntity::getObjectId)
                                .collect(Collectors.toList());
                        for (String objectId : list) {
                            if (PermissionConst.ROLE.equalsIgnoreCase(key)) {
                                cusCheckModel.getAbleRoleIds().add(objectId);
                                cusCheckModel.getAbleIds().add(objectId + "--" + PermissionConst.ROLE.toLowerCase());
                            }
                            if (PermissionConst.POSITION.equalsIgnoreCase(key)) {
                                cusCheckModel.getAblePosIds().add(objectId);
                                cusCheckModel.getAbleIds()
                                        .add(objectId + "--" + PermissionConst.POSITION.toLowerCase());
                            }
                            if (PermissionConst.USER.equalsIgnoreCase(key)) {
                                cusCheckModel.getAbleUserIds().add(objectId);
                                cusCheckModel.getAbleIds().add(objectId + "--" + PermissionConst.USER.toLowerCase());
                            }
                            if (PermissionConst.GROUP.equalsIgnoreCase(key)) {
                                cusCheckModel.getAbleGroupIds().add(objectId);
                                cusCheckModel.getAbleIds().add(objectId + "--" + PermissionConst.GROUP.toLowerCase());
                            }
                            if (PermissionConst.DEPARTMENT.equalsIgnoreCase(key)) {
                                cusCheckModel.getAbleDepIds().add(objectId);
                                cusCheckModel.getAbleIds()
                                        .add(objectId + "--" + PermissionConst.DEPARTMENT.toLowerCase());
                            }
                            if (PermissionConst.ORGANIZE.equalsIgnoreCase(key)) {
                                cusCheckModel.getAbleComIds().add(objectId);
                                cusCheckModel.getAbleIds()
                                        .add(objectId + "--" + PermissionConst.ORGANIZE.toLowerCase());
                            }
                        }
                    }
                    cusCheckModel.setControlType(yunzhupaasKey);
                    List<String> dataList;
                    switch (yunzhupaasKey) {
                        case YunzhupaasKeyConsts.NUM_INPUT:
                            String regNum = "-?\\d+(\\.\\d+)?";
                            if (StringUtil.isNotEmpty(value) && !value.matches(regNum)) {
                                errList.set(i, label + "值不正确");
                                break;
                            }
                            // 有精度，验证精度
                            BigDecimal valueDecimal = null;
                            try {
                                valueDecimal = new BigDecimal(value);
                            } catch (Exception e) {
                            }
                            if (valueDecimal == null) {
                                errList.set(i, label + "值不正确");
                                break;
                            }
                            int configPrecision = swapDataVo.getPrecision() == null ? 0 : swapDataVo.getPrecision();
                            if (valueDecimal.scale() > configPrecision) {
                                errList.set(i, label + "值的精度不正确");
                                break;
                            }
                            if (swapDataVo.getMin() != null) {
                                if (valueDecimal.compareTo(new BigDecimal(swapDataVo.getMin())) < 0) {
                                    errList.set(i, label + "值不能小于最小值");
                                    break;
                                }
                            }
                            if (swapDataVo.getMax() != null) {
                                if (valueDecimal.compareTo(new BigDecimal(swapDataVo.getMax())) > 0) {
                                    errList.set(i, label + "值不能大于最大值");
                                    break;
                                }
                            }
                            break;
                        /**
                         * 高级控件
                         */
                        case YunzhupaasKeyConsts.COMSELECT:
                            if (!multiple && valueList.size() > 1) {
                                errList.set(i, label + "值不正确");
                                break;
                            }
                            // 验证值是否正确
                            List<List<String>> comTwoList = new ArrayList<>();
                            List<String> comOneList = new ArrayList<>();
                            boolean comErrorHapen = false;
                            for (String comValue : valueList) {
                                if (StringUtil.isEmpty(comValue)) {
                                    errList.set(i, label + "值不正确");
                                    comErrorHapen = true;
                                    break;
                                }
                                boolean find = false;
                                for (String key : allOrgsTreeName.keySet()) {
                                    Object o = allOrgsTreeName.get(key);
                                    if (comValue.equals(o.toString())) {
                                        String[] split = key.split(",");
                                        comOneList.addAll(Arrays.asList(split));
                                        comTwoList.add(Arrays.asList(split));
                                        find = true;
                                        break;
                                    }
                                }
                                if (!find) {
                                    errList.set(i, label + "值不正确");
                                    comErrorHapen = true;
                                    break;
                                }
                            }
                            if (comErrorHapen) {
                                break;
                            }
                            // 判断是否是可选范围
                            insMap.put(swapDataVo.getVModel(), !multiple ? JsonUtil.getObjectToString(comOneList)
                                    : JsonUtil.getObjectToString(comTwoList));
                            if ("custom".equals(swapDataVo.getSelectType())) {
                                List<String> strList = new ArrayList<>();
                                for (List<String> strings : comTwoList) {
                                    strList.add(JsonUtil.getListToJsonArray(strings).toJSONString());
                                }
                                cusCheckModel.setDataList(strList);
                                checkCustomControl(cusCheckModel, errList, i, label);
                            }
                            break;
                        case YunzhupaasKeyConsts.DEPSELECT:
                            dataList = checkOptionsControl(multiple, insMap, swapDataVo.getVModel(), label, depMap,
                                    valueList, errList, i);
                            if (dataList.size() == valueList.size() && swapDataVo.getSelectType().equals("custom")) {
                                cusCheckModel.setDataList(dataList);
                                checkCustomControl(cusCheckModel, errList, i, label);
                            }
                            break;
                        case YunzhupaasKeyConsts.POSSELECT:
                            dataList = checkOptionsControl(multiple, insMap, swapDataVo.getVModel(), label, posMap,
                                    valueList, errList, i);
                            if (dataList.size() == valueList.size() && swapDataVo.getSelectType().equals("custom")) {
                                cusCheckModel.setDataList(dataList);
                                checkCustomControl(cusCheckModel, errList, i, label);
                            }
                            break;
                        case YunzhupaasKeyConsts.USERSELECT:
                            dataList = checkOptionsControl(multiple, insMap, swapDataVo.getVModel(), label, userMap,
                                    valueList, errList, i);
                            if (dataList.size() == valueList.size() && swapDataVo.getSelectType().equals("custom")) {
                                cusCheckModel.setDataList(dataList);
                                checkCustomControl(cusCheckModel, errList, i, label);
                            }
                            break;
                        case YunzhupaasKeyConsts.CUSTOMUSERSELECT:
                            boolean cusUserErrorHapen = false;
                            if (!multiple) {
                                // 非多选填入多选值
                                if (valueList.size() > 1) {
                                    cusUserErrorHapen = true;
                                    errList.set(i, label + "值不正确");
                                }
                            }
                            if (!cusUserErrorHapen) {
                                boolean cusUserErrorHapen1 = false;
                                List<String> cusUserList = new ArrayList<>();
                                for (String va : valueList) {
                                    if (StringUtil.isEmpty(va)) {
                                        cusUserErrorHapen1 = true;
                                        break;
                                    }
                                    String type = null;
                                    String id = null;
                                    if (groupMap.get(va) != null) {
                                        type = "group";
                                        id = groupMap.get(va).toString();
                                    } else if (roleMap.get(va) != null) {
                                        type = "role";
                                        id = roleMap.get(va).toString();
                                    } else if (depMap.get(va) != null) {
                                        type = "department";
                                        id = depMap.get(va).toString();
                                    } else if (comMap.get(va) != null) {
                                        type = "company";
                                        id = comMap.get(va).toString();
                                    } else if (posMap.get(va) != null) {
                                        type = "position";
                                        id = posMap.get(va).toString();
                                    } else if (userMap.get(va) != null) {
                                        type = "user";
                                        id = userMap.get(va).toString();
                                    }
                                    if (type == null && id == null) {
                                        cusUserErrorHapen1 = true;
                                    } else {
                                        String lastCusId = id + "--" + type;
                                        cusUserList.add(lastCusId);
                                    }
                                }
                                if (cusUserErrorHapen1) {
                                    errList.set(i, label + "值不正确");
                                } else {
                                    insMap.put(swapDataVo.getVModel(),
                                            !multiple ? cusUserList.get(0) : JsonUtil.getObjectToString(cusUserList));
                                    if (swapDataVo.getSelectType().equals("custom")) {
                                        cusCheckModel.setDataList(cusUserList);
                                        checkCustomControl(cusCheckModel, errList, i, label);
                                    }
                                }
                            }
                            break;
                        case YunzhupaasKeyConsts.ROLESELECT:
                            dataList = checkOptionsControl(multiple, insMap, swapDataVo.getVModel(), label, roleMap,
                                    valueList, errList, i);
                            if (dataList.size() == valueList.size() && swapDataVo.getSelectType().equals("custom")) {
                                cusCheckModel.setDataList(dataList);
                                checkCustomControl(cusCheckModel, errList, i, label);
                            }
                            break;
                        case YunzhupaasKeyConsts.GROUPSELECT:
                            dataList = checkOptionsControl(multiple, insMap, swapDataVo.getVModel(), label, groupMap,
                                    valueList, errList, i);
                            if (dataList.size() == valueList.size() && swapDataVo.getSelectType().equals("custom")) {
                                cusCheckModel.setDataList(dataList);
                                checkCustomControl(cusCheckModel, errList, i, label);
                            }
                            break;
                        case YunzhupaasKeyConsts.ADDRESS:
                            if (!multiple && valueList.size() > 1) {
                                errList.set(i, label + "值不正确");
                                break;
                            }
                            boolean errorHapen = false;
                            valueList = Arrays.asList(value.split(","));
                            List<String[]> addresss = new ArrayList<>();
                            List<String> addressList1 = new ArrayList<>();
                            for (String va : valueList) {
                                if (StringUtil.isEmpty(va)) {
                                    errList.set(i, label + "值不正确");
                                    errorHapen = true;
                                    break;
                                }
                                String[] addressSplit = va.split("/");
                                if (addressSplit.length != swapDataVo.getLevel() + 1) {
                                    errList.set(i, label + "值的格式不正确");
                                    errorHapen = true;
                                    break;
                                }
                                List<String> addressJoined = new ArrayList<>();
                                List<String> addressParentID = new ArrayList<>();
                                for (String add : addressSplit) {
                                    ProvinceEntity PRO = areaApi.getInfo(add, addressParentID);
                                    if (PRO == null) {
                                        errList.set(i, label + "值不正确");
                                        errorHapen = true;
                                        break;
                                    } else {
                                        addressJoined.add(PRO.getId());
                                        addressParentID.add(PRO.getId());
                                    }
                                }
                                if (errorHapen) {
                                    break;
                                }
                                addressList1.addAll(addressJoined);
                                addresss.add(addressJoined.toArray(new String[addressJoined.size()]));
                            }
                            if (errorHapen) {
                                break;
                            }
                            insMap.put(swapDataVo.getVModel(), multiple ? JsonUtil.getObjectToString(addresss)
                                    : JsonUtil.getObjectToString(addressList1));
                            break;
                        /**
                         * 系统控件
                         */
                        case YunzhupaasKeyConsts.CURRORGANIZE:
                            List<UserRelationEntity> OrgRelations = userRelationApi
                                    .getListByUserId(userInfo.getUserId(), PermissionConst.ORGANIZE);
                            insMap.put(swapDataVo.getVModel(),
                                    OrgRelations.size() > 0 ? OrgRelations.get(0).getObjectId() : null);
                            break;
                        case YunzhupaasKeyConsts.CURRDEPT:
                            List<UserRelationEntity> depUserRelations = userRelationApi
                                    .getListByUserId(userInfo.getUserId(), PermissionConst.DEPARTMENT);
                            insMap.put(swapDataVo.getVModel(),
                                    depUserRelations.size() > 0 ? depUserRelations.get(0).getObjectId() : null);
                            break;
                        case YunzhupaasKeyConsts.CREATEUSER:
                            insMap.put(swapDataVo.getVModel(), userEntity.getId());
                            break;
                        case YunzhupaasKeyConsts.CREATETIME:
                            insMap.put(swapDataVo.getVModel(), DateUtil.getNow());
                            break;
                        case YunzhupaasKeyConsts.MODIFYTIME:
                            break;
                        case YunzhupaasKeyConsts.MODIFYUSER:
                            break;
                        case YunzhupaasKeyConsts.CURRPOSITION:
                            insMap.put(swapDataVo.getVModel(), userEntity.getPositionId());
                            break;
                        /**
                         * 基础控件
                         */
                        case YunzhupaasKeyConsts.SWITCH:
                            String activeTxt = swapDataVo.getActiveTxt();
                            String inactiveTxt = swapDataVo.getInactiveTxt();
                            if (value.equals(activeTxt)) {
                                insMap.put(swapDataVo.getVModel(), 1);
                            } else if (value.equals(inactiveTxt)) {
                                insMap.put(swapDataVo.getVModel(), 0);
                            } else {
                                errList.set(i, label + "值不正确");
                            }
                            break;
                        case YunzhupaasKeyConsts.RATE:
                            Double ratevalue = null;
                            try {
                                ratevalue = Double.valueOf(value);
                                if (ratevalue == null) {
                                    errList.set(i, label + "值不正确");
                                    break;
                                }
                            } catch (Exception e) {
                                errList.set(i, label + "值不正确");
                                break;
                            }
                            Double maxvalue = Double.valueOf(0);
                            if (swapDataVo.getCount() != -1) {
                                maxvalue = Double.valueOf(swapDataVo.getCount());
                            }
                            if (ratevalue > maxvalue) {
                                errList.set(i, label + "值不能大于最大值");
                                break;
                            }
                            if (swapDataVo.getAllowhalf()) {
                                if (ratevalue % 0.5 != 0 || ratevalue < 0) {
                                    errList.set(i, label + "值不正确");
                                }
                            } else {
                                if (ratevalue % 1 != 0 || ratevalue < 0) {
                                    errList.set(i, label + "值不正确");
                                }
                            }
                            insMap.put(swapDataVo.getVModel(), ratevalue);
                            break;
                        case YunzhupaasKeyConsts.SLIDER:
                            BigDecimal Ivalue = null;
                            try {
                                Ivalue = new BigDecimal(value);
                                if (Ivalue == null) {
                                    errList.set(i, label + "值不正确");
                                    break;
                                }
                            } catch (Exception e) {
                                errList.set(i, label + "值不正确");
                                break;
                            }
                            if (swapDataVo.getMin() != null) {
                                BigDecimal min = new BigDecimal(swapDataVo.getMin());
                                if (Ivalue.compareTo(min) == -1) {
                                    errList.set(i, label + "值不能小于最小值");
                                    break;
                                }
                            }
                            if (swapDataVo.getMax() != null) {
                                BigDecimal max = new BigDecimal(swapDataVo.getMax());
                                if (Ivalue.compareTo(max) == 1) {
                                    errList.set(i, label + "值不能大于最大值");
                                    break;
                                }
                            }
                            insMap.put(swapDataVo.getVModel(), Ivalue);
                            break;
                        case YunzhupaasKeyConsts.TEXTAREA:
                            if (StringUtil.isNotEmpty(swapDataVo.getMaxlength())) {
                                if (value.length() > Integer.valueOf(swapDataVo.getMaxlength())) {
                                    errList.set(i, label + "值超出最多输入字符限制");
                                    break;
                                }
                            }
                            break;
                        case YunzhupaasKeyConsts.COM_INPUT:
                            // 只验证子表。主副表在外面做唯一验证
                            Boolean unique = swapDataVo.getConfig().getUnique();
                            if (!uniqueModel.isMain()) {
                                if (StringUtil.isNotEmpty(swapDataVo.getMaxlength())) {
                                    if (value.length() > Integer.valueOf(swapDataVo.getMaxlength())) {
                                        errList.set(i, label + "值超出最多输入字符限制");
                                        break;
                                    }
                                }
                                boolean comInputError = false;
                                if (unique) {
                                    // 子表重复只判断同一个表单
                                    if (insMap.get("child_table_list") != null) {
                                        List<Map<String, Object>> childList = uniqueModel.getChildMap();
                                        String finalValue = value;
                                        for (int j = 0; j < childList.size(); j++) {
                                            Map<String, Object> t = childList.get(j);
                                            if (finalValue.equals(t.get(swapDataVo.getVModel()))) {
                                                comInputError = true;
                                                errList.set(i, label + "值已存在");
                                                uniqueModel.setChildIndex(j);
                                                break;
                                            }
                                        }
                                    }
                                }
                                // 验证正则
                                if (StringUtil.isNotEmpty(swapDataVo.getConfig().getRegList())) {
                                    List<RegListModel> regList = JsonUtil
                                            .getJsonToList(swapDataVo.getConfig().getRegList(), RegListModel.class);
                                    for (RegListModel regListModel : regList) {
                                        // 处理正则格式
                                        String reg = regListModel.getPattern();
                                        if (reg.startsWith("/") && reg.endsWith("/")) {
                                            reg = reg.substring(1, reg.length() - 1);
                                        }
                                        boolean matches = value.matches(reg);
                                        if (!matches) {
                                            comInputError = true;
                                            errList.set(i, label + regListModel.getMessage());
                                        }
                                    }
                                }
                                if (!comInputError) {
                                    insMap.put(swapDataVo.getVModel(), value);
                                }
                            }
                            break;
                        case YunzhupaasKeyConsts.TIME:
                            // 格式
                            String dataFomrat = "yyyy-MM-dd " + swapDataVo.getFormat();
                            String valueTime = com.yunzhupaas.util.DateUtil.daFormat(new Date()) + " " + value;
                            try {
                                if (swapDataVo.getFormat().length() != value.length())
                                    throw new DataException();
                                SimpleDateFormat formatter = new SimpleDateFormat(dataFomrat);
                                formatter.setLenient(false);
                                Date d = formatter.parse(valueTime);
                            } catch (Exception e) {
                                errList.set(i, label + "值不正确");
                                break;
                            }

                            // 范围
                            try {
                                // 判断时间是否在设置范围内
                                boolean timeHasRangeError = FormPublicUtils.dateTimeCondition(swapDataVo, dataFomrat,
                                        valueTime, data, yunzhupaasKey);
                                if (timeHasRangeError) {
                                    errList.set(i, label + "值不在范围内");
                                    break;
                                }
                            } catch (Exception e) {
                                errList.set(i, label + "值不在范围内");
                                break;
                            }

                            break;
                        case YunzhupaasKeyConsts.DATE:
                            String format = swapDataVo.getFormat();
                            Date valueDate = null;
                            try {
                                if (format.length() != value.length())
                                    throw new DataException();
                                SimpleDateFormat formatter = new SimpleDateFormat(format);
                                formatter.setLenient(false);
                                valueDate = formatter.parse(value);
                            } catch (Exception e) {
                                errList.set(i, label + "值不正确");
                                break;
                            }

                            try {
                                // 判断时间是否在设置范围内
                                boolean timeHasRangeError = FormPublicUtils.dateTimeCondition(swapDataVo, format, value,
                                        data, yunzhupaasKey);
                                if (timeHasRangeError) {
                                    errList.set(i, label + "值不在范围内");
                                    break;
                                }
                            } catch (Exception e) {
                                errList.set(i, label + "值不在范围内");
                                break;
                            }
                            insMap.put(swapDataVo.getVModel(), valueDate.getTime());
                            break;
                        /**
                         * 子表
                         */
                        case YunzhupaasKeyConsts.CHILD_TABLE:
                            StringJoiner childJoiner = new StringJoiner(",");
                            List<Map<String, Object>> childAllData = (List<Map<String, Object>>) data
                                    .get(swapDataVo.getVModel());
                            List<Map<String, Object>> childTable = new ArrayList<>(childAllData.size());
                            uniqueModel.setChildMap(new ArrayList<>());
                            for (int childI = 0, childLen = childAllData.size(); childI < childLen; childI++) {
                                Map<String, Object> item = childAllData.get(childI);
                                Map<String, Object> childMap = new HashMap<>(item);
                                childMap.put("mainAndMast", data);
                                childMap.put("child_table_list", data.get(swapDataVo.getVModel()));
                                Map<String, Object> childTableMap = new HashMap<>(childMap);
                                Map<String, Object> childerrorMap = new HashMap<>(childMap);
                                uniqueModel.setMain(false);
                                StringJoiner childJoiner1 = new StringJoiner(",");
                                List<String> childErrList = this.checkExcelData(swapDataVo.getConfig().getChildren(),
                                        childMap, localCache, childTableMap, childerrorMap, uniqueModel);
                                childErrList.stream().forEach(t -> {
                                    if (StringUtil.isNotEmpty(t)) {
                                        childJoiner1.add(t);
                                    }
                                });
                                List<Map<String, Object>> childList = uniqueModel.getChildMap();
                                if (childJoiner1.length() > 0) {
                                    if (uniqueModel.isUpdate() && uniqueModel.getChildIndex() != null
                                            && childJoiner1.toString().split(",").length == 1
                                            && childJoiner1.toString().contains("值已存在")) {
                                        childList.set(uniqueModel.getChildIndex(), childTableMap);
                                    } else {
                                        childJoiner.add(childJoiner1.toString());
                                    }
                                } else {
                                    childList.add(childTableMap);
                                    childTable.add(childTableMap);
                                }
                            }
                            if (childJoiner.length() == 0) {
                                insMap.put(swapDataVo.getVModel(), childTable);
                            } else {
                                errList.set(i, childJoiner.toString());
                            }
                            uniqueModel.setMain(true);
                            break;
                        default:
                            break;

                    }
                    /**
                     * 数据接口
                     */
                    if (dataType != null) {
                        List<Map<String, Object>> options = new ArrayList<>();
                        String dataLabel = swapDataVo.getProps().getLabel() != null ? swapDataVo.getProps().getLabel()
                                : "";
                        String dataValue = swapDataVo.getProps().getValue() != null ? swapDataVo.getProps().getValue()
                                : "";
                        String children = swapDataVo.getProps().getChildren() != null
                                ? swapDataVo.getProps().getChildren()
                                : "";
                        boolean isCascader = YunzhupaasKeyConsts.CASCADER.equals(yunzhupaasKey);

                        String localCacheKey;
                        Map<String, Object> dataInterfaceMap = new HashMap<>();
                        // 静态数据
                        if (dataType.equals(OnlineDataTypeEnum.STATIC.getType())) {
                            localCacheKey = String.format("%s-%s",
                                    swapDataVo.getConfig().getRelationTable() + swapDataVo.getVModel(),
                                    OnlineDataTypeEnum.STATIC.getType());
                            if (!localCache.containsKey(localCacheKey)) {
                                if (swapDataVo.getOptions() != null) {
                                    options = JsonUtil.getJsonToListMap(swapDataVo.getOptions());
                                    String Children = swapDataVo.getProps().getChildren();
                                    JSONArray staticData = JsonUtil.getListToJsonArray(options);
                                    getOptions(dataLabel, dataValue, Children, staticData, options);
                                } else {
                                    options = JsonUtil.getJsonToListMap(swapDataVo.getOptions());
                                }
                                Map<String, Object> finalDataInterfaceMap = new HashMap<>(16);
                                String finalDataLabel = dataLabel;
                                String finalDataValue = dataValue;
                                options.stream().forEach(o -> {
                                    finalDataInterfaceMap.put(String.valueOf(o.get(finalDataLabel)),
                                            o.get(finalDataValue));
                                });
                                localCache.put(localCacheKey, finalDataInterfaceMap);
                                dataInterfaceMap = finalDataInterfaceMap;
                            } else {
                                dataInterfaceMap = (Map<String, Object>) localCache.get(localCacheKey);
                            }

                            checkFormDataInteface(multiple, insMap, swapDataVo.getVModel(), label, dataInterfaceMap,
                                    valueList, errList, i, isCascader);
                            // 远端数据
                        } else if (dataType.equals(OnlineDataTypeEnum.DYNAMIC.getType())) {
                            localCacheKey = String.format("%s-%s-%s-%s", OnlineDataTypeEnum.DYNAMIC.getType(),
                                    swapDataVo.getConfig().getPropsUrl(), dataValue, dataLabel);
                            if (!localCache.containsKey(localCacheKey)) {
                                List<TemplateJsonModel> templateJson = swapDataVo.getConfig().getTemplateJson();
                                Map<String, String> param = new HashMap<>();
                                for (TemplateJsonModel tm : templateJson) {
                                    param.put(tm.getField(), tm.getDefaultValue());
                                }
                                ActionResult actionResult = dataInterFaceApi
                                        .infoToId(swapDataVo.getConfig().getPropsUrl(), null, param);
                                if (actionResult != null && actionResult.getData() != null) {
                                    List<Map<String, Object>> dycDataList = new ArrayList<>();
                                    if (actionResult.getData() instanceof List) {
                                        dycDataList = (List<Map<String, Object>>) actionResult.getData();
                                    }
                                    JSONArray dataAll = JsonUtil.getListToJsonArray(dycDataList);
                                    treeToList(dataLabel, dataValue, children, dataAll, options);
                                    Map<String, Object> finalDataInterfaceMap1 = new HashMap<>(16);
                                    String finalDataLabel2 = dataLabel;
                                    String finalDataValue1 = dataValue;
                                    options.stream().forEach(o -> {
                                        finalDataInterfaceMap1.put(String.valueOf(o.get(finalDataLabel2)),
                                                String.valueOf(o.get(finalDataValue1)));
                                    });
                                    dataInterfaceMap = finalDataInterfaceMap1;
                                    localCache.put(localCacheKey, dataInterfaceMap);
                                }
                            } else {
                                dataInterfaceMap = (Map<String, Object>) localCache.get(localCacheKey);
                            }
                            checkFormDataInteface(multiple, insMap, swapDataVo.getVModel(), label, dataInterfaceMap,
                                    valueList, errList, i, isCascader);
                            // 数据字典
                        } else if (dataType.equals(OnlineDataTypeEnum.DICTIONARY.getType())) {
                            localCacheKey = String.format("%s-%s", OnlineDataTypeEnum.DICTIONARY.getType(),
                                    swapDataVo.getConfig().getDictionaryType());
                            dataLabel = swapDataVo.getProps().getLabel();
                            dataValue = swapDataVo.getProps().getValue();
                            if (!localCache.containsKey(localCacheKey)) {
                                List<DictionaryDataEntity> list = dictionaryDataApi
                                        .getDicList(swapDataVo.getConfig().getDictionaryType());
                                options = list.stream().map(dic -> {
                                    Map<String, Object> dictionaryMap = new HashMap<>(16);
                                    dictionaryMap.put("id", dic.getId());
                                    dictionaryMap.put("enCode", dic.getEnCode());
                                    dictionaryMap.put("fullName", dic.getFullName());
                                    return dictionaryMap;
                                }).collect(Collectors.toList());
                                localCache.put(localCacheKey, options);
                            } else {
                                options = (List<Map<String, Object>>) localCache.get(localCacheKey);
                            }
                            Map<String, Object> finalDataInterfaceMap1 = new HashMap<>(16);
                            String finalDataLabel3 = dataLabel;
                            String finalDataValue3 = dataValue;
                            options.stream().forEach(o -> finalDataInterfaceMap1
                                    .put(String.valueOf(o.get(finalDataLabel3)), o.get(finalDataValue3)));

                            checkFormDataInteface(multiple, insMap, swapDataVo.getVModel(), label,
                                    finalDataInterfaceMap1, valueList, errList, i, isCascader);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    errList.set(i, e.getMessage());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return errList;
    }

    private List<String> checkOptionsControl(boolean multiple, Map<String, Object> insMap, String vModel, String label,
            Map<String, Object> cacheMap,
            List<String> valueList, List<String> errList, int i) {
        boolean error = false;
        if (!multiple) {
            // 非多选填入多选值
            if (valueList.size() > 1) {
                error = true;
                errList.set(i, label + "值不正确");
            }
        }
        List<String> dataList = new ArrayList<>();
        if (!error) {
            boolean errorHapen = false;
            for (String va : valueList) {
                if (StringUtil.isEmpty(va)) {
                    errorHapen = true;
                    break;
                }
                Object vo = cacheMap.get(va);
                if (vo == null) {
                    errorHapen = true;
                    break;
                } else {
                    dataList.add(vo.toString());
                }
            }
            if (errorHapen) {
                errList.set(i, label + "值不正确");
            } else {
                insMap.put(vModel, !multiple ? dataList.get(0) : JsonUtil.getObjectToString(dataList));
            }
        }
        return dataList;
    }

    public void checkCustomControl(OnlineCusCheckModel cusCheckModel, List<String> errList, int i, String label) {
        boolean contains;
        List<String> ableIdsAll = new ArrayList<>();
        List<String> ableDepIds = cusCheckModel.getAbleDepIds();
        List<String> ableGroupIds = cusCheckModel.getAbleGroupIds();
        List<String> ablePosIds = cusCheckModel.getAblePosIds();
        List<String> ableRoleIds = cusCheckModel.getAbleRoleIds();
        List<String> ableUserIds = cusCheckModel.getAbleUserIds();
        List<String> ableComIds = cusCheckModel.getAbleComIds();
        List<String> ableComIdsStr = cusCheckModel.getAbleComIdsStr();
        List<String> dataList = cusCheckModel.getDataList();
        String controlType = cusCheckModel.getControlType();
        switch (controlType) {
            case YunzhupaasKeyConsts.GROUPSELECT:
                ableIdsAll.addAll(ableGroupIds);
                break;
            case YunzhupaasKeyConsts.ROLESELECT:
                ableIdsAll.addAll(ableRoleIds);
                break;
            case YunzhupaasKeyConsts.DEPSELECT:
                ableIdsAll.addAll(ableDepIds);
                break;
            case YunzhupaasKeyConsts.COMSELECT:
                ableIdsAll.addAll(ableComIdsStr);
                break;
            case YunzhupaasKeyConsts.CUSTOMUSERSELECT:
                for (String id : ableDepIds) {
                    ableIdsAll.add(id + "--department");
                }
                for (String id : ableGroupIds) {
                    ableIdsAll.add(id + "--group");
                }
                for (String id : ablePosIds) {
                    ableIdsAll.add(id + "--position");
                }
                for (String id : ableRoleIds) {
                    ableIdsAll.add(id + "--role");
                }
                for (String id : ableUserIds) {
                    ableIdsAll.add(id + "--user");
                }
                for (String id : ableComIds) {
                    ableIdsAll.add(id + "--company");
                }
                ableIdsAll.addAll(ableDepIds);
                ableIdsAll.addAll(ableGroupIds);
                ableIdsAll.addAll(ablePosIds);
                ableIdsAll.addAll(ableRoleIds);
                ableIdsAll.addAll(ableUserIds);
                ableIdsAll.addAll(ableComIds);
                List<UserRelationEntity> listByObjectIdAll = userRelationApi.getListByObjectIdAll(ableIdsAll);
                for (UserRelationEntity userRelationEntity : listByObjectIdAll) {
                    ableIdsAll.add(userRelationEntity.getUserId() + "--user");
                }
                break;
            case YunzhupaasKeyConsts.USERSELECT:
                List<String> objIds = new ArrayList<>();
                if (ableComIds.size() > 0) {
                    List<String> lastIds = new ArrayList<>();
                    for (String str : ableComIds) {
                        lastIds.add(str);
                    }
                    objIds.addAll(lastIds);
                }
                if (ableDepIds.size() > 0) {
                    List<String> lastIds = new ArrayList<>();
                    for (String str : ableDepIds) {
                        lastIds.add(str);
                    }
                    objIds.addAll(lastIds);
                }
                if (ableGroupIds.size() > 0) {
                    objIds.addAll(ableGroupIds);
                }
                if (ablePosIds.size() > 0) {
                    objIds.addAll(ablePosIds);
                }
                if (ableRoleIds.size() > 0) {
                    objIds.addAll(ableRoleIds);
                }
                List<String> UserIds = userRelationApi.getListByObjectIdAll(objIds).stream()
                        .map(UserRelationEntity::getUserId).collect(Collectors.toList());
                UserIds.addAll(ableUserIds);
                ableIdsAll.addAll(UserIds);
                break;
            case YunzhupaasKeyConsts.POSSELECT:
                List<String> posIds = new ArrayList<>();
                if (ableDepIds.size() > 0) {
                    List<String> depIds = positionApi.getListByOrganizeId(ableDepIds, false).stream()
                            .map(PositionEntity::getId).collect(Collectors.toList());
                    posIds.addAll(depIds);
                }
                if (ablePosIds.size() > 0) {
                    posIds.addAll(ablePosIds);
                }
                ableIdsAll.addAll(posIds);
                break;
            default:
                break;
        }
        if (ableIdsAll.size() > 0) {
            for (String id : dataList) {
                contains = ableIdsAll.contains(id);
                if (!contains) {
                    errList.set(i, label + "值不在范围内");
                    break;
                }
            }
        }
    }

    public void checkFormDataInteface(boolean multiple, Map<String, Object> insMap, String vModel, String label,
            Map<String, Object> cacheMap,
            List<String> valueList, List<String> errList, int i, boolean isCascader) {
        List<String[]> staticStrData = new ArrayList<>();
        List<String> staticStrDataList1 = new ArrayList<>();
        // 单选给多选直接报错
        if (!multiple && valueList.size() > 1) {
            errList.set(i, label + "值不正确");
            return;
        }
        boolean hasError = false;
        boolean takeOne = false;
        for (String dicValue : valueList) {
            if (isCascader) {
                List<String> staticStrDataList2 = new ArrayList<>();
                if (!multiple && valueList.size() > 1)
                    hasError = true;
                if (dicValue.contains("/")) {
                    String[] split = dicValue.split("/");
                    for (String s : split) {
                        Object s1 = cacheMap.get(s);
                        if (s1 != null) {
                            staticStrDataList2.add(s1.toString());
                            staticStrDataList1.add(s1.toString());
                        } else {
                            hasError = true;
                        }
                    }
                    staticStrData.add(staticStrDataList2.toArray(new String[staticStrDataList2.size()]));
                } else {
                    if (cacheMap.get(dicValue) == null) {
                        hasError = true;
                    } else {
                        staticStrDataList1.add(cacheMap.get(dicValue).toString());
                        staticStrData.add(new String[] { cacheMap.get(dicValue).toString() });
                    }
                }
            } else {
                takeOne = true;
                Object s1 = cacheMap.get(dicValue);
                if (s1 != null) {
                    staticStrDataList1.add(s1.toString());
                } else {
                    hasError = true;
                }
            }
        }

        if (hasError) {
            errList.set(i, label + "值不正确");
        } else {
            String v = multiple
                    ? takeOne ? JsonUtil.getObjectToString(staticStrDataList1)
                            : JsonUtil.getObjectToString(staticStrData)
                    : takeOne ? staticStrDataList1.get(0) : JsonUtil.getObjectToString(staticStrDataList1);
            insMap.put(vModel, v);
        }
    }

    /**
     * 获取接口api数据结果
     *
     * @param
     * @return
     * @copyright 深圳市乐程软件有限公司
     * @date 2023/1/10
     */
    public List<Map<String, Object>> getInterfaceData(VisualdevReleaseEntity visualdevEntity,
            PaginationModel paginationModel, ColumnDataModel columnDataModel) {
        List<Map<String, Object>> realList = new ArrayList<>();
        try {
            Map<String, Object> queryMap = JsonUtil.stringToMap(paginationModel.getQueryJson());

            // 页签搜索
            Map<String, Object> extraMap = JsonUtil.stringToMap(paginationModel.getExtraQueryJson());
            extraMap = extraMap == null ? new HashMap<>() : extraMap;
            DataInterfaceEntity info = dataInterFaceApi.getInfo(visualdevEntity.getInterfaceId());
            // 接口真分页
            if (info.getHasPage() == 1) {
                DataInterfacePage page = new DataInterfacePage();
                page.setCurrentPage(paginationModel.getCurrentPage());
                page.setPageSize(paginationModel.getPageSize());
                if ("1".equals(paginationModel.getDataType())) {
                    page.setPageSize(99999999);
                }
                List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(visualdevEntity.getInterfaceParam(),
                        DataInterfaceModel.class);
                for (DataInterfaceModel df : jsonToList) {
                    if (queryMap != null && queryMap.containsKey(df.getField()) && queryMap.get(df.getField()) != null
                            && StringUtil.isNotEmpty(queryMap.get(df.getField()).toString())) {
                        String thisValue = queryMap.get(df.getField()).toString();
                        if (extraMap.containsKey(df.getField())) {
                            thisValue = extraMap.get(df.getField()).toString();
                        }
                        if (Objects.equals(df.getSourceType(), 2)) {
                            df.setRelationField(thisValue);
                        }
                        df.setDefaultValue(thisValue);
                    } else if (extraMap.containsKey(df.getField())) {
                        String thisValue = extraMap.get(df.getField()).toString();
                        if (Objects.equals(df.getSourceType(), 2)) {
                            df.setRelationField(thisValue);
                        }
                        df.setDefaultValue(thisValue);
                    }
                }
                page.setParamList(jsonToList);
                ActionResult actionResult = dataInterFaceApi.infoToIdPageList(visualdevEntity.getInterfaceId(), page);
                if (actionResult.getCode() == 200) {
                    PageListVO data = JsonUtil.getJsonToBean(actionResult.getData(), PageListVO.class);
                    realList = (List<Map<String, Object>>) data.getList();
                    PaginationVO pagination = data.getPagination();
                    paginationModel.setTotal(pagination.getTotal());
                }
            } else {
                Map<String, String> parameterMap = new HashMap<>();
                if (StringUtil.isNotEmpty(visualdevEntity.getInterfaceParam())) {
                    List<InterefaceParamModel> jsonToList = JsonUtil.getJsonToList(visualdevEntity.getInterfaceParam(),
                            InterefaceParamModel.class);
                    for (InterefaceParamModel mapStr : jsonToList) {
                        TemplateJsonModel jsonToBean = JsonUtil.getJsonToBean(mapStr, TemplateJsonModel.class);
                        String dataValue = paramSourceTypeReplaceValue(jsonToBean, null);
                        mapStr.setDefaultValue(dataValue);
                        if (mapStr.getUseSearch() != null && Objects.equals(mapStr.getUseSearch(), true)) {
                            Map<String, Object> keyJsonMap = queryMap;
                            if (keyJsonMap != null && keyJsonMap.get(mapStr.getField()) != null
                                    && StringUtil.isNotEmpty(keyJsonMap.get(mapStr.getField()).toString())) {
                                parameterMap.put(mapStr.getField(), keyJsonMap.get(mapStr.getField()).toString());
                            } else {
                                parameterMap.put(mapStr.getField(), null);
                            }
                        } else {
                            parameterMap.put(mapStr.getField(), mapStr.getDefaultValue());
                        }
                    }
                }

                // 组装查询条件
                List<FieLdsModel> queryCondition = this.getQueryCondition(paginationModel, columnDataModel);
                // 封装sql---sql普通查询塞参数到数据接口那边去组装sql
                OnlinePublicUtils.getViewQuerySql(info, queryCondition, parameterMap, extraMap);

                ActionResult dataInterfaceInfo = dataInterFaceApi.infoToId(visualdevEntity.getInterfaceId(), null,
                        parameterMap);
                if (dataInterfaceInfo.getCode() == 200) {
                    List<Map<String, Object>> dataRes = (List<Map<String, Object>>) dataInterfaceInfo.getData();
                    // 假查询条件-不为sql时查询在此过滤
                    List<Map<String, Object>> dataInterfaceList = OnlinePublicUtils.getViewQueryNotSql(info,
                            queryCondition, dataRes, extraMap);

                    // 判断是否有id没有则随机
                    dataInterfaceList.forEach(item -> {
                        if (item.get("id") == null) {
                            item.put("id", RandomUtil.uuId());
                        }
                        if (item.get("f_id") != null) {
                            item.put("id", item.get("f_id"));
                        }
                        if (item.get("children") != null) {
                            item.remove("children");
                        }
                    });

                    // 排序
                    if (StringUtil.isNotEmpty(paginationModel.getSidx())) {
                        String[] split = paginationModel.getSidx().split(",");
                        Collections.sort(dataInterfaceList, new Comparator<Map<String, Object>>() {
                            @Override
                            public int compare(Map<String, Object> a, Map<String, Object> b) {
                                for (String sidx : split) {
                                    String key = sidx;
                                    if (sidx.startsWith("-")) {
                                        key = sidx.substring(1);
                                    }
                                    if (a.get(key) == null) {
                                        if (b.get(key) == null) {
                                            return 0;
                                        }
                                        return 1;
                                    }
                                    if (b.get(key) == null) {
                                        return -1;
                                    }
                                    if (!a.get(key).equals(b.get(key))) {
                                        return String.valueOf(b.get(key)).compareTo(String.valueOf(a.get(key)));
                                    }
                                }
                                return 0;
                            }
                        });
                    }

                    if ("1".equals(paginationModel.getDataType())) {// 导出全部数据用
                        return dataInterfaceList;
                    }
                    // 假分页
                    if (columnDataModel.getHasPage() && CollectionUtils.isNotEmpty(dataInterfaceList)) {
                        List<List<Map<String, Object>>> partition = Lists.partition(dataInterfaceList,
                                (int) paginationModel.getPageSize());
                        int i = (int) paginationModel.getCurrentPage() - 1;
                        realList = partition.size() > i ? partition.get(i) : Collections.emptyList();
                        paginationModel.setTotal(dataInterfaceList.size());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据视图，接口请求失败!message={}", e.getMessage());
        }
        // 数据添加随机id
        dataId(realList, columnDataModel.getViewKey());
        return realList;
    }

    /**
     * 数据添加随机id
     *
     * @param data
     * @param key
     */
    private void dataId(List<Map<String, Object>> data, String key) {
        for (Map<String, Object> item : data) {
            if (item.get("id") == null) {
                item.put("id", RandomUtil.uuId());
            }
            if (item.get("f_id") != null) {
                item.put("id", item.get("f_id"));
            }
            if (item.get(key) != null) {
                item.put("id", item.get(key));
            }

            if (item.get("children") != null) {
                List<Map<String, Object>> children = new ArrayList<>();
                try {
                    children.addAll(JsonUtil.getJsonToListMap(String.valueOf(item.get("children"))));
                } catch (Exception e) {

                }
                if (children.size() > 0) {
                    dataId(children, null);
                    item.put("children", children);
                }
            }
        }
    }

    public static List convertToList(Object obj) {
        if (obj instanceof List) {
            List arrayList = (List) obj;
            return arrayList;
        } else {
            List arrayList = new ArrayList();
            arrayList.add(obj);
            return arrayList;
        }
    }

    public static String convertValueToString(String obj, boolean mult, boolean isOrg) {
        if (StringUtil.isNotEmpty(obj)) {
            String prefix = "[";
            if (isOrg) {
                prefix = "[[";
            }
            if (mult) {
                if (!obj.startsWith(prefix)) {
                    JSONArray arr = new JSONArray();
                    if (isOrg) {
                        // 组织多选为二维数组
                        arr.add(JSONArray.parse(obj));
                    } else {
                        arr.add(obj);
                    }
                    return arr.toJSONString();
                }
            } else {
                if (obj.startsWith(prefix)) {
                    JSONArray objects = JSONArray.parseArray(obj);
                    return objects.size() > 0 ? objects.get(0).toString() : "";
                }
            }
        }
        return obj;
    }

    /**
     * 获取组织数据中的最后一级组织ID
     * 单选数据获取数组中最后一个组织本身的ID
     * 多选数据获取最后一组组织数据中的最后一个组织本身的ID
     *
     * @param data
     * @return
     */
    public static String getLastOrganizeId(Object data) {
        if (data instanceof List) {
            List listData = (List) data;
            data = listData.get(listData.size() - 1);
            return getLastOrganizeId(data);
        } else if (data instanceof String) {
            String strData = (String) data;
            if (strData.startsWith(StrPool.BRACKET_START)) {
                JSONArray jsonArray = JSONArray.parseArray(strData);
                return getLastOrganizeId(jsonArray);
            } else {
                return strData;
            }
        }
        return data.toString();
    }

    /**
     * 输入时表单时间字段根据格式转换去尾巴
     *
     * @param list 字段属性
     * @param map  数据
     */
    public static void swapDatetime(List<FieLdsModel> list, Map<String, Object> map) {
        List<FieLdsModel> fields = new ArrayList<>();
        FormPublicUtils.recursionFieldsExceptChild(fields, list);
        // 主副表
        for (FieLdsModel field : fields) {
            try {
                String vModel = field.getVModel();
                String format = DateTimeFormatConstant.getFormat(field.getFormat());
                ConfigModel config = field.getConfig();
                if (map.get(vModel) != null) {
                    String s = map.get(vModel).toString();
                    if (StringUtil.isBlank(s) || "[]".equals(s) || "[[]]".equals(s)) {
                        map.replace(vModel, null);
                    }
                }

                // SQL Server text字段先这样处理。
                if (map.get(vModel) == null) {
                    String dbType = "";
                    try {
                        @Cleanup
                        Connection connection = DynamicDataSourceUtil.getCurrentConnection();
                        dbType = connection.getMetaData().getDatabaseProductName().trim();
                    } catch (Exception e) {
                    }
                    if (YunzhupaasKeyConsts.getTextField().contains(config.getYunzhupaasKey())
                            && "Microsoft SQL Server".equals(dbType)) {
                        map.put(vModel, "");
                    }
                }
                if (YunzhupaasKeyConsts.DATE.equals(config.getYunzhupaasKey()) && map.get(vModel) != null) {
                    Date date = new Date(Long.parseLong(String.valueOf(map.get(vModel))));
                    String completionStr = "";
                    switch (format) {
                        case "yyyy":
                            completionStr = "-01-01 00:00:00";
                            break;
                        case "yyyy-MM":
                            completionStr = "-01 00:00:00";
                            break;
                        case "yyyy-MM-dd":
                            completionStr = " 00:00:00";
                            break;
                        case "yyyy-MM-dd HH":
                            completionStr = ":00:00";
                            break;
                        case "yyyy-MM-dd HH:mm":
                            completionStr = ":00";
                            break;
                        default:
                            break;
                    }
                    String datestr = com.yunzhupaas.util.DateUtil.dateToString(date, format);
                    long time = com.yunzhupaas.util.DateUtil.stringToDate(datestr + completionStr).getTime();
                    map.replace(vModel, time);
                }
                if (YunzhupaasKeyConsts.EDITOR.equals(config.getYunzhupaasKey()) && map.get(vModel) != null) {
                    map.replace(vModel, XSSEscape.escapeImgOnlyBase64(map.get(vModel).toString()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 子表
        for (FieLdsModel field : fields) {
            if (field.getVModel().toLowerCase().startsWith(YunzhupaasKeyConsts.CHILD_TABLE_PREFIX)) {
                List<FieLdsModel> children = field.getConfig().getChildren();
                if (CollectionUtils.isNotEmpty(children)) {
                    String tableKey = field.getConfig().getTableName() + "List";
                    if (map.get(tableKey) != null) {
                        List<Object> listObj = (List) map.get(tableKey);
                        if (CollectionUtils.isEmpty(listObj))
                            continue;
                        List<Object> listObjNew = new ArrayList<>();
                        for (Object o : listObj) {
                            Map<String, Object> stringObjectMap = JsonUtil.entityToMap(o);
                            swapDatetime(children, stringObjectMap);
                            listObjNew.add(stringObjectMap);
                        }
                        if (CollectionUtils.isNotEmpty(listObjNew)) {
                            map.replace(tableKey, listObjNew);
                        }
                    }
                    String tableFieldKey = field.getVModel();
                    if (map.get(tableFieldKey) != null) {
                        List<Object> listObj = (List) map.get(tableFieldKey);
                        if (CollectionUtils.isEmpty(listObj))
                            continue;
                        List<Object> listObjNew = new ArrayList<>();
                        for (Object o : listObj) {
                            Map<String, Object> stringObjectMap = JsonUtil.entityToMap(o);
                            swapDatetime(children, stringObjectMap);
                            listObjNew.add(stringObjectMap);
                        }
                        if (CollectionUtils.isNotEmpty(listObjNew)) {
                            map.replace(tableFieldKey, listObjNew);
                        }
                    }
                }
            }

        }
    }

    /**
     * 判断组织层级是否正确
     *
     * @param comTwoList
     * @param comOneList
     * @return
     */
    private boolean orgListRight(List<List<String>> comTwoList, List<String> comOneList) {
        if (CollectionUtils.isNotEmpty(comOneList)) {
            String one = comOneList.get(comOneList.size() - 1);
            List<String> realOrgs = new ArrayList<>();
            OrganizeEntity organizeEntity = organizeApi.getInfo(one);
            if (organizeEntity != null) {
                if (StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree())) {
                    String[] split = organizeEntity.getOrganizeIdTree().split(",");
                    if (split.length > 0) {
                        realOrgs = Arrays.asList(split);
                    }
                    if (!JsonUtil.getObjectToString(comOneList).equals(JsonUtil.getObjectToString(realOrgs))) {
                        return true;
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(comTwoList) && comTwoList.size() > 0) {
            for (List<String> two : comTwoList) {
                if (two.size() <= 0) {
                    return false;
                }
                String one = two.get(two.size() - 1);
                List<String> realOrgs = new ArrayList<>();
                OrganizeEntity organizeEntity = organizeApi.getInfo(one);
                if (organizeEntity != null) {
                    if (StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree())) {
                        String[] split = organizeEntity.getOrganizeIdTree().split(",");
                        if (split.length > 0) {
                            realOrgs = Arrays.asList(split);
                        }
                        if (!JsonUtil.getObjectToString(comOneList).equals(JsonUtil.getObjectToString(realOrgs))) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 视图条件组装
     *
     * @param paginationModel
     * @param columnDataModel
     * @return
     */
    public List<FieLdsModel> getQueryCondition(PaginationModel paginationModel, ColumnDataModel columnDataModel) {
        List<FieLdsModel> searchVOList = JsonUtil.getJsonToList(columnDataModel.getSearchList(), FieLdsModel.class);
        Map<String, Object> keyJsonMap = JsonUtil.stringToMap(paginationModel.getQueryJson());

        List<FieLdsModel> searchResList = new ArrayList<>();
        if (keyJsonMap == null) {
            return searchResList;
        }
        for (String key : keyJsonMap.keySet()) {
            for (FieLdsModel item : searchVOList) {
                String vModel = item.getVModel();
                if (key.equals(vModel) && keyJsonMap.get(key) != null) {
                    if (!item.getConfig().getIsFromParam()) {// 非接口参数的条件
                        FieLdsModel model = BeanUtil.copyProperties(item, FieLdsModel.class);
                        String yunzhupaasKey = model.getConfig().getYunzhupaasKey();
                        switch (yunzhupaasKey) {
                            case YunzhupaasKeyConsts.COM_INPUT:
                                if (Objects.equals(model.getSearchType(), 3)) {
                                    model.setSearchType(2);// 单行输入范围调整为模糊
                                }
                                model.setFieldValue(String.valueOf(keyJsonMap.get(vModel)));
                                break;
                            case YunzhupaasKeyConsts.NUM_INPUT:
                                model.setSearchType(3);// 定义为between
                                List<Long> integerList = JsonUtil.getJsonToList(keyJsonMap.get(vModel), Long.class);
                                model.setFieldValueOne(integerList.get(0));
                                model.setFieldValueTwo(integerList.get(1));
                                break;
                            case YunzhupaasKeyConsts.DATE:
                                model.setSearchType(3);// 定义为between
                                List<Long> dateList = JsonUtil.getJsonToList(keyJsonMap.get(vModel), Long.class);
                                String timeOne = FormPublicUtils.getTimeFormat(com.yunzhupaas.util.DateUtil
                                        .dateToString(new Date(dateList.get(0)), model.getFormat()));
                                String timeTwo = FormPublicUtils.getTimeFormat(com.yunzhupaas.util.DateUtil
                                        .dateToString(new Date(dateList.get(1)), model.getFormat()));
                                model.setFieldValueOne(timeOne);
                                model.setFieldValueTwo(timeTwo);
                                break;
                            case YunzhupaasKeyConsts.TIME:
                                model.setSearchType(3);// 定义为between
                                List<String> stringList = JsonUtil.getJsonToList(keyJsonMap.get(vModel), String.class);
                                model.setFieldValueOne(stringList.get(0));
                                model.setFieldValueTwo(stringList.get(1));
                                break;
                            case YunzhupaasKeyConsts.SELECT:
                            case YunzhupaasKeyConsts.POSSELECT:
                            case YunzhupaasKeyConsts.ROLESELECT:
                            case YunzhupaasKeyConsts.GROUPSELECT:
                                model.setSearchType(4);
                                List<String> dataList = new ArrayList<>();
                                try {
                                    List<String> list = JsonUtil.getJsonToList(keyJsonMap.get(vModel), String.class);
                                    dataList.addAll(list);
                                } catch (Exception e1) {
                                    dataList.add(String.valueOf(keyJsonMap.get(vModel)));
                                }
                                model.setDataList(dataList);
                                break;
                            case YunzhupaasKeyConsts.COMSELECT:
                                model.setSearchType(4);
                                List<String> listOrg = new ArrayList<>();
                                List<String> orgListRes = new ArrayList<>();
                                if (model.getSearchMultiple()) {
                                    List<List<String>> list = JsonUtil.getJsonToBean(keyJsonMap.get(vModel),
                                            List.class);
                                    for (List<String> a : list) {
                                        listOrg.add(a.get(a.size() - 1));
                                        orgListRes.add(JSONArray.toJSONString(a));
                                    }
                                } else {
                                    List<String> list = JsonUtil.getJsonToBean(keyJsonMap.get(vModel), List.class);
                                    listOrg.add(list.get(list.size() - 1));
                                    orgListRes.add(JSONArray.toJSONString(list));
                                }
                                // 包含子组织
                                if (model.getIsIncludeSubordinate()) {
                                    for (String org : listOrg) {
                                        // 获取子组织
                                        List<String> underOrganizations = organizeApi.getUnderOrganizations(org, false);
                                        // 获取组织全路径
                                        for (String itemOrg : underOrganizations) {
                                            OrganizeEntity organizeEntity = organizeApi.getInfo(itemOrg);
                                            if (organizeEntity != null) {
                                                if (StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree())) {
                                                    String[] split = organizeEntity.getOrganizeIdTree().split(",");
                                                    if (split.length > 0) {
                                                        orgListRes.add(JSONArray.toJSONString(Arrays.asList(split)));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    model.setDataList(orgListRes);
                                } else {
                                    model.setDataList(orgListRes);
                                }
                                break;
                            case YunzhupaasKeyConsts.DEPSELECT:
                                model.setSearchType(4);
                                List<String> listDep = new ArrayList<>();
                                List<String> depListRes = new ArrayList<>();
                                if (model.getSearchMultiple()) {
                                    List<String> list = JsonUtil.getJsonToBean(keyJsonMap.get(vModel), List.class);
                                    listDep.addAll(list);
                                    depListRes.addAll(list);
                                } else {
                                    listDep.add(String.valueOf(keyJsonMap.get(vModel)));
                                    depListRes.add(String.valueOf(keyJsonMap.get(vModel)));
                                }
                                // 包含当前部门及子部门
                                if (model.getIsIncludeSubordinate()) {
                                    for (String org : listDep) {
                                        // 获取子部门
                                        List<String> underOrganizations = organizeApi.getUnderOrganizations(org, false);
                                        depListRes.addAll(underOrganizations);
                                    }
                                    model.setDataList(depListRes);
                                } else {
                                    model.setDataList(depListRes);
                                }
                                break;
                            case YunzhupaasKeyConsts.USERSELECT:
                                model.setSearchType(4);
                                List<String> listUser = new ArrayList<>();
                                List<String> userListRes = new ArrayList<>();
                                if (model.getSearchMultiple()) {
                                    List<String> list = JsonUtil.getJsonToBean(keyJsonMap.get(vModel), List.class);
                                    listUser.addAll(list);
                                    userListRes.addAll(list);
                                } else {
                                    listUser.add(String.valueOf(keyJsonMap.get(vModel)));
                                    userListRes.add(String.valueOf(keyJsonMap.get(vModel)));
                                }
                                // 包含当前用户及下属
                                if (model.getIsIncludeSubordinate()) {
                                    for (String userId : listUser) {
                                        // 获取下属用户
                                        List<UserEntity> underOrganizations = userApi.getListByManagerId(userId, null);
                                        List<String> collect = underOrganizations.stream().map(UserEntity::getId)
                                                .collect(Collectors.toList());
                                        userListRes.addAll(collect);
                                    }
                                    model.setDataList(userListRes);
                                } else {
                                    model.setDataList(userListRes);
                                }
                                break;
                            default:
                                model.setFieldValue(String.valueOf(keyJsonMap.get(vModel)));
                                break;
                        }
                        searchResList.add(model);
                    }
                }
            }
        }
        return searchResList;
    }

    /**
     * 获取默认数据和下拉列表map
     *
     * @param formJson  表单设计json
     * @param selectKey 选中字段key
     */
    public ExcelModel getDefaultValue(String formJson, List<String> selectKey) {
        FormDataModel formDataModel = JsonUtil.getJsonToBean(formJson, FormDataModel.class);
        List<FieLdsModel> fieLdsModels = JsonUtil.getJsonToList(formDataModel.getFields(), FieLdsModel.class);
        List<FieLdsModel> allFieLds = new ArrayList<>();
        VisualUtils.recursionFields(fieLdsModels, allFieLds);
        Map<String, String[]> optionMap = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        List<ExcelColumnAttr> models = new ArrayList<>();

        for (String s : selectKey.stream()
                .filter(s -> !s.toLowerCase().startsWith(YunzhupaasKeyConsts.CHILD_TABLE_PREFIX))
                .collect(Collectors.toList())) {
            FieLdsModel fieLdsModel = allFieLds.stream().filter(c -> c.getVModel().equals(s)).findFirst().orElse(null);
            fieLdsModel.setId(fieLdsModel.getVModel());
            models.add(ExcelColumnAttr.builder().key(fieLdsModel.getVModel()).name(fieLdsModel.getLabel())
                    .require(fieLdsModel.getConfig().isRequired()).fontColor(IndexedColors.RED.getIndex()).build());

            dataMap.put(s, VisualUtils.exampleExcelMessage(fieLdsModel));
            String[] options = getOptions(fieLdsModel);
            if (options != null && options.length > 0) {
                optionMap.put(fieLdsModel.getVModel(), options);
            }
        }
        List<FieLdsModel> childFields = allFieLds.stream()
                .filter(f -> f.getConfig().getYunzhupaasKey().equals(YunzhupaasKeyConsts.CHILD_TABLE))
                .collect(Collectors.toList());
        for (FieLdsModel child : childFields) {
            List<String> childList = selectKey.stream().filter(s -> s.startsWith(child.getVModel()))
                    .collect(Collectors.toList());
            childList.stream().forEach(c -> c.replace(child.getVModel() + "-", ""));
            List<FieLdsModel> children = child.getConfig().getChildren();
            List<Map<String, Object>> childData = new ArrayList<>();
            Map<String, Object> childMap = new HashMap<>();
            for (String cl : childList) {
                String substring = cl.substring(cl.indexOf("-") + 1);
                FieLdsModel fieLdsModel = children.stream().filter(c -> c.getVModel().equals(substring)).findFirst()
                        .orElse(null);
                String id = fieLdsModel.getConfig().getParentVModel() + "-" + fieLdsModel.getVModel();
                fieLdsModel.setId(id);
                models.add(ExcelColumnAttr.builder().key(cl).name(fieLdsModel.getLabel())
                        .require(fieLdsModel.getConfig().isRequired()).fontColor(IndexedColors.RED.getIndex()).build());
                childMap.put(substring, VisualUtils.exampleExcelMessage(fieLdsModel));
                String[] options = getOptions(fieLdsModel);
                if (options != null && options.length > 0) {
                    optionMap.put(id, options);
                }
            }
            childData.add(childMap);
            dataMap.put(child.getVModel(), childData);
        }
        return ExcelModel.builder().selectKey(selectKey).models(models).dataMap(dataMap).optionMap(optionMap).build();
    }

    /**
     * 根据配置获取下拉列表
     *
     * @param model
     * @return
     */
    public String[] getOptions(FieLdsModel model) {
        ConfigModel config = model.getConfig();
        String yunzhupaasKey = config.getYunzhupaasKey();
        String[] options = null;
        if (YunzhupaasKeyConsts.SWITCH.equals(yunzhupaasKey)) {
            options = new String[2];
            options[0] = model.getActiveTxt();
            options[1] = model.getInactiveTxt();
        }
        Boolean multiple = model.getMultiple();
        if ((YunzhupaasKeyConsts.SELECT.equals(yunzhupaasKey) && !multiple)
                || YunzhupaasKeyConsts.RADIO.equals(yunzhupaasKey)) {
            String selectOptions = model.getOptions();
            PropsModel props = model.getProps();
            String labelkey = props.getLabel();
            String dataType = model.getConfig().getDataType();
            if ("static".equals(dataType)) {
                List<Map> list = JsonUtil.getJsonToList(selectOptions, Map.class);
                options = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    Map map = list.get(i);
                    String label = (String) map.get(props.getLabel());
                    options[i] = label;
                }
            } else if ("dictionary".equals(dataType)) {
                List<DictionaryDataEntity> list = dictionaryDataApi.getList(model.getConfig().getDictionaryType(),
                        true);
                options = list.stream().map(DictionaryDataEntity::getFullName).collect(Collectors.toList())
                        .toArray(new String[0]);
            } else if ("dynamic".equals(dataType)) {
                ActionResult result = dataInterFaceApi.infoToId(model.getConfig().getPropsUrl(), null, new HashMap<>());
                ArrayList arr = (ArrayList) result.getData();
                options = new String[arr.size()];
                for (int i = 0; i < arr.size(); i++) {
                    Map data = (Map) arr.get(i);
                    options[i] = (String) data.get(labelkey);
                }
            }
        }
        return options;
    }

    /**
     * 获取流程任务状态
     *
     * @param list 功能数据列表
     * @throws WorkFlowException
     */
    public void getFlowStatus(List<Map<String, Object>> list) throws WorkFlowException {
        List<String> ids = new ArrayList<>();
        for (Map<String, Object> item : list) {
            getFLowFields(item);
            if (Objects.nonNull(item.get(FlowFormConstant.FLOWTASKID))) {
                ids.add(item.get(FlowFormConstant.FLOWTASKID).toString());
            }
        }

        List<TaskEntity> tasks = taskApi.getInfosSubmit(ids.toArray(new String[] {}), TaskEntity::getStatus,
                TaskEntity::getId);
        for (Map<String, Object> m : list) {
            if (m != null && Objects.nonNull(m.get(FlowFormConstant.FLOWTASKID))) {
                String flowTaskId = m.get(FlowFormConstant.FLOWTASKID).toString();
                m.put(FlowFormConstant.FLOW_STATE, 0);
                tasks.forEach(i -> {
                    if (i.getId().equals(flowTaskId)) {
                        m.put(FlowFormConstant.FLOW_STATE, i.getStatus());
                    }
                });
            }
        }
    }

    /**
     * 获取流程相关字段
     *
     * @param item
     */
    public void getFLowFields(Map<String, Object> item) {
        Map<String, Object> t = new CaseInsensitiveMap(item);
        String flowTaskId = "";
        if (t != null && t.get(FlowFormConstant.FLOWTASKID) != null) {
            flowTaskId = t.get(FlowFormConstant.FLOWTASKID).toString();
        }
        if (t != null && t.get(TableFeildsEnum.FLOWTASKID.getField()) != null) {
            flowTaskId = t.get(TableFeildsEnum.FLOWTASKID.getField()).toString();
        }
        item.put(FlowFormConstant.FLOWTASKID, flowTaskId);
        String flowId = "";
        if (t != null && t.get(FlowFormConstant.FLOWID) != null) {
            flowId = t.get(FlowFormConstant.FLOWID).toString();
        }
        if (t != null && t.get(TableFeildsEnum.FLOWID.getField()) != null) {
            flowId = t.get(TableFeildsEnum.FLOWID.getField()).toString();
        }
        item.put(FlowFormConstant.FLOWID, flowId);
    }

    /**
     * 主附表单行输入验证
     */
    public void checkUnique(List<FieLdsModel> modelList, Map<String, Object> data, List<String> errList,
            ImportFormCheckUniqueModel uniqueModel) {
        for (int i = 0; i < modelList.size(); i++) {
            FieLdsModel swapDataVo = modelList.get(i);
            String yunzhupaasKey = swapDataVo.getConfig().getYunzhupaasKey();
            Object valueO = data.get(swapDataVo.getVModel());
            String label = swapDataVo.getConfig().getLabel();
            String value = String.valueOf(valueO);
            if (ObjectUtil.isEmpty(valueO)) {
                continue;
            }
            if (YunzhupaasKeyConsts.COM_INPUT.equals(yunzhupaasKey) && uniqueModel.isMain()) {
                if (StringUtil.isNotEmpty(swapDataVo.getMaxlength())) {
                    if (value.length() > Integer.valueOf(swapDataVo.getMaxlength())) {
                        errList.set(i, label + "值超出最多输入字符限制");
                        break;
                    }
                }

                Boolean unique = swapDataVo.getConfig().getUnique();
                if (unique) {
                    try {
                        DbLinkEntity linkEntity = uniqueModel.getLinkEntity();
                        DynamicDataSourceUtil.switchToDataSource(linkEntity);
                        @Cleanup
                        Connection connection = DynamicDataSourceUtil.getCurrentConnection();
                        String databaseProductName = connection.getMetaData().getDatabaseProductName().trim();

                        // 表格中出现多个的唯一值判断
                        boolean exists = false;
                        List<ImportDataModel> importDataModel = uniqueModel.getImportDataModel();
                        List<Map<String, Object>> successList = importDataModel.stream()
                                .map(ImportDataModel::getResultData).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(successList)) {
                            for (int uniqueIndex = 0; uniqueIndex < successList.size(); uniqueIndex++) {
                                if (value.equals(
                                        String.valueOf(successList.get(uniqueIndex).get(swapDataVo.getVModel())))) {
                                    errList.set(i, label + "值已存在");
                                    exists = true;
                                    break;
                                }
                            }
                        }
                        if (exists) {
                            break;
                        }
                        String tableName = Optional.ofNullable(swapDataVo.getConfig().getRelationTable())
                                .orElse(swapDataVo.getConfig().getTableName());
                        // 验证唯一
                        SqlTable sqlTable = SqlTable.of(tableName);
                        String key = flowDataUtil.getTableKey(connection, tableName);
                        String vModelThis = swapDataVo.getVModel();

                        String foriegKey = "";
                        String columnName = "";
                        boolean isMain = uniqueModel.isMain();
                        TableModel mainTableModel = new TableModel();
                        TableModel tableModel = new TableModel();
                        for (TableModel item : uniqueModel.getTableModelList()) {
                            if (Objects.equals(item.getTypeId(), "1")) {
                                mainTableModel = item;
                            }

                            if (StringUtil.isNotEmpty(swapDataVo.getConfig().getRelationTable())) {
                                // 子表判断
                                if (swapDataVo.getConfig().getRelationTable().equals(item.getTable())) {
                                    tableModel = item;
                                }
                            } else {
                                // 主副表判断
                                if (swapDataVo.getConfig().getTableName().equals(item.getTable())) {
                                    tableModel = item;
                                }
                            }
                        }

                        if (tableModel != null) {
                            String fieldName = vModelThis;
                            if (vModelThis.contains("_yunzhupaas_")) {
                                fieldName = vModelThis.split("_yunzhupaas_")[1];
                                isMain = false;
                                foriegKey = tableModel.getTableField();
                            }
                            String finalFieldName = fieldName;
                            TableFields tableFields = tableModel.getFields().stream()
                                    .filter(t -> t.getField().equals(finalFieldName)).findFirst().orElse(null);
                            if (tableFields != null) {
                                columnName = StringUtil.isNotEmpty(tableFields.getField()) ? tableFields.getField()
                                        : fieldName;
                            }
                        }

                        List<BasicColumn> selectKey = new ArrayList<>();
                        selectKey.add(sqlTable.column(columnName));
                        selectKey.add(sqlTable.column(key));
                        if (StringUtil.isNotEmpty(foriegKey)) {
                            String finalForiegKey = foriegKey;
                            TableFields tableFields = tableModel.getFields().stream()
                                    .filter(t -> t.getField().equals(finalForiegKey)).findFirst().orElse(null);
                            if (tableFields != null) {
                                foriegKey = StringUtil.isNotEmpty(tableFields.getField()) ? tableFields.getField()
                                        : finalForiegKey;
                            }
                            selectKey.add(sqlTable.column(foriegKey));
                        }

                        SqlTable sqlMainTable = SqlTable.of(mainTableModel.getTable());
                        String mainKey = flowDataUtil.getKey(mainTableModel, databaseProductName);
                        String taskIdField = TableFeildsEnum.FLOWTASKID.getField();
                        if (databaseProductName.contains("Oracle") || databaseProductName.contains("DM DBMS")) {
                            taskIdField = TableFeildsEnum.FLOWTASKID.getField().toUpperCase();
                        }
                        if (StringUtil.isNotEmpty(uniqueModel.getFlowId())) {
                            selectKey.add(sqlMainTable.column(taskIdField));
                        }

                        QueryExpressionDSL<SelectModel>.QueryExpressionWhereBuilder where;
                        // 是否主表
                        if (isMain) {
                            where = SqlBuilder
                                    .select(selectKey)
                                    .from(sqlTable)
                                    .where(sqlTable.column(columnName), SqlBuilder.isEqualTo(value));
                        } else {
                            where = SqlBuilder
                                    .select(selectKey)
                                    .from(sqlMainTable)
                                    .leftJoin(sqlTable)
                                    .on(sqlTable.column(tableModel.getTableField()),
                                            new EqualTo(sqlMainTable.column(tableModel.getRelationField())))
                                    .where(sqlTable.column(columnName), SqlBuilder.isEqualTo(value));
                        }
                        // 是流程
                        if (StringUtil.isNotEmpty(uniqueModel.getFlowId())) {
                            where.and(sqlMainTable.column(TableFeildsEnum.FLOWID.getField()),
                                    SqlBuilder.isIn(uniqueModel.getFlowIdList()));
                        } else {
                            where.and(sqlMainTable.column(TableFeildsEnum.FLOWID.getField()), SqlBuilder.isNull());
                        }
                        // 开启逻辑删除
                        if (uniqueModel.getLogicalDelete()) {
                            where.and(sqlMainTable.column(TableFeildsEnum.DELETEMARK.getField()), SqlBuilder.isNull());
                        }

                        // 业务主键存在的话需要剔除当前数据
                        if (StringUtil.isNotEmpty(uniqueModel.getId())) {
                            where.and(sqlTable.column(mainKey), SqlBuilder.isNotEqualTo(uniqueModel.getId()));
                        }

                        SelectStatementProvider render = where.build().render(RenderingStrategies.MYBATIS3);
                        List<Map<String, Object>> mapList = flowFormDataMapper.selectManyMappedRows(render);
                        int count = mapList.size();
                        if (count > 0) {
                            errList.set(i, label + "值已存在");
                            break;
                        }
                    } catch (Exception e) {
                        errList.set(i, label + "值不正确");
                    } finally {
                        DynamicDataSourceUtil.clearSwitchDataSource();
                    }
                }
            }
        }
    }
}
