354798ggg
2023-07-24 9a261c1c166bf9ad0ac5cd8f04a0a6dd0ae1408f
项目调整
已添加13个文件
已修改1个文件
4242 ■■■■■ 文件已修改
pom.xml 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/pom.xml 56 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/config/CmnCode.java 75 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/config/CmnConst.java 148 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/controller/SystemDataExportController.java 80 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/controller/SystemDataUploadController.java 358 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/service/OrganizationImportService.java 1824 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/service/SystemDataExportService.java 329 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/service/SystemDataUpLoadService.java 882 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/service/idel/IOrganizationImportService.java 53 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/service/idel/ISystemDataUpLoadService.java 28 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/utli/Custemhandler.java 67 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/utli/CustomMergeStrategy.java 98 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
product-server-data-export-import/src/main/java/com/product/module/data/utli/SystemApiToMethods.java 243 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
@@ -17,6 +17,7 @@
        <module>product-server-project-base</module>
        <module>product-server-project-management</module>
        <module>product-server-project-contract</module>
        <module>product-server-data-export-import</module>
        <module>product-server-web</module>
    </modules>
    <properties>
product-server-data-export-import/pom.xml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,56 @@
<?xml version="1.0"?>
<project
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
        xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.lx</groupId>
        <artifactId>product-server</artifactId>
        <version>2.0.0-release</version>
    </parent>
    <artifactId>product-server-data-export-import</artifactId>
    <name>product-server-data-export-import</name>
    <description>product-server-data-export-import</description>
    <version>2.0.0-release</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.lx</groupId>
            <artifactId>product-server-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.lx</groupId>
            <artifactId>product-server-common</artifactId>
        </dependency>
        <dependency>
            <groupId>com.lx</groupId>
            <artifactId>product-server-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.lx</groupId>
            <artifactId>product-server-file</artifactId>
        </dependency>
        <dependency>
            <groupId>com.lx</groupId>
            <artifactId>product-server-org-admin</artifactId>
        </dependency>
    </dependencies>
</project>
product-server-data-export-import/src/main/java/com/product/module/data/config/CmnCode.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,75 @@
package com.product.module.data.config;
import com.product.common.enums.IEnum;
import com.product.common.enums.ModuleEnum;
public enum CmnCode implements IEnum {
    SYSTEM_OPERATION_SUCCESS("成功", "200"),
    SYSTEM_FORM_NODATA("请求参数为空", ModuleEnum.EXPORT_IMPORT.getValue() + "999"),
    SYSTEM_FORM_COUNT("请求参数有误", ModuleEnum.EXPORT_IMPORT.getValue() + "998"),
    SYSTEM_TABLE_NODATA("请求表名有误", ModuleEnum.EXPORT_IMPORT.getValue() + "997"),
    SYSTEM_ACQUIRE_PARAM_FAIL("获取参数失败", ModuleEnum.EXPORT_IMPORT.getValue() + "996"),
    SYSTEM_CPAGES_NOT_NULL("分页参数不能为空", ModuleEnum.EXPORT_IMPORT.getValue() + "995"),
    EXPORT_GENERAL_LIST_DATA_IMPORT_FIAL("导出列表数据失败", ModuleEnum.EXPORT_IMPORT.getValue() + "001"),
    EXPORT_FILE_NAME_NOT_EMPTY("导出文件名称不能为空", ModuleEnum.EXPORT_IMPORT.getValue() + "002"),
    EXPORT_UPLOAD_URL_NOT_EMPTY("导出数据接口不能为空", ModuleEnum.EXPORT_IMPORT.getValue() + "003"),
    EXPORT_PARAMS_NOT_EMPTY("导出所需参数不能为空", ModuleEnum.EXPORT_IMPORT.getValue() + "004"),
    EXPORT_GET_DATA_EMPTY("导出获取数据为空", ModuleEnum.EXPORT_IMPORT.getValue() + "005"),
    EXPORT_GET_API_METHOD_FILA("导出获取method失败", ModuleEnum.EXPORT_IMPORT.getValue() + "006"),
    EXPORT_REPORT_DATA_FIAL("导出获取method失败", ModuleEnum.EXPORT_IMPORT.getValue() + "007"),
    UPLOAD_TEMPLATE_GET_LIST_FAIL("获取模板导入列表失败", ModuleEnum.EXPORT_IMPORT.getValue() + "101"),
    UPLOAD_TEMPLATE_DELETE_FAIL("删除模板失败", ModuleEnum.EXPORT_IMPORT.getValue() + "102"),
    UPLOAD_TEMPLATE_GET_MAIN_INFO_FAIL("获取模板主表信息失败", ModuleEnum.EXPORT_IMPORT.getValue() + "103"),
    UPLOAD_TEMPLATE_GET_INFO_FAIL("获取模板详情失败", ModuleEnum.EXPORT_IMPORT.getValue() + "104"),
    UPLOAD_TEMPLATE_ADD_FAIL("新增模板失败", ModuleEnum.EXPORT_IMPORT.getValue() + "105"),
    UPLOAD_TEMPLATE_UPDATE_FAIL("修改模板失败", ModuleEnum.EXPORT_IMPORT.getValue() + "106"),
    UPLOAD_TEMPLATE_FIND_FAIL("查询模板详情失败", ModuleEnum.EXPORT_IMPORT.getValue() + "107"),
    UPLOAD_TEMPLATE_DOWNLOAD_FAIL("下载模板失败", ModuleEnum.EXPORT_IMPORT.getValue() + "108"),
    UPLOAD_TEMPLATE_RECORD_DATA_IMPORT_FILE_FAIL("业务数据导入文件失败", ModuleEnum.EXPORT_IMPORT.getValue() + "109"),
    UPLOAD_TEMPLATE_RECORD_DATA_IMPORT_DATA_FAIL("业务数据导入数据失败", ModuleEnum.EXPORT_IMPORT.getValue() + "110"),
    UPLOAD_TEMPLATE_GET_RECORD_TABLE_FAIL("获取业务表信息失败", ModuleEnum.EXPORT_IMPORT.getValue() + "111"),
    UPLOAD_TEMPLATE_IMPORT_DATA_FAIL("导入数据失败", ModuleEnum.EXPORT_IMPORT.getValue() + "112"),
    UPLOAD_TEMPLATE_BEFORE_FUNC_EXEC_FAIL("事件前方法处理执行失败", ModuleEnum.EXPORT_IMPORT.getValue() + "113"),
    UPLOAD_TEMPLATE_BEFORE_FUNC_EXEC_NO_DATA("执行事件前方法处理后数据为空", ModuleEnum.EXPORT_IMPORT.getValue() + "114"),
    UPLOAD_TEMPLATE_AFTER_FUNC_EXEC_FAIL("事件后方法处理执行失败", ModuleEnum.EXPORT_IMPORT.getValue() + "115"),
    UPLOAD_TEMPLATE_GET_UPLOAD_RECORD_FAIL("获取模板导入记录失败", ModuleEnum.EXPORT_IMPORT.getValue() + "116"),
    UPLOAD_TEMPLATE_NOT_ALLOWED_FORMAT("不支持的模板格式", ModuleEnum.EXPORT_IMPORT.getValue() + "117"),
    UPLOAD_TEMPLATE_SAVE_FAIL("模板保存失败", ModuleEnum.EXPORT_IMPORT.getValue() + "118"),
    UPLOAD_TEMPLATE_EXISTS_EMPTY_COL("模板文件中无法存在空列", ModuleEnum.EXPORT_IMPORT.getValue() + "119"),
    GET_MVC_FIRST_PAGE_INFO_FAIL("获取mvc列表信息失败", ModuleEnum.EXPORT_IMPORT.getValue() + "120"),
    GET_EXPORT_PROMPT_LIST_FINAL("获取参照列表失败", ModuleEnum.EXPORT_IMPORT.getValue() + "121")
    ;
    private String text;
    private String value;
    CmnCode(String text, String value) {
        this.text = text;
        this.value = value;
    }
    /**
     * èŽ·å–æžšä¸¾ç±»åž‹å®žä¾‹è¦æ˜¾ç¤ºçš„æ–‡æœ¬ã€‚
     *
     * @return è¿”回枚举类型实例的文本。
     */
    @Override
    public String getText() {
        return text;
    }
    /**
     * èŽ·å–æžšä¸¾ç±»åž‹å®žä¾‹çš„å€¼ã€‚
     *
     * @return è¿”回枚举类型实例的值。
     */
    @Override
    public String getValue() {
        return value;
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/config/CmnConst.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,148 @@
package com.product.module.data.config;
/**
 * @Author cheng
 * @Description å¸¸é‡
 * @Date 2021/6/10 14:36
 * @Version 1.0
 */
public class CmnConst {
    // è¡¨åå¸¸é‡å®šä¹‰
    // åˆ†é¡µå¸¸é‡å®šä¹‰
    public static final String CPAGE = "cpage"; // é¡µæ•°
    public static final String PAGESIZE = "pagesize"; // æ¯é¡µæ¡æ•°
    // è¡¨å
    public static final String TABLE_PRODUCT_SYS_BUTTONS = "product_sys_function_buttons";// mvc-按钮表
    public static final String TABLE_PRODUCT_SYS_MVC_PAGE = "product_sys_mvc_page";// mvc-页面表
    public static final String TABLE_PRODUCT_SYS_MVC_LINK = "product_sys_link";// mvc-连线表
    public static final String TABLE_PRODUCT_SYS_ATTACHMENT = "product_sys_attachments";// é™„件表
    public static final String TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL = "product_sys_data_upload_model";// æ•°æ®ä¸Šä¼ æ¨¡æ¿
    public static final String TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB = "product_sys_data_upload_model_sub";// æ•°æ®ä¸Šä¼ æ¨¡æ¿å­è¡¨
    public static final String TABLE_PRODUCT_SYS_DATA_UPLOAD_RECORD = "product_sys_data_upload_record";// æ•°æ®æ¨¡æ¿å¯¼å…¥è®°å½•表
    public static final String TABLE_PRODUCT_SYS_ORG_LEVELS = "product_sys_org_levels";// ç»„织机构表
    public static final String TABLE_PRODUCT_SYS_DATA_STRATEGY_MASTER = "product_sys_data_strategy_master"; // æ•°æ®æƒé™ä¸»è¡¨
    public static final String TABLE_PRODUCT_SYS_JOB_POSTS_GRADES_MAPPING = "product_sys_job_posts_grades_mapping";
    public static final String TABLE_PRODUCT_SYS_STAFFS = "product_sys_staffs";
    // å…¬å…±å¸¸é‡å®šä¹‰
    public static final String UPDATED_BY = "updated_by"; // ä¿®æ”¹è€…
    public static final String USER_ACCOUNT = "user_account"; // ä¿®æ”¹è€…
    public static final String USER_PWD = "user_pwd"; // ä¿®æ”¹è€…
    public static final String TRICODE = "tricode"; // ä¿®æ”¹è€…
    public static final String USER_NAME = "user_name"; // ä¿®æ”¹è€…
    public static final String USER_ID = "USER_ID"; // ä¿®æ”¹è€…
    public static final String CLIENT_UUID = "client_uuid"; // å®¢æˆ·uuid
    public static final String UPDATED_UTC_DATETIME = "updated_utc_datetime"; // ä¿®æ”¹æ—¶é—´
    public static final String CREATED_BY = "created_by"; // åˆ›å»ºè€…
    public static final String CREATED_UTC_DATETIME = "created_utc_datetime"; // åˆ›å»ºæ—¶é—´
    public static final String STAFF_ID = "staff_id"; // å‘˜å·¥id
    public static final String STAFF_UUID = "staff_uuid"; // å‘˜å·¥uuid
    public static final String ORG_LEVEL_UUID = "org_level_uuid"; // ç»„织架构uuid
    public static final String UUID = "uuid"; // uuid
    public static final String STAFFS_UUID = "staffs_uuid"; // å‘˜å·¥uuid
    public static final String IS_USED = "is_used";// æ˜¯å¦
    public static final String SEQUENCE = "sequence";//排序
    public static final String TABLE_NAME = "table_name";//导出接口参数key
    public static final String EXPORT_PARAM = "export_param";//导出接口参数key
    public static final String FILE_NAME = "file_name";//文件名称
    public static final String START_CPAGE = "start_cpage";//开始页
    public static final String END_CPAGE = "end_cpage";//结束页
    public static final String UPLOAD_API_URL = "upload_api_url";//上传api
    public static final String FIELD_NAME = "field_name";
    public static final String FIELD_DESC = "field_description";
    //组织机构
    public static final String FIELD_ORG_LEVEL_NAME = "org_level_name";
    public static final String FIELD_ORG_LEVEL_ALL = "org_level_all";
    public static final String FIELD_ORG_LEVEL_CODE = "org_level_code";
    public static final String FIELD_ORG_LEVEL_CODE_PARENT = "org_level_code_parent";
    public static final String FIELD_ORG_LEVEL_STATUS = "org_level_status";
    public static final String FIELD_ORG_LEVEL_TYPE = "org_level_type";
    // å²—位等级
    public static final String FIELD_GROUP_NAME = "group_name";
    public static final String FIELD_JOB_GRADE_NAME = "job_grade_name";
    public static final String FIELD_JOB_GRADE_CLASS = "job_grade_class";
    //岗位
    public static final String FIELD_JOB_POST_NAME = "job_post_name";
    public static final String FIELD_DEPT_UUID = "dept_uuid";
    public static final String FIELD_JOB_POST_GRADE = "job_post_grades_uuid";
    //员工
    public static final String FIELD_DIRECT_LEADER_CODE = "direct_leader_code";
    public static final String FIELD_STAFF_CODE = "staff_code";
    public static final String FIELD_GENDER = "gender";
    public static final String FIELD_JOB_POST_GRADE_UUID = "job_post_grade_uuid";
    // é€šç”¨
    public static final String FIELD_ORG_LEVEL_UUID = "org_level_uuid";
    // æ•°æ®æ¨¡æ¿ä¸Šä¼ è¡¨
    public static final String FIELD_UPLOAD_SIGN = "upload_sign";
    public static final String FIELD_TITLE = "title";
    public static final String FIELD_FUNCTION_UUID = "function_uuid";
    public static final String FIELD_BUTTON_UUID = "button_uuid";
    public static final String FIELD_BEFORE_FUNC = "before_func";
    public static final String FIELD_AFTER_FUNC = "after_func";
    public static final String FIELD_TABLE_NAME = "table_name";
    public static final String FIELD_TEMPLATE_INFO = "template_info";
    public static final String FIELD_SHEET_ORDER = "sheet_order";
    // æ•°æ®æ¨¡æ¿ä¸Šä¼ å­è¡¨
    public static final String FIELD_EXCEL_HEADER = "excel_header";
    public static final String FIELD_FIELD_NAME = "field_name";
    public static final String FIELD_FIELD_TYPE = "field_type";
    public static final String FIELD_PROMPT_NAME = "prompt_name";
    public static final String FIELD_IS_MULTI = "is_multi";
    public static final String FIELD_MODEL_UUID = "model_uuid";
    // é™„件表
    public static final String FIELD_ATTACHMENT_URL = "attachment_url";
    public static final String FIELD_ATTACHMENT_TITLE = "attachment_title";// å¤„理之后的附件名称
    // è®°å½•表
    public static final String FIELD_IMPORT_INFO = "import_info";
    public static final String FIELD_IS_SUCCESS = "is_success";
    // æ™®é€šå‚照表
    public static final String FIELD_DICT_LABEL = "dict_label";
    public static final String FIELD_DICT_VALUE = "dict_value";
    // é«˜çº§å‚照表
    public static final String FILED_VIEW_FIELD = "view_fields";
    public static final String FILED_VALUE_FIELD = "value_field";
    public static final String FILED_SOURCE_TABLE = "source_table";
    public static final String FILED_FILTER = "filter";
    // mvc按钮
    public static final String FILED_FUNCTION_UUID = "function_uuid";
    public static final String FILED_BUTTON_NAME = "button_name";
    public static final String FILED_BUTTON_TITLE = "button_title";
    public static final String FILED_STATUS_UUID = "status_uuid";
    public static final String FILED_CATEGORY_UUID = "button_category_uuid";
    public static final String FILED_CLIENT_TYPE_UUID = "client_type_uuid";
    public static final String FILED_ROUTE_NAME = "route_name";
    // mvc页面
    public static final String FIELD_PAGE_NAME = "page_name";
    public static final String FIELD_PAGE_TYPE = "page_type";
    // mvc连线
    public static final String FIELD_LINK_TYPE = "link_type";
    public static final String FIELD_LINE_FROM = "line_from";
    public static final String FIELD_FROM_TYPE = "from_type";
    public static final String FIELD_LINE_TO = "line_to";
    public static final String FIELD_TO_TYPE = "to_type";
    // å›ºå®šç›®å½•
    public static final String DIR_TEMPLATE = "template";// æ¨¡æ¿ç›®å½•
    public static final String DIR_IMPORT = "import";// æ•°æ®å¯¼å…¥ç›®å½•
    public static final String DIR_PRINT = "print";// æ‰“印目录
    public static final String DIR_OTHER = "other";// å…¶ä»–目录
    // ç¼“å­˜
    public static final String CACHE_TABLE = "所有表信息";
    public static final String CACHE_FIELD = "所有表关联信息";
    public static final String CACHE_COMMON_PROMPT = "数据字典配置信息";
    public static final String CACHE_ADVANCED_PROMPT = "高级参照配置信息";
}
product-server-data-export-import/src/main/java/com/product/module/data/controller/SystemDataExportController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,80 @@
package com.product.module.data.controller;
import com.alibaba.druid.util.StringUtils;
import com.product.core.config.CoreConst;
import com.product.core.controller.support.AbstractBaseController;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.module.data.config.CmnCode;
import com.product.module.data.config.CmnConst;
import com.product.module.data.service.SystemDataExportService;
import com.product.module.sys.version.ApiVersion;
import com.product.util.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
/**
 * @Author cheng
 * @Description æ•°æ®å¯¼å‡º
 * @Date 2021/6/10 14:33
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/data/export")
public class SystemDataExportController extends AbstractBaseController {
    @Autowired
    SystemDataExportService systemDataExportService;
    @PostMapping("general-list/{version}")
    @ApiVersion(1)
    public String generalListDataExport(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            if (bean != null) {
                RequestParameterEntity reqp = (RequestParameterEntity) bean;
                fse = reqp.getFormData();
            }
            if (bean == null || fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            // åˆ¤æ–­å‚数是否正常
            if (StringUtils.isEmpty(fse.getString(CmnConst.FILE_NAME))) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.EXPORT_FILE_NAME_NOT_EMPTY.getValue(), CmnCode.EXPORT_FILE_NAME_NOT_EMPTY.getText());
                return this.error(CmnCode.EXPORT_FILE_NAME_NOT_EMPTY.getValue(), CmnCode.EXPORT_FILE_NAME_NOT_EMPTY.getText());
            }
            if (StringUtils.isEmpty(fse.getString(CmnConst.UPLOAD_API_URL))) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.EXPORT_UPLOAD_URL_NOT_EMPTY.getValue(), CmnCode.EXPORT_UPLOAD_URL_NOT_EMPTY.getText());
                return this.error(CmnCode.EXPORT_UPLOAD_URL_NOT_EMPTY.getValue(), CmnCode.EXPORT_UPLOAD_URL_NOT_EMPTY.getText());
            }
            if (BaseUtil.dataTableIsEmpty(fse.getSubDataTable(CmnConst.EXPORT_PARAM))) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.EXPORT_PARAMS_NOT_EMPTY.getValue(), CmnCode.EXPORT_PARAMS_NOT_EMPTY.getText());
                return this.error(CmnCode.EXPORT_PARAMS_NOT_EMPTY.getValue(), CmnCode.EXPORT_PARAMS_NOT_EMPTY.getText());
            }
            systemDataExportService.generalListDataExport(fse.clones());
            return OK();
        } catch (BaseException e) {
            e.printStackTrace();
            SpringMVCContextHolder.getSystemLogger().error(e);
            return error(e);
        } catch (Exception e) {
            e.printStackTrace();
            SpringMVCContextHolder.getSystemLogger().error(e);
            return error(CmnCode.EXPORT_GENERAL_LIST_DATA_IMPORT_FIAL.getValue(), CmnCode.EXPORT_GENERAL_LIST_DATA_IMPORT_FIAL.getText() + e.getMessage());
        }
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/controller/SystemDataUploadController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,358 @@
package com.product.module.data.controller;
import com.alibaba.fastjson.JSONObject;
import com.product.common.lang.StringUtils;
import com.product.core.config.CoreConst;
import com.product.core.controller.support.AbstractBaseController;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.file.config.FileCode;
import com.product.module.data.config.CmnCode;
import com.product.module.data.config.CmnConst;
import com.product.module.data.service.SystemDataUpLoadService;
import com.product.module.data.service.idel.ISystemDataUpLoadService;
import com.product.module.sys.version.ApiVersion;
import com.product.util.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("/api/data-model")
public class SystemDataUploadController extends AbstractBaseController {
    @Autowired
    private SystemDataUpLoadService systemDataUpLoadService;
    /**
     * æ¨¡æ¿ä¸Šä¼ 
     *
     * @return ç»“æžœ
     */
    @RequestMapping(value = "/upload-template/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String uploadTemplate(HttpServletRequest request) {
        try {
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            ISystemDataUpLoadService iSystemDataUpLoadService = (ISystemDataUpLoadService) getProxyInstance(systemDataUpLoadService);
            JSONObject resultObj = iSystemDataUpLoadService.uploadTemplate(rpe);
            return BaseUtil.success(resultObj);
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(FileCode.UPLOAD_FILE_FAIL.getValue(), FileCode.UPLOAD_FILE_FAIL.getText());
        }
    }
    /**
     * æ ¹æ®å·²ç»ä¸Šä¼ çš„excel文件,解析excel表头
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/analysis-template/{version}", method = RequestMethod.POST)
    public String analysisTemplate(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            JSONObject dataJson = systemDataUpLoadService.analysisTemplate(fse);
            return BaseUtil.success(dataJson);
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(CmnCode.UPLOAD_TEMPLATE_GET_INFO_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_GET_INFO_FAIL.getText());
        }
    }
    /**
     * ä¸Šä¼ æ¨¡æ¿æ–°å¢ž
     *
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/save-template/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String saveTemplate(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            ISystemDataUpLoadService iSystemDataUpLoadService = (ISystemDataUpLoadService) getProxyInstance(systemDataUpLoadService);
            iSystemDataUpLoadService.saveTemplate(fse);
            return OK();
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(CmnCode.UPLOAD_TEMPLATE_SAVE_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_SAVE_FAIL.getText());
        }
    }
    @PostMapping("/get-prompt/{version}")
    @ApiVersion(1)
    public String getPromptList() {
        try {
            return BaseUtil.success(systemDataUpLoadService.getPrompt());
        } catch (BaseException e) {
            return this.error(e.getCode(), e.getMessageInfo());
        } catch (Exception e) {
            return error(CmnCode.GET_EXPORT_PROMPT_LIST_FINAL.getValue(), CmnCode.GET_EXPORT_PROMPT_LIST_FINAL.getText());
        }
    }
    /**
     * æ¨¡æ¿å°è´¦-左边树结构
     *
     * @return ç»“æžœ
     */
    @RequestMapping(value = "/list-template/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String listTemplate(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute("requestPara");
            if (bean != null) {
                RequestParameterEntity reqp = (RequestParameterEntity) bean;
                fse = reqp.getFormData();
            }
            if (bean == null || fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            if (StringUtils.isEmpty(fse.getTableName()) || !CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL.equals(fse.getTableName())) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
                return this.error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
            }
            return OK_List(systemDataUpLoadService.listTemplate(fse));
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            return this.error(e.getCode(), e.getMessageInfo());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            logger.error("", e);
            return error(CmnCode.UPLOAD_TEMPLATE_GET_LIST_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_GET_LIST_FAIL.getText());
        }
    }
    /**
     * æŸ¥è¯¢æ¨¡æ¿è¯¦æƒ…
     *
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/find-template/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String findTemplate(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            return OK_List(systemDataUpLoadService.findTemplate(fse));
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(CmnCode.UPLOAD_TEMPLATE_FIND_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_FIND_FAIL.getText());
        }
    }
    /**
     * æ•°æ®ä¸Šä¼ æ¨¡æ¿åˆ é™¤æŽ¥å£
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete-template/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String deleteDataModel(HttpServletRequest request) {
        try {
            //获取传参数据
            FieldSetEntity fse = null;
            Object bean = request.getAttribute("requestPara");
            if (bean != null) {
                RequestParameterEntity reqp = (RequestParameterEntity) bean;
                fse = reqp.getFormData();
            }
            if (bean == null || fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            if (StringUtils.isEmpty(fse.getTableName()) || !CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL.equals(fse.getTableName())) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
                return this.error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
            }
            ISystemDataUpLoadService iSystemDataUpLoadService = (ISystemDataUpLoadService) getProxyInstance(systemDataUpLoadService);
            iSystemDataUpLoadService.deleteModel(fse);
            return OK();
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            return this.error(e.getCode(), e.getMessageInfo());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            logger.error("", e);
            return error(CmnCode.UPLOAD_TEMPLATE_DELETE_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_DELETE_FAIL.getText());
        }
    }
    /**
     * æ¨¡æ¿ä¸‹è½½
     *
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/download-template/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            systemDataUpLoadService.downloadTemplate(fse, response);
            return OK();
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(CmnCode.UPLOAD_TEMPLATE_DOWNLOAD_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_DOWNLOAD_FAIL.getText());
        }
    }
    /**
     * ä¸šåŠ¡åŠŸèƒ½å¯¼å…¥-上传文件
     *
     * @param request
     * @return
     * @throws IOException
     * @throws BaseException
     */
    @RequestMapping(value = "/record-data-import/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String recordDataImport(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            if (StringUtils.isEmpty(fse.getTableName()) || !CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_RECORD.equals(fse.getTableName())) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
                return this.error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
            }
            ISystemDataUpLoadService iSystemDataUpLoadService = (ISystemDataUpLoadService) getProxyInstance(systemDataUpLoadService);
            String uuid = iSystemDataUpLoadService.recordDataImport(rpe);
            return OK_Add(uuid);
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(CmnCode.UPLOAD_TEMPLATE_RECORD_DATA_IMPORT_FILE_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_RECORD_DATA_IMPORT_FILE_FAIL.getText());
        }
    }
    /**
     * ä¸šåŠ¡åŠŸèƒ½å¯¼å…¥-解析并保存到数据库
     *
     * @param request
     * @return
     * @throws IOException
     * @throws BaseException
     */
    @RequestMapping(value = "/record-data-save/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String recordDataSave(HttpServletRequest request) {
        try {
            FieldSetEntity fse = null;
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity rpe = (RequestParameterEntity) bean;
            if (null != rpe && null != rpe.getFormData()) {
                fse = rpe.getFormData();
            }
            if (fse == null) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
                return this.error(CmnCode.SYSTEM_FORM_NODATA.getValue(), CmnCode.SYSTEM_FORM_NODATA.getText());
            }
            if (StringUtils.isEmpty(fse.getTableName()) || !CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_RECORD.equals(fse.getTableName())) {
                SpringMVCContextHolder.getSystemLogger().error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
                return this.error(CmnCode.SYSTEM_TABLE_NODATA.getValue(), CmnCode.SYSTEM_TABLE_NODATA.getText());
            }
            ISystemDataUpLoadService iSystemDataUpLoadService = (ISystemDataUpLoadService) getProxyInstance(systemDataUpLoadService);
            iSystemDataUpLoadService.recordDataSave(fse);
            return OK();
        } catch (BaseException e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(e);
            e.printStackTrace();
            return error(CmnCode.UPLOAD_TEMPLATE_RECORD_DATA_IMPORT_FILE_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_RECORD_DATA_IMPORT_FILE_FAIL.getText());
        }
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/service/OrganizationImportService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,1824 @@
package com.product.module.data.service;
import com.google.common.collect.Sets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.product.admin.service.UpdateLoginUserInfoService;
import com.product.common.lang.StringUtils;
import com.product.common.utils.IdcardUtils;
import com.product.core.config.Global;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.exception.BaseException;
import com.product.core.service.support.AbstractBaseService;
import com.product.core.spring.context.SpringBeanUtil;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.module.data.config.CmnCode;
import com.product.module.data.config.CmnConst;
import com.product.module.data.service.idel.IOrganizationImportService;
import com.product.module.sys.entity.SystemUser;
import com.product.org.admin.service.StaffManagerService;
import com.product.util.BaseUtil;
import com.product.util.CallBack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
 * @ClassName OrganizationImportService
 * @Description ç»„织机构导入数据处理
 * @Author cheng
 * @Date 2021/12/2 16:14
 */
@Service
public class OrganizationImportService extends AbstractBaseService implements IOrganizationImportService {
    @Autowired
    StaffManagerService staffManagerService;
    private final String companyLevelSeparator = ">";
    /**
     * å¯¼å…¥å…¬å¸ ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param dt
     * @throws BaseException
     */
    @Override
    public DataTableEntity importCompanyBefore(DataTableEntity dt) throws BaseException {
        ImportErrorEntity errorEntity = new ImportErrorEntity();
        try {
            SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
            //管理员权限验证
            managerPermissionValidation(errorEntity, currentUser);
            FieldSetEntity managerFieldSet = currentUser.getCurrentManager();
            String managerCompany = managerFieldSet.getString(CmnConst.ORG_LEVEL_UUID);
            // å½“前管理员管理的公司
            String managerCompanyUuids = currentUser.getCurrentCompany().getString(CmnConst.ORG_LEVEL_UUID);
            if (!BaseUtil.dataTableIsEmpty(dt)) {
                //数据验证结果
                Map<String, String> fieldType = Maps.newHashMap();
                fieldType.put(CmnConst.SEQUENCE, "int");
                errorEntity = fieldRequiredValidation(dt, new String[]{CmnConst.FIELD_ORG_LEVEL_NAME, CmnConst.FIELD_ORG_LEVEL_ALL, CmnConst.SEQUENCE}, null, f -> {
                    if (f != null && f[0] != null) {
                        FieldSetEntity fse = f[0];
                        //公司名称
                        String companyName = fse.getString(CmnConst.FIELD_ORG_LEVEL_NAME);
                        //公司全称
                        String companyAllName = fse.getString(CmnConst.FIELD_ORG_LEVEL_ALL);
                        //上级公司全称
                        String parentAllName = companyAllName.replace(companyLevelSeparator + companyName, "");
                        fse.setValue("parentAllName", parentAllName);
                    }
                });
                DataTableEntity systemData = getBaseDao().listTable(CmnConst.TABLE_PRODUCT_SYS_ORG_LEVELS, " org_level_type=0 AND "
                        + BaseUtil.buildQuestionMarkFilter(CmnConst.ORG_LEVEL_UUID, managerCompanyUuids.split(","), true), new Object[]{}, "org_level_code");
                // éªŒè¯é‡å¤ & åˆå¹¶é”™è¯¯ä¿¡æ¯
                errorEntity.mergeError(fieldRepeatValidation(dt, systemData, CmnConst.FIELD_ORG_LEVEL_ALL));
                if (errorEntity.isError) {
                    errorEntity.newThrowBaseException();
                }
                List<FieldSetEntity> data = dt.getData();
                data.sort((a, b) -> {
                    String Aorg_level_all = a.getString(CmnConst.FIELD_ORG_LEVEL_ALL);
                    String Borg_level_all = b.getString(CmnConst.FIELD_ORG_LEVEL_ALL);
                    int lengthA = Aorg_level_all != null ? Aorg_level_all.length() : -1;
                    int lengthB = Borg_level_all != null ? Borg_level_all.length() : -1;
                    return lengthA - lengthB;
                });
                // èŽ·å–å½“å‰ç®¡ç†ç®¡ç†å…¬å¸ä»¥åŠå­å…¬å¸
                DataTableEntity allCompany = getBaseDao().listTable(CmnConst.TABLE_PRODUCT_SYS_ORG_LEVELS, " org_level_type=0 AND "
                        + BaseUtil.buildQuestionMarkFilter(CmnConst.ORG_LEVEL_UUID, managerCompanyUuids.split(","), true), new Object[]{}, "org_level_code");
                Map<String, String> levelCode = Maps.newHashMap();
                if (!BaseUtil.dataTableIsEmpty(allCompany)) {
                    for (int i = 0; i < allCompany.getRows(); i++) {
                        String org_level_all = allCompany.getString(i, CmnConst.FIELD_ORG_LEVEL_ALL);
                        String org_level_code = allCompany.getString(i, CmnConst.FIELD_ORG_LEVEL_CODE);
                        // å°†å…¬å¸ç¼–码用全称存储
                        levelCode.put(org_level_all, org_level_code);
                    }
                }
                for (FieldSetEntity fse : data) {
                    //当前行
                    Integer rowIndex = fse.getInteger("~row~");
                    //公司全称
                    String companyAllName = fse.getString(CmnConst.FIELD_ORG_LEVEL_ALL);
                    //上级组织机构全称
                    String parentAllName = fse.getString("parentAllName");
                    //上级机构编码
                    String code = levelCode.get(parentAllName);
                    if (StringUtils.isEmpty(code)) {
                        errorEntity.addError(rowIndex, " èŽ·å–ä¸Šçº§æœºæž„ç¼–ç é”™è¯¯ï¼Œè¯·æ£€æŸ¥å…¬å¸åç§°ã€å…¨ç§°æ˜¯å¦æ­£ç¡®ï¼Œé”™è¯¯è¡Œå·ï¼š").append(rowIndex + 1);
                        continue;
                    }
                    //初始化公司数据
                    initOrganizationFieldSet(fse, currentUser.getClient_uuid(), code, 0);
                    // å°†å½“前公司生成的org_level_code æ”¾å…¥map中
                    levelCode.put(companyAllName, fse.getString(CmnConst.FIELD_ORG_LEVEL_CODE));
                    String uuid = null;
                    try {
                        // ä¿å­˜å‡ºé”™ç›´æŽ¥è·³è¿‡è¯¥æ¡æ•°æ®
                        getBaseDao().add(fse);
                    } catch (Exception e) {
                        continue;
                    }
                    if (null != uuid) {
                        // å¯¼å…¥æ—¶åˆ›å»ºè¯¥å…¬å¸çš„æ•°æ®æƒé™
                        FieldSetEntity fs = new FieldSetEntity();
                        fs.setTableName(CmnConst.TABLE_PRODUCT_SYS_DATA_STRATEGY_MASTER);
//                        fs.setValue(CmnConst.ORG_LEVEL_UUID, uuid);
                        fs.setValue("property_uuid", "001");
                        fs.setValue("is_used", "1");
                        fs.setValue("effective_start_date", new Date());
                        fs.setValue(CmnConst.CREATED_BY, currentUser.getUser_id());
                        fs.setValue(CmnConst.CREATED_UTC_DATETIME, new Date());
                        getBaseDao().add(fs);
                    }
                }
                // å›žå†™åˆ°éšè—ç®¡ç†å‘˜æ‰€ç®¡ç†çš„公司 todo group_concat å¤ªå¤šä¼šæŠ¥é”™
                getBaseDao().executeUpdate("UPDATE product_sys_org_manager SET org_level_uuid =(SELECT group_concat(UUID) FROM product_sys_org_levels WHERE CLIENT_UUID =? AND ORG_LEVEL_TYPE =0) WHERE CLIENTS_UUID=? AND MANAGER_TYPE=? "
                        , new Object[]{currentUser.getClient_uuid(), currentUser.getClient_uuid(), 3});
                // å›žå†™å½“前管理员管理的公司
                if (currentUser.getUserType() == 2 && dt.getUuids() != null) {
                    if (!StringUtils.isEmpty(managerCompany)) {
                        managerCompany += ",";
                    } else {
                        managerCompany = "";
                    }
                    managerCompany += dt.getUuidsToString();
                    String manager_uuid = managerFieldSet.getUUID();
                    String sql = "update product_sys_org_manager set org_level_uuid=? where uuid=?";
                    getBaseDao().executeUpdate(sql, new Object[]{managerCompany, manager_uuid});
                }
                //抛出错误
                if (errorEntity.isError) {
                    errorEntity.newThrowBaseException();
                }
                UpdateLoginUserInfoService loginUserInfoService = SpringBeanUtil.getBean("updateLoginUserInfoService", UpdateLoginUserInfoService.class);
                loginUserInfoService.updateUserInfoByUserId(new Object[]{currentUser.getUser_id()}, false);
                return dt;
            } else {
                errorEntity.newThrowBaseException("导入公司失败,未提取到数据");
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            errorEntity.addError(0, "导入公司失败,未知错误 ï¼Œ" + e.getMessage());
            errorEntity.newThrowBaseException();
        }
        return null;
    }
    /**
     * å­—段重复验证
     *
     * @param errorEntity
     * @param importData  å¯¼å…¥æ•°æ®
     * @param systemData  ç³»ç»Ÿæ•°æ® ï¼ˆå¯é€‰ï¼‰
     * @param fieldNames  å­—段名称
     * @return
     * @throws BaseException
     */
    protected ImportErrorEntity fieldRepeatValidation(ImportErrorEntity errorEntity, DataTableEntity importData, DataTableEntity systemData, String[] fieldNames) throws BaseException {
        if (fieldNames == null || fieldNames.length <= 0) {
            return errorEntity;
        }
        List<FieldSetEntity> dataList = importData.clones().getData();
        Map<String, Object> valueMap = Maps.newHashMap();
        if (!BaseUtil.dataTableIsEmpty(systemData)) {
            for (int i = 0; i < systemData.getRows(); i++) {
                for (String field : fieldNames) {
                    String value = systemData.getString(i, field);
                    if (!StringUtils.isEmpty(value)) {
                        valueMap.put(field + this.companyLevelSeparator + value, Boolean.FALSE);
                    }
                }
            }
        }
        fieldRepeatValidation(errorEntity, dataList, valueMap, fieldNames);
        return errorEntity;
    }
    /**
     * å­—段重复验证
     *
     * @param dataList   å¯¼å…¥æ•°æ®
     * @param valueMap
     * @param fieldNames å­—段名称
     * @throws BaseException
     */
    protected void fieldRepeatValidation(ImportErrorEntity errorEntity, List<FieldSetEntity> dataList, Map<String, Object> valueMap, String[] fieldNames) throws BaseException {
        for (FieldSetEntity fse : dataList) {
            DataLocation dataLocation = getDataLocation(fse);
            for (String fieldName : fieldNames) {
                String value = fse.getString(fieldName);
                if (!StringUtils.isEmpty(value)) {
                    if (valueMap.get(fieldName + this.companyLevelSeparator + value) != null) {
                        Object val = valueMap.get(fieldName + this.companyLevelSeparator + value);
                        if (val != null) {
                            String error;
                            if (val instanceof Boolean) {
                                // ç³»ç»Ÿä¸­å­˜åœ¨
                                // ç¬¬ N è¡Œï¼Œç¬¬ N åˆ—,'表头名称' ('数据值') æ•°æ®é‡å¤ï¼Œåœ¨ç³»ç»Ÿä¸­å·²å­˜åœ¨
                                error = "第 %s è¡Œï¼Œç¬¬ %s åˆ— '%s', æ•°æ®é‡å¤ï¼Œåœ¨ç³»ç»Ÿä¸­å·²å­˜åœ¨";
                                error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(fieldName), dataLocation.getColName(fieldName), value);
                            } else {
                                FieldSetEntity fs = (FieldSetEntity) val;
                                DataLocation historyLocation = getDataLocation(fs);
                                // ç¬¬N行,第 N列,'表头名称' ('数据值') æ•°æ®å’Œç¬¬ %s è¡Œï¼Œç¬¬N行,第 N列,'表头名称' ('数据值') æ•°æ®é‡å¤
                                error = "第 %s è¡Œï¼Œç¬¬ %s åˆ— '%s', æ•°æ®å’Œç¬¬ %s è¡Œï¼Œç¬¬ %s åˆ— '%s' ,数据重复";
                                error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(fieldName), dataLocation.getColName(fieldName), value,
                                        historyLocation.getRowIndex(), historyLocation.getColIndex(fieldName), historyLocation.getColName(fieldName), value);
                            }
                            errorEntity.addError(dataLocation.getRowIndex(), error);
                        }
                    } else {
                        valueMap.put(fieldName + this.companyLevelSeparator + value, fse);
                    }
                }
            }
        }
    }
    /**
     * å­—段重复验证
     *
     * @param importData å¯¼å…¥æ•°æ®
     * @param systemData ç³»ç»Ÿæ•°æ® ï¼ˆå¯é€‰ï¼‰
     * @param fieldName  å­—段名称
     * @return
     * @throws BaseException
     */
    protected ImportErrorEntity fieldRepeatValidation(DataTableEntity importData, DataTableEntity
            systemData, String fieldName) throws BaseException {
        return fieldRepeatValidation(new ImportErrorEntity(), importData, systemData, new String[]{fieldName});
    }
    /**
     * å­—段必填验证
     *
     * @param dt
     * @return
     * @throws BaseException
     */
    protected ImportErrorEntity fieldRequiredValidation(DataTableEntity dt, String[]
            fieldNames, Map<String, String> fieldType, CallBack<FieldSetEntity> callBack) throws BaseException {
        ImportErrorEntity errorEntity = new ImportErrorEntity();
        for (int i = 0; i < dt.getRows(); i++) {
            FieldSetEntity fieldSetEntity = dt.getFieldSetEntity(i);
            if (callBack != null) {
                callBack.method(fieldSetEntity);
            }
            fieldRequiredValidation(errorEntity, fieldSetEntity, fieldNames, fieldType);
        }
        return errorEntity;
    }
    /**
     * å­—段类型验证
     * ç›®å‰æ”¯æŒ int  double dateTime
     *
     * @param errorEntity
     * @param fse
     * @param fieldTypeMap
     * @return
     * @throws BaseException
     */
    protected boolean fieldTypeValidation(ImportErrorEntity errorEntity, FieldSetEntity
            fse, Map<String, String> fieldTypeMap) throws BaseException {
        boolean flag = true;
        if (fieldTypeMap != null && fieldTypeMap.size() > 0 && fse != null) {
            for (Map.Entry<String, String> v : fieldTypeMap.entrySet()) {
                String fieldType = v.getValue();
                String key = v.getKey();
                Object value = fse.getObject(key);
                if (value == null) {
                    continue;
                }
                String type = null;
                String msg = "";
                try {
                    switch (fieldType) {
                        case "int":
                            type = "整数";
                            fse.getInteger(key);
                            continue;
                        case "dateTime":
                            type = "日期";
                            Date date = fse.getDate(key);
                            fse.setValue(key, date);
                            continue;
                        case "double":
                            type = "小数";
                            fse.getDouble(key);
                            continue;
                        case "mobile_phone":
                            type = "移动电话";
                            String phone = fse.getString(key);
                            // éªŒè¯æ˜¯å¦ä¸ºä¸­å›½å¤§é™† æ‰‹æœºå·
                            if (!BaseUtil.isChinaPhoneLegal(phone)) {
                                throw new BaseException("", "");
                            }
                            continue;
                        case "id_card":
                            type = "身份证号码";
                            String idCard = fse.getString(key);
                            // éªŒè¯èº«ä»½è¯å·ç æ˜¯å¦åˆæ³•
                            if (IdcardUtils.validateCard(idCard)) {
                                msg = BaseUtil.idCardVerification(idCard);
                                throw new BaseException("", "");
                            }
                            continue;
                        case "email":
                            type = "邮箱";
                            String email = fse.getString(key);
                            // é‚®ç®±éªŒè¯
                            if (!BaseUtil.isEmail(email)) {
                                throw new BaseException("", "");
                            }
                            continue;
                        case "sex":
                            type = "性别";
                            String sex = fse.getString(key);
                            // é‚®ç®±éªŒè¯
                            if (!"男".equals(sex) && !"女".equals(sex)) {
                                throw new BaseException("", "");
                            }
                            continue;
                        default:
                    }
                } catch (BaseException e) {
                    DataLocation dataLocation = getDataLocation(fse);
                    String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,数据类型错误" + (type != null ? ",请输入正确的 '%s'值" : "");
                    if (type != null) {
                        error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(key), type);
                    } else {
                        error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(key));
                    }
                    if (!StringUtils.isEmpty(msg)) {
                        error += "," + msg;
                    }
                    errorEntity.addError(dataLocation.getRowIndex(), error);
                    flag = false;
                }
            }
        }
        return flag;
    }
    /**
     * å­—段必填验证
     *
     * @param fse
     * @return
     * @throws BaseException
     */
    private boolean fieldRequiredValidation(ImportErrorEntity errorEntity, FieldSetEntity fse, String[]
            fieldNames, Map<String, String> fieldType) throws BaseException {
        if (fse == null || fieldNames == null || fieldNames.length <= 0) {
            return true;
        }
        DataLocation dataLocation = getDataLocation(fse);
        boolean flag = true;
        for (String fieldName : fieldNames) {
            if (!StringUtils.isEmpty(fieldName)) {
                String value = fse.getString(fieldName);
                if (StringUtils.isEmpty(value)) {
                    String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ— '%s', ä¸èƒ½ä¸ºç©º";
                    Integer rowIndex = dataLocation.getRowIndex();
                    String colIndex = dataLocation.getColIndex(fieldName);
                    String colName = dataLocation.getColName(fieldName);
                    error = String.format(error, rowIndex, colIndex, colName);
                    errorEntity.addError(rowIndex, error);
                    flag = false;
                }
            }
        }
        if (flag) {
            return fieldTypeValidation(errorEntity, fse, fieldType);
        } else {
            fieldTypeValidation(errorEntity, fse, fieldType);
            return false;
        }
    }
    /**
     * å¯¼å…¥éƒ¨é—¨ ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param dt
     * @throws BaseException
     */
    @Override
    public DataTableEntity importDeptBefore(DataTableEntity dt) throws BaseException {
        ImportErrorEntity errorEntity = new ImportErrorEntity();
        if (!BaseUtil.dataTableIsEmpty(dt)) {
            try {
                SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
                //管理员权限验证
                managerPermissionValidation(errorEntity, currentUser);
                Map<String, String> fieldType = Maps.newHashMap();
                fieldType.put(CmnConst.SEQUENCE, "int");
                //数据必填验证结果
                errorEntity = fieldRequiredValidation(dt, new String[]{CmnConst.FIELD_ORG_LEVEL_NAME, CmnConst.FIELD_ORG_LEVEL_ALL, CmnConst.SEQUENCE, CmnConst.ORG_LEVEL_UUID}, fieldType, null);
                if (errorEntity.isError) {
                    errorEntity.newThrowBaseException();
                }
                FieldSetEntity currentManager = currentUser.getCurrentManager();
                String managerCompanyUuids = currentManager.getString(CmnConst.ORG_LEVEL_UUID);
                String uuidFilter = BaseUtil.buildQuestionMarkFilter("uuid", managerCompanyUuids.split(","), true);
                StringBuilder sql = new StringBuilder(8);
                sql.append(" select uuid,org_level_name,org_level_code, ");
                sql.append(" org_level_code_parent,org_level_all,org_level_type ");
                sql.append(" FROM product_sys_org_levels where client_uuid=?  and ( ");
                sql.append(" ( ");
                sql.append("  ").append(uuidFilter);
                sql.append(" AND org_level_type=0 ) ");
                sql.append(" or ( ");
                sql.append("  ").append(uuidFilter.replace("uuid", "org_level_uuid"));
                sql.append(" AND org_level_type=1 ) ");
                sql.append(" )  order by org_level_code,org_level_type");
                // ç³»ç»Ÿæ•°æ®
                DataTableEntity systemData = getBaseDao().listTable(sql.toString(), new Object[]{currentUser.getClient_uuid()});
                importDeptBefore(dt, systemData, currentUser, errorEntity);
                return dt;
            } catch (BaseException e) {
                e.printStackTrace();
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
                errorEntity.addError(0, "导入部门失败,未知错误 ï¼Œ" + e.getMessage());
                errorEntity.newThrowBaseException();
            }
        }
        errorEntity.newThrowBaseException("导入公司失败,未提取到数据");
        return null;
    }
    private void importDeptBefore(DataTableEntity dt, DataTableEntity systemData, SystemUser
            user, ImportErrorEntity errorEntity) throws BaseException {
        List<FieldSetEntity> data = dt.getData();
        // æœºæž„全称排序
        data.sort(Comparator.comparing(a -> a.getString(CmnConst.FIELD_ORG_LEVEL_ALL)));
        if (BaseUtil.dataTableIsEmpty(systemData)) {
            errorEntity.newThrowBaseException("获取系统机构信息失败,请联系管理员 ");
        }
        List<FieldSetEntity> systemDataList = systemData.getData();
        // å…¬å¸
        Map<String, FieldSetEntity> companyMap = Maps.newHashMap();
        // éƒ¨é—¨
        Map<String, FieldSetEntity> deptMap = Maps.newHashMap();
        for (FieldSetEntity fse : systemDataList) {
            // æœºæž„类型
            String orgLevelType = fse.getString(CmnConst.FIELD_ORG_LEVEL_TYPE);
            // æœºæž„全称
            String org_level_all = fse.getString(CmnConst.FIELD_ORG_LEVEL_ALL);
            Map<String, FieldSetEntity> map;
            if ("0".equals(orgLevelType)) {
                map = companyMap;
            } else if ("1".equals(org_level_all)) {
                map = deptMap;
            } else {
                continue;
            }
            map.put(org_level_all, fse);
        }
        for (int i = 0; i < dt.getRows(); i++) {
            FieldSetEntity fse = dt.getFieldSetEntity(i);
            // å…¬å¸å…¨ç§°
            String companyAllName = fse.getString(CmnConst.ORG_LEVEL_UUID);
            // éƒ¨é—¨å…¨ç§°
            String deptAllName = fse.getString(CmnConst.FIELD_ORG_LEVEL_ALL);
            // éƒ¨é—¨åç§°
            String deptName = fse.getString(CmnConst.FIELD_ORG_LEVEL_NAME);
            DataLocation dataLocation = getDataLocation(fse);
            FieldSetEntity companyFse = companyMap.get(companyAllName);
            if (companyFse == null || StringUtils.isEmpty(companyFse.getUUID())) {
                String error = "第 %s è¡Œï¼Œä¸Šçº§æœºæž„获取失败,所属公司不存在,请检查' %s '是否正确:' %s '";
                error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColName(CmnConst.ORG_LEVEL_UUID), companyAllName);
                errorEntity.addError(dataLocation.getRowIndex(), error);
                continue;
            }
            String error = "第 %s è¡Œï¼Œä¸Šçº§æœºæž„获取失败,上级部门不存在,请检查' %s '是否正确:' %s '";
            // éƒ¨é—¨ä¸Šçº§å…¨ç§°
            String parentDeptAllName = getParentAllName(deptAllName, deptName);
            if (StringUtils.isEmpty(parentDeptAllName)) {
                error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColName(CmnConst.FIELD_ORG_LEVEL_ALL), deptAllName);
                errorEntity.addError(dataLocation.getRowIndex(), error);
                continue;
            }
            // ä¸Šçº§ç¼–码
            String code;
            // ä¸Šçº§æœºæž„çš„uuid
            String parentUuid;
            if (!parentDeptAllName.equals(companyAllName)) {
                FieldSetEntity deptFse = deptMap.get(parentDeptAllName);
                if (deptFse == null || StringUtils.isEmpty(deptFse.getUUID())) {
                    error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColName(CmnConst.FIELD_ORG_LEVEL_ALL), deptAllName);
                    errorEntity.addError(dataLocation.getRowIndex(), error);
                    continue;
                }
                // å–出上级部门的code作为上级编码
                code = deptFse.getString(CmnConst.FIELD_ORG_LEVEL_CODE);
                parentUuid = deptFse.getString(CmnConst.ORG_LEVEL_UUID);
            } else {
                // å–出上级公司的code作为上级编码
                code = companyFse.getString(CmnConst.FIELD_ORG_LEVEL_CODE);
                parentUuid = companyFse.getUUID();
            }
            initOrganizationFieldSet(fse, user.getClient_uuid(), code, 1);
            fse.setValue(CmnConst.ORG_LEVEL_UUID, parentUuid);
            getBaseDao().saveFieldSetEntity(fse);
            deptMap.put(deptAllName, fse);
        }
        if (errorEntity.isError) {
            errorEntity.newThrowBaseException();
        }
    }
    private String getParentAllName(String allName, String name) {
        if (!StringUtils.isEmpty(allName) && !StringUtils.isEmpty(name)) {
            int index = allName.indexOf(this.companyLevelSeparator + name);
            if (index > -1) {
                return allName.substring(0, index);
            }
        }
        return "";
    }
    /**
     * å¯¼å…¥å²—位等级 ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param dt
     * @throws BaseException
     */
    @Override
    public DataTableEntity importPostLevelBefore(DataTableEntity dt) throws BaseException {
        ImportErrorEntity errorEntity = new ImportErrorEntity();
        try {
            if (!BaseUtil.dataTableIsEmpty(dt)) {
                SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
                //管理员权限验证
                managerPermissionValidation(errorEntity, currentUser);
                // å½“前管理员管理的公司
                String managerCompanyUuids = currentUser.getCurrentManager().getString(CmnConst.ORG_LEVEL_UUID);
                Map<String, List<FieldSetEntity>> groupCompany = Maps.newHashMap();
                Map<String, String> fieldType = Maps.newHashMap();
                fieldType.put(CmnConst.SEQUENCE, "int");
                fieldType.put(CmnConst.FIELD_JOB_GRADE_CLASS, "int");
                StringBuilder sql = new StringBuilder();
                sql.append(" select concat( ");
                sql.append(" org_level_uuid,'>',job_grade_name) uuid ");
                sql.append("  FROM product_sys_job_post_grades where ");
                sql.append(BaseUtil.buildQuestionMarkFilter("org_level_uuid", managerCompanyUuids.split(","), true));
                DataTableEntity systemData = getBaseDao().listTable(sql.toString(), new Object[]{});
                Set<Object> systemDataSet = Sets.newHashSet();
                if (!BaseUtil.dataTableIsEmpty(systemData)) {
                    systemDataSet.addAll(Arrays.asList(systemData.getUuidsToString().split(",")));
                }
                for (int i = 0; i < dt.getRows(); i++) {
                    FieldSetEntity fse = dt.getFieldSetEntity(i);
                    // å­—段必填验证
                    boolean validation = fieldRequiredValidation(errorEntity, fse, new String[]{CmnConst.ORG_LEVEL_UUID, CmnConst.FIELD_JOB_GRADE_NAME, CmnConst.SEQUENCE, CmnConst.FIELD_JOB_GRADE_CLASS}, fieldType);
                    if (!validation) {
                        // éªŒè¯æœªé€šè¿‡ è·³è¿‡è¯¥æ¡æ•°æ®
                        continue;
                    }
                    // å…¬å¸å…¨ç§°
                    String companyAllName = fse.getString(CmnConst.ORG_LEVEL_UUID);
                    List<FieldSetEntity> groupPostGradeList = groupCompany.get(companyAllName);
                    if (groupPostGradeList == null) {
                        groupPostGradeList = Lists.newArrayList();
                        groupCompany.put(companyAllName, groupPostGradeList);
                    }
                    groupPostGradeList.add(fse);
                }
                if (errorEntity.isError) {
                    errorEntity.newThrowBaseException();
                }
                Set<String> companyAllNames = groupCompany.keySet();
                sql = new StringBuilder();
                sql.append(" select uuid,org_level_all ");
                sql.append(" FROM product_sys_org_levels ");
                sql.append(" where ");
                sql.append(BaseUtil.buildQuestionMarkFilter("uuid", managerCompanyUuids.split(","), true));
                sql.append(" AND ");
                sql.append(BaseUtil.buildQuestionMarkFilter("org_level_all", companyAllNames.toArray(), true));
                // æ ¹æ®ç”¨æˆ·ä¸Šä¼ çš„公司全称 & è¯¥ç®¡ç†å‘˜ç®¡ç†çš„æ‰€æœ‰å…¬å¸ è¿›è¡ŒæŸ¥è¯¢å…¬å¸çš„uuid
                DataTableEntity companyInfo = getBaseDao().listTable(sql.toString(), new Object[]{});
                // å®šä¹‰æ²¡æœ‰æ‰¾åˆ°å…¬å¸çš„æ•°æ® å†™å…¥é”™è¯¯æ–¹æ³•
                CallBack<FieldSetEntity> callBack = (value) -> {
                    for (FieldSetEntity fs : value) {
                        DataLocation dataLocation = getDataLocation(fs);
                        String error = "第 %s è¡Œï¼Œç¬¬ %s æ•°æ®é”™è¯¯,所属公司不存在,请检查列 '%s'";
                        errorEntity.addError(dataLocation.getRowIndex(), String.format(error,
                                dataLocation.getRowIndex(),
                                dataLocation.getColIndex(CmnConst.ORG_LEVEL_UUID),
                                dataLocation.getColName(CmnConst.ORG_LEVEL_UUID)));
                    }
                };
                // æ²¡æœ‰æŸ¥è¯¢åˆ°æ‰€æœ‰å…¬å¸ä¿¡æ¯
                if (BaseUtil.dataTableIsEmpty(companyInfo)) {
                    for (List<FieldSetEntity> value : groupCompany.values()) {
                        // å¾ªçŽ¯å†™å…¥é”™è¯¯
                        callBack.method(value.toArray(new FieldSetEntity[]{}));
                    }
                    errorEntity.newThrowBaseException();
                } else {
                    // copy å…¬å¸å…¨ç§°
                    Set<String> companyNames = Sets.newHashSet();
                    companyNames.addAll(companyAllNames);
                    // å¾ªçŽ¯æŸ¥è¯¢çš„å…¬å¸ç»“æžœ
                    for (int i = 0; i < companyInfo.getRows(); i++) {
                        String uuid = companyInfo.getString(i, CmnConst.UUID);
                        String org_level_all = companyInfo.getString(i, CmnConst.FIELD_ORG_LEVEL_ALL);
                        if (companyNames.contains(org_level_all)) {
                            companyNames.remove(org_level_all);
                        }
                        List<FieldSetEntity> postGradeList = groupCompany.get(org_level_all);
                        if (postGradeList != null) {
                            for (FieldSetEntity fs : postGradeList) {
                                // å°†å…¬å¸uuid写入每条数据
                                BaseUtil.createCreatorAndCreationTime(currentUser, fs);
                                fs.setValue(CmnConst.ORG_LEVEL_UUID, uuid);
                                fs.setValue(CmnConst.IS_USED, 1);
                                String job_grade_name = fs.getString(CmnConst.FIELD_JOB_GRADE_NAME);
//                            String group_name = fs.getString(CmnConst.FIELD_GROUP_NAME);
                                String managerValue = uuid + this.companyLevelSeparator + job_grade_name;
                                if (systemDataSet.contains(managerValue)) {
                                    DataLocation dataLocation = getDataLocation(fs);
                                    String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,数据重复";
                                    error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(CmnConst.FIELD_JOB_GRADE_NAME));
                                    errorEntity.addError(dataLocation.getRowIndex(), error);
                                    continue;
                                }
                                systemDataSet.add(managerValue);
                            }
                            if (errorEntity.isError) {
                                errorEntity.newThrowBaseException();
                            }
                        }
                    }
                    // åˆ¤æ–­æœ‰æ˜¯å¦æœ‰å…¬å¸æ²¡æŸ¥è¯¢åˆ°
                    if (companyNames != null && companyNames.size() > 0) {
                        List<FieldSetEntity> postGradeList = Lists.newArrayList();
                        for (String companyName : companyNames) {
                            //将没查询到的公司所属岗位等级合并
                            postGradeList.addAll(groupCompany.get(companyName));
                        }
                        if (postGradeList.size() > 0) {
                            //调用错误组装回调
                            callBack.method(postGradeList.toArray(new FieldSetEntity[]{}));
                            // æŠ›å‡ºé”™è¯¯
                            errorEntity.newThrowBaseException();
                        }
                    }
                    // ä¿å­˜æ‰€æœ‰æ•°æ®
                    getBaseDao().add(dt);
                    return dt;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            errorEntity.newThrowBaseException("导入岗位等级失败", e);
        }
        errorEntity.newThrowBaseException("导入岗位等级失败,未提取到数据");
        return null;
    }
    /**
     * å¯¼å…¥å²—位 ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param dt
     * @throws BaseException
     */
    @Override
    public DataTableEntity importPostBefore(DataTableEntity dt) throws BaseException {
        ImportErrorEntity errorEntity = new ImportErrorEntity();
        if (!BaseUtil.dataTableIsEmpty(dt)) {
            SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
            //管理员权限验证
            managerPermissionValidation(errorEntity, currentUser);
            Map<String, String> fieldType = Maps.newHashMap();
            // å½“前管理员管理的公司
            String managerCompanyUuids = currentUser.getCurrentManager().getString(CmnConst.ORG_LEVEL_UUID);
            fieldType.put(CmnConst.SEQUENCE, "int");
            String companyFilter = BaseUtil.buildQuestionMarkFilter(CmnConst.ORG_LEVEL_UUID, managerCompanyUuids.split(","), true);
            StringBuilder sql = new StringBuilder(8);
            sql.append(" SELECT org_level_all uuid, uuid dept_uuid,org_level_uuid FROM product_sys_org_levels where org_level_type=1 and length(org_level_uuid)>0 ");
            sql.append(" and ");
            sql.append(companyFilter);
            DataTableEntity deptData = getBaseDao().listTable(sql.toString(), new Object[]{});
            if (BaseUtil.dataTableIsEmpty(deptData)) {
                errorEntity.newThrowBaseException("您所管理的公司没有可供选择的部门,请核对部门数据");
            }
            sql = new StringBuilder(8);
            sql.append(" SELECT job_grade_name uuid,org_level_uuid,uuid grade_uuid ");
            sql.append(" FROM product_sys_job_post_grades WHERE ");
            sql.append(companyFilter);
            // æŸ¥è¯¢å½“前管理管理公司所有的岗位等级
            DataTableEntity postGradeData = getBaseDao().listTable(sql.toString(), new Object[]{});
            if (BaseUtil.dataTableIsEmpty(postGradeData)) {
//                errorEntity.newThrowBaseException("您所管理的公司没有可供选择的岗位等级,请核对岗位等级数据");
            }
            for (int i = 0; i < dt.getRows(); i++) {
                FieldSetEntity fse = dt.getFieldSetEntity(i);
                // å­—段必填 & ç±»åž‹éªŒè¯
                boolean validationResult = fieldRequiredValidation(errorEntity, fse, new String[]{CmnConst.FIELD_DEPT_UUID, CmnConst.FIELD_JOB_POST_NAME, CmnConst.SEQUENCE}, fieldType);
                if (!validationResult) {
                    // éªŒè¯æœªé€šè¿‡è·³è¿‡
                    continue;
                }
                // éƒ¨é—¨å…¨ç§°
                String deptAllName = fse.getString(CmnConst.FIELD_DEPT_UUID);
                // å²—位等级名称
                String[] gradeNames = BaseUtil.ifNull(fse.getString(CmnConst.FIELD_JOB_POST_GRADE), "").split(",");
                List<FieldSetEntity> fieldSetEntity = deptData.getFieldSetEntity(deptAllName);
                // éƒ¨é—¨æ‰€åœ¨çš„公司
                String companyUuid = null;
                // é”™è¯¯æ ‡è¯†
                boolean errorFlag = false;
                DataLocation dataLocation = null;
                if (fieldSetEntity == null || fieldSetEntity.size() < 1) {
                    dataLocation = getDataLocation(fse);
                    String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,部门不存在,请核对 '%s' æ•°æ®åœ¨ç³»ç»Ÿä¸­æ˜¯å¦å­˜åœ¨";
                    error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(CmnConst.FIELD_DEPT_UUID), dataLocation.getColName(CmnConst.FIELD_DEPT_UUID));
                    errorEntity.addError(dataLocation.getRowIndex(), error);
                    errorFlag = true;
                } else {
                    FieldSetEntity fs = fieldSetEntity.get(0);
                    companyUuid = fs.getString(CmnConst.ORG_LEVEL_UUID);
                    fse.setValue(CmnConst.FIELD_DEPT_UUID, fs.getString(CmnConst.FIELD_DEPT_UUID));
                }
                // æ ¹æ®å²—位等级名称取出相关数据
                List<FieldSetEntity> postGradeList = new ArrayList<>();
                for (String gradeName : gradeNames) {
                    if (!BaseUtil.dataTableIsEmpty(postGradeData) && postGradeData.getFieldSetEntity(gradeName) != null) {
                        postGradeList.addAll(postGradeData.getFieldSetEntity(gradeName));
                    }
                }
                String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,岗位等级不存在,请核对 '%s' æ•°æ®åœ¨ç³»ç»Ÿä¸­æ˜¯å¦å­˜åœ¨";
                // åˆ¤æ–­å²—位等级是否存在 é»˜è®¤ä¸æŠ›å‡ºé”™è¯¯
                if (postGradeList.size() < 1 && false) {
                    if (dataLocation == null) {
                        dataLocation = getDataLocation(fse);
                    }
                    error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(CmnConst.FIELD_JOB_POST_GRADE), dataLocation.getColName(CmnConst.FIELD_JOB_POST_GRADE));
                    errorEntity.addError(dataLocation.getRowIndex(), error);
                    errorFlag = true;
                } else if (postGradeList.size() > 0) {
                    String gradeUuid = "";
                    // å¾ªçŽ¯å²—ä½ç­‰çº§
                    for (FieldSetEntity fs : postGradeList) {
                        // æŸ¥æ‰¾å²—位等级与公司是否匹配
                        if (companyUuid != null && companyUuid.equals(fs.getString(CmnConst.ORG_LEVEL_UUID))) {
                            if (!StringUtils.isEmpty(gradeUuid)) {
                                gradeUuid += ",";
                            }
                            gradeUuid += fs.getString("grade_uuid");
                        }
                    }
                    // æ²¡æœ‰åŒ¹é…åˆ°è¯¥å…¬å¸ä¸‹æœ‰ç›¸åº”的岗位等级
                    if (StringUtils.isEmpty(gradeUuid)) {
                        if (dataLocation == null) {
                            dataLocation = getDataLocation(fse);
                        }
                        error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,岗位等级在不存在,请核对 '%s' æ•°æ®åœ¨æ‰€å±žéƒ¨é—¨çš„公司中是否存在";
                        error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(CmnConst.FIELD_JOB_POST_GRADE), dataLocation.getColName(CmnConst.FIELD_JOB_POST_GRADE));
                        errorEntity.addError(dataLocation.getRowIndex(), error);
                        errorFlag = true;
                    } else {
                        String[] gradeUuids = gradeUuid.split(",");
                        // åˆ›å»ºå²—位与岗位等级的映射表
                        DataTableEntity subGradeMapping = new DataTableEntity();
                        for (String uuid : gradeUuids) {
                            FieldSetEntity gradeMappingFieldSet = new FieldSetEntity();
                            gradeMappingFieldSet.setTableName(CmnConst.TABLE_PRODUCT_SYS_JOB_POSTS_GRADES_MAPPING);
                            gradeMappingFieldSet.setValue("job_grade_uuid", uuid);
                            BaseUtil.createCreatorAndCreationTime(gradeMappingFieldSet);
                            subGradeMapping.addFieldSetEntity(gradeMappingFieldSet);
                        }
                        fse.addSubDataTable(subGradeMapping);
                        fse.setValue(CmnConst.FIELD_JOB_POST_GRADE, null);
                    }
                }
                if (errorFlag) {
                    continue;
                }
                // å¯¼å…¥æ•°æ®é»˜è®¤å¯ç”¨
                fse.setValue(CmnConst.IS_USED, 1);
            }
            if (errorEntity.isError) {
                errorEntity.newThrowBaseException();
            } else {
                return dt;
            }
        }
        errorEntity.newThrowBaseException("导入岗位等级失败,未提取到数据");
        return null;
    }
    /**
     * å¯¼å…¥å‘˜å·¥ ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param fse
     * @throws BaseException
     */
    @Override
    public DataTableEntity importStaffBefore(DataTableEntity fse) throws BaseException {
        ImportStaffDataVo staffDataVo = new ImportStaffDataVo(fse);
        staffDataVo.startImporting();
        return fse;
    }
    /**
     * å‘˜å·¥å¯¼å…¥æ“ä½œç±»
     */
    private class ImportStaffDataVo {
        //导入的所有数据
        private DataTableEntity dt;
        /**
         * é”™è¯¯å¤„理类
         */
        private ImportErrorEntity errorEntity;
        /**
         * ç³»ç»Ÿä¸­ä¸Šçº§é¢†å¯¼æ•°æ®
         */
        DataTableEntity directLeaderData;
        /**
         * éƒ¨é—¨æ•°æ®
         */
        DataTableEntity deptData;
        /**
         * è§’色数据
         */
        DataTableEntity roleData;
        /**
         * å²—位 & å²—位等级数据
         */
        DataTableEntity postData;
        /**
         * å‘˜å·¥è¡¨åŽ†å²æ•°æ®
         */
        DataTableEntity systemData;
        /**
         * å¯¼å…¥æ•°æ®çš„æ‰€æœ‰é¢†å¯¼(员工编码)
         */
        Set<String> direct_leader_codes;
        /**
         * å¯¼å…¥çš„æ•°æ®æŒ‰éƒ¨é—¨åˆ†ç»„
         */
        Map<String, List<FieldSetEntity>> deptGroupMap;
        /**
         * å½“前用户
         */
        SystemUser currentUser;
        /**
         * å½“前客户
         */
        String client_uuid;
        /**
         * å¯¼å…¥çš„æ•°æ®ä»¥å‘˜å·¥ç¼–码存放(员工编码是唯一的)
         */
        Map<String, FieldSetEntity> staffCodeMap;
        /**
         * å¯¼å…¥æ•°æ®ç±»åž‹éªŒè¯
         */
        Map<String, String> fieldType;
        /**
         * å…¬å¸è¿‡æ»¤æ¡ä»¶
         */
        String companyFilter;
        /**
         * åˆ†éš”符
         */
        String separator = ">";
        StringBuilder sql;
        /**
         * åˆå§‹å¯†ç 
         * æ¥æºäºŽ properties ä¸­çš„初始密码 å¦‚不存在默认为 '123'
         */
        String init_pwd;
        /**
         * éƒ¨é—¨å…¨ç§°å­˜æ”¾çš„部门详情数据
         */
        private Map<String, FieldSetEntity> deptMap;
        /**
         * å‘˜å·¥ç®¡ç†service
         * å®šä¹‰è¯¥æ“ä½œç±»ä¸­é¿å…æ²¡å¿…要的注入 è¿›å…¥æž„造时会初始化对应bean
         */
        private StaffManagerService staffManagerService;
        /**
         * æž„造方法 ç”¨äºŽclone éžå¿…要不要自行调用此方法
         *
         * @param currentData
         * @param currentDeptData
         */
        ImportStaffDataVo(FieldSetEntity currentData, FieldSetEntity currentDeptData) throws BaseException {
            // è¯¥æž„造用于 clone æ–¹æ³•
            // éžclone æ–¹å¼è°ƒç”¨ä¼šå‡ºçŽ°æœªçŸ¥é”™è¯¯
            this.currentData = currentData;
            this.currentDeptData = currentDeptData;
            if (currentData == null || currentDeptData == null) {
                try {
                    throw new RuntimeException("Constructor arguments cannot be null");
                } catch (RuntimeException e) {
                    throw new BaseException(e);
                }
            }
        }
        /**
         * æ— å‚构造 åˆå§‹å¿…要数据
         *
         * @param dt
         */
        public ImportStaffDataVo(DataTableEntity dt) throws BaseException {
            errorEntity = new ImportErrorEntity();
            if (BaseUtil.dataTableIsEmpty(dt)) {
                errorEntity.newThrowBaseException("导入员工失败,未提取到数据");
            }
            this.staffManagerService = SpringBeanUtil.getBean("staffManagerService", StaffManagerService.class);
            direct_leader_codes = Sets.newHashSet();
            fieldType = Maps.newHashMap();
            currentUser = SpringMVCContextHolder.getCurrentUser();
            client_uuid = currentUser.getClient_uuid();
            staffCodeMap = Maps.newHashMap();
            deptGroupMap = Maps.newHashMap();
            init_pwd = Global.getSystemConfig("initial.pwd", "123");
            this.dt = dt;
            //管理员权限验证
            managerPermissionValidation(errorEntity, currentUser);
            // å…¬å¸è¿‡æ»¤æ¡ä»¶
            companyFilter = BaseUtil.buildQuestionMarkFilter(CmnConst.ORG_LEVEL_UUID, currentUser.getCurrentManager().getString(CmnConst.ORG_LEVEL_UUID).split(","), true);
            fieldType.put("id_number", "id_card");
            fieldType.put("birth_date", "dateTime");
            fieldType.put("entry_datetime", "dateTime");
            fieldType.put("mobile_phone", "mobile_phone");
            fieldType.put("staff_email", "email");
            fieldType.put("age", "int");
        }
        /**
         * å¯¼å…¥æ•°æ®å…¥å£
         * å¼€å§‹å¯¼å…¥
         */
        public void startImporting() throws BaseException {
            // æ•°æ®æœ‰æ•ˆæ€§éªŒè¯ æ•°æ®å¿…填验证 & æ•°æ®æœ‰æ•ˆæ€§éªŒè¯ & æ•°æ®åˆ†ç»„
            this.requiredValidation();
            // æŸ¥è¯¢ç³»ç»Ÿä¸­å·²å­˜åœ¨çš„员工
            findExistStaff();
            // æ•°æ®é‡å¤éªŒè¯
            this.repeatValidation();
            this.throwError();
            // åˆå§‹åŒ–所需数据
            this.initializeSystemData();
            // å¼€å§‹å¤„理导入数据
            this.handleDataTable();
        }
        /**
         * handleDataTable éåŽ†æ—¶çš„æ•°æ®
         * å¯èƒ½æ˜¯é€šè¿‡ clone å¯¹è±¡èµ‹å€¼çš„ æ²¡æœ‰é€šè¿‡ handleDataTable æ–¹æ³•
         */
        private FieldSetEntity currentData;
        /**
         * handleDataTable éåŽ†æ•°æ®å¯¹åº”çš„éƒ¨é—¨
         * å¯èƒ½æ˜¯é€šè¿‡ clone å¯¹è±¡èµ‹å€¼çš„ æ²¡æœ‰é€šè¿‡ handleDataTable æ–¹æ³•
         */
        private FieldSetEntity currentDeptData;
        /**
         * ä¸Šçº§é¢†å¯¼æœªæ‰¾åˆ°
         */
        private void superStaffNotExist() throws BaseException {
            DataLocation dataLocation = getDataLocation(this.currentData);
            String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,上级领导获取失败,请检查 %s å¡«å†™å€¼æ˜¯å¦æ­£ç¡®ï¼Œè¯¥åˆ—值应填写 %s åˆ—对应的值";
            error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(CmnConst.FIELD_DIRECT_LEADER_CODE), dataLocation.getColName(CmnConst.FIELD_DIRECT_LEADER_CODE), dataLocation.getColName(CmnConst.FIELD_STAFF_CODE));
            errorEntity.addError(dataLocation.getRowIndex(), error);
        }
        /**
         * å¤„理所有记录
         */
        private void handleDataTable() throws BaseException {
            for (Map.Entry<String, List<FieldSetEntity>> fieldSets : this.deptGroupMap.entrySet()) {
                String deptAllName = fieldSets.getKey();
                currentDeptData = this.getStaffDept(deptAllName);
                List<FieldSetEntity> values = fieldSets.getValue();
                if (currentDeptData == null) {
                    for (int i = 0; i < values.size(); i++) {
                        this.currentData = values.get(i);
                        DataLocation dataLocation = getDataLocation(this.currentData);
                        String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,部门在系统或管理的公司中不存在,请检查列 '%s' çš„值 '%s' æ˜¯å¦æ­£ç¡®";
                        error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex(CmnConst.FIELD_DEPT_UUID),
                                dataLocation.getColName(CmnConst.FIELD_DEPT_UUID), deptAllName);
                        this.errorEntity.addError(dataLocation.getRowIndex(), error);
                    }
                    continue;
                }
                for (FieldSetEntity value : values) {
                    if (value.getBoolean("~processed~")) {
                        continue;
                    }
                    this.currentData = value;
                    this.handleFieldSet();
                }
            }
            throwError();
        }
        /**
         * å¤„理单条记录
         */
        private void handleFieldSet() throws BaseException {
            if (this.currentData.getBoolean("~processed~")) {
                return;
            }
            String dept_uuid = this.currentDeptData.getString(CmnConst.UUID);
            String org_level_uuid = this.currentDeptData.getString(CmnConst.ORG_LEVEL_UUID);
            this.currentData.setValue("~processed~", 1);
            this.currentData.setValue("~dept_uuid~", dept_uuid);
            this.currentData.setValue(CmnConst.FIELD_STAFF_CODE, this.currentData.getString("~temp_staff_code~"));
            this.currentData.setValue(CmnConst.FIELD_DEPT_UUID, currentDeptData.getString(CmnConst.FIELD_DEPT_UUID));
            this.currentData.setValue(CmnConst.ORG_LEVEL_UUID, org_level_uuid);
            this.currentData.setValue("status", 1);
            //取出配置中账户初始密码
            this.currentData.setValue(CmnConst.USER_PWD, this.init_pwd);
            String sex = this.currentData.getString("sex");
            if (!StringUtils.isEmpty(sex)) {
                // æ€§åˆ«ä¸ä¸ºç©ºæ—¶ è½¬æ¢å‚照数据 æ€§åˆ«éªŒè¯å·²åœ¨ä¸Šä¸ªæ–¹æ³•中验证过
                this.currentData.setValue("sex", sex.equals("男") ? 0 : 1);
            }
            // å¯¼å…¥æ•°æ®é…ç½®ä¸­ ä½¿ç”¨ staff_avatar å­—段作为用户登录账户的载体 åœ¨æ­¤å¤„转换回来
            this.currentData.setValue(CmnConst.USER_ACCOUNT, this.currentData.getString("staff_avatar"));
            // åˆ é™¤è½½ä½“数据
            this.currentData.remove("staff_avatar");
            // å°†show_name å­—段(员工名称) å¤åˆ¶åˆ° user表字段上
            this.currentData.setValue(CmnConst.USER_NAME, this.currentData.getString("show_name"));
            String job_post_grade_uuid = this.currentData.getString(CmnConst.FIELD_JOB_POST_GRADE_UUID);
            String job_post_name = this.currentData.getString("job_post_uuid");
            // å²—位 & å²—位等级
            List<FieldSetEntity> postDataList = postData.getFieldSetEntity(this.currentData.getString("job_post_uuid"));
            if (postDataList == null || postDataList.size() <= 0) {
                // æ²¡æœ‰å²—位
                postNotExist.method(this.currentData, "job_post_uuid");
            } else {
                // è®°å½•找到的岗位等级uuid ï¼Œå¤šä¸ªç”¨é€—号分隔
                String grade_uuid = "";
                // å²—位uuid
                String post_uuid = null;
                // å¾ªçŽ¯ç³»ç»Ÿä¸­å²—ä½æ•°æ®
                for (FieldSetEntity postFs : postDataList) {
                    // åˆ¤æ–­å²—位是否在部门下 & å²—位名称和导入数据的岗位名称是否相同
                    if (currentDeptData.getString(CmnConst.FIELD_DEPT_UUID).equals(postFs.getString(CmnConst.FIELD_DEPT_UUID)) && job_post_name.equals(postFs.getUUID())) {
                        // ç³»ç»Ÿä¸­å²—位的uuid
                        String job_post_uuid = postFs.getString("job_post_uuid");
                        // å²—位uuid不为空时 åˆ¤æ–­å½“前postFs ä¸­çš„岗位uuid是否跟已找到的岗位相同
                        if (post_uuid != null && !post_uuid.equals(job_post_uuid)) {
                            continue;
                        }
                        if (post_uuid == null) {
                            // è®°å½•岗位uuid
                            post_uuid = job_post_uuid;
                        }
                        // èŽ·å–å²—ä½ä¸­çš„å²—ä½ç­‰çº§åç§°
                        String job_grade_name = postFs.getString(CmnConst.FIELD_JOB_GRADE_NAME);
                        // æ‹†åˆ†å¾ªçŽ¯å¯¼å…¥å²—ä½ç­‰çº§åç§°
                        if (!BaseUtil.strIsNull(job_post_grade_uuid)) {
                            for (String grade_name : job_post_grade_uuid.split(",")) {
                                // åˆ¤æ–­å²—位等级名称和系统中相同
                                if (job_grade_name.equals(grade_name)) {
                                    if (!StringUtils.isEmpty(grade_uuid)) {
                                        grade_uuid += ",";
                                    }
                                    grade_uuid += postFs.getString(CmnConst.FIELD_JOB_POST_GRADE);
                                }
                            }
                        }
                    }
                }
                // æ²¡æœ‰æ‰¾åˆ°å²—位
                if (StringUtils.isEmpty(post_uuid)) {
                    // æŠ›å‡ºå²—位未找到错误
                    postNotExist.method(this.currentData, "job_post_uuid");
                } else {
                    // æ‰¾åˆ°å²—位
                    this.currentData.setValue("job_post_uuid", post_uuid);
                }
                // æ²¡æœ‰æ‰¾åˆ°å²—位等级
                if (!StringUtils.isEmpty(grade_uuid)) {
//                    postNotExist.method(this.currentData, CmnConst.FIELD_JOB_POST_GRADE_UUID);
//                } else {
                    this.currentData.setValue(CmnConst.FIELD_JOB_POST_GRADE_UUID, grade_uuid);
                }
            }
            // å¯¼å…¥æ•°æ®ä¸­å²—位名称
            String[] role_uuids = this.currentData.getString("role_uuids").split(",");
            String roleUuid = "";
            // è§’色处理
            roleFor:
            // å¾ªçŽ¯è§’è‰²åç§°
            for (String roleName : role_uuids) {
                // ä½¿ç”¨è§’色名称获取系统数据
                List<FieldSetEntity> roleList = roleData.getFieldSetEntity(roleName);
                if (roleList != null && roleList.size() > 0) {
                    // å¾ªçŽ¯ç³»ç»Ÿä¸­çš„è§’è‰²
                    for (FieldSetEntity roleFs : roleList) {
                        // å› ç³»ç»Ÿä¸­è§’色所属公司可多选,在此处前后拼接逗号
                        String roleCompany = "," + roleFs.getString(CmnConst.ORG_LEVEL_UUID) + ",";
                        // åˆ¤æ–­è§’色是否有导入数据的公司
                        if (roleCompany.contains("," + org_level_uuid + ",")) {
                            String role_uuid = roleFs.getString("role_uuid");
                            if (!StringUtils.isEmpty(roleUuid)) {
                                roleUuid += ",";
                            }
                            roleUuid += role_uuid;
                            continue roleFor;
                        }
                    }
                }
                // æ²¡æœ‰æ‰¾åˆ°è§’色数据 æŠ›å‡ºé”™è¯¯
                roleNotExist.method(this.currentData, roleName);
            }
            this.currentData.setValue("role_uuids", roleUuid);
            //装载上级领导code
            this.loadingSuperCode();
            if (staffManagerService == null) {
                staffManagerService = SpringBeanUtil.getBean("staffManagerService", StaffManagerService.class);
            }
            staffManagerService.saveStaffInfo(this.currentData);
        }
        /**
         * æŠ›å‡ºé”™è¯¯
         *
         * @throws BaseException
         */
        void throwError() throws BaseException {
            if (errorEntity.isError) {
                errorEntity.newThrowBaseException();
            }
        }
        /**
         * è£…载上级领导编码
         *
         * @return
         */
        private boolean loadingSuperCode() throws BaseException {
            // ä¸Šçº§é¢†å¯¼ï¼ˆå‘˜å·¥ç¼–码)
            String direct_leader_code = this.currentData.getString(CmnConst.FIELD_DIRECT_LEADER_CODE);
            String superCode = "";
            if (!StringUtils.isEmpty(direct_leader_code)) {
                List<FieldSetEntity> fieldSetEntity = directLeaderData.getFieldSetEntity(direct_leader_code);
                if (staffCodeMap.get(direct_leader_code) == null && (fieldSetEntity == null || fieldSetEntity.size() <= 0)) {
                    // æœªæ‰¾åˆ°ä¸Šçº§é¢†å¯¼
                    this.superStaffNotExist();
                    return false;
                } else {
                    //上级领导在导入数据 æˆ–系统中已存在
                    // æ ¹æ®ç¼–码获取上级(导入数据)
                    FieldSetEntity superFs = staffCodeMap.get(direct_leader_code);
                    if (superFs == null && (fieldSetEntity == null || fieldSetEntity.size() <= 0)) {
                        // æœªæ‰¾åˆ°ä¸Šçº§é¢†å¯¼
                        this.superStaffNotExist();
                        return false;
                    } else if (superFs == null) {
                        // åœ¨ç³»ç»Ÿä¸­æ‹¿å‡ºä¸Šçº§é¢†å¯¼
                        superFs = fieldSetEntity.get(0);
                    }
                    String user_id = superFs.getString(CmnConst.USER_ID);
                    if (StringUtils.isEmpty(user_id)) {
                        // user_id ä¸å­˜åœ¨ï¼Œè¯¥ä¸Šçº§åœ¨å¯¼å…¥æ•°æ®ä¸­æœªä¿å­˜è¿‡
                        String deptAllName = superFs.getString(CmnConst.FIELD_DEPT_UUID);
                        if (superFs.getBoolean("~processed~")) {
                            deptAllName = superFs.getString("~" + CmnConst.FIELD_DEPT_UUID + "~");
                        }
                        FieldSetEntity deptFs = getStaffDept(deptAllName);
                        if (deptFs == null) {
                            return false;
                        }
                        // å…‹éš†å½“前对象 å°†çˆ¶çº§çš„部门 & å‘˜å·¥è¡¨æ•°æ®æ”¾å…¥å…‹éš†å¯¹è±¡ä¸­
                        ImportStaffDataVo clone = this.clone(deptFs, superFs);
                        // å…ˆè®©çˆ¶çº§æ•°æ®è¿›è¡Œä¿å­˜æ“ä½œ
                        // è¿™é‡Œä¼šå‡ºçŽ°é€’å½’æ“ä½œ å› ä¸º handleFieldSet æ–¹æ³•调用了当前方法 çˆ¶çº§çš„父级进入一致的判断会一直递归 clone并保存
                        // å¦‚果递归层数过多可能会出现 full gc
                        clone.handleFieldSet();
                    } else {
                        //已保存过的数据 å–出已生成的tricode
                        superCode = superFs.getString(CmnConst.TRICODE);
                    }
                }
            }
            this.currentData.setValue(CmnConst.FIELD_DIRECT_LEADER_CODE, superCode);
            return true;
        }
        /**
         * å…‹éš†å¯¹è±¡
         * å…‹éš†åŽ sql æˆå‘˜å˜é‡æœªåˆå§‹åŒ–
         *
         * @param currentDeptData
         * @param currentData
         * @return
         */
        private ImportStaffDataVo clone(FieldSetEntity currentDeptData, FieldSetEntity currentData) throws BaseException {
            ImportStaffDataVo clone = new ImportStaffDataVo(currentData, currentDeptData);
            clone.deptData = this.deptData;
            clone.postData = this.postData;
            clone.roleData = this.roleData;
            clone.deptGroupMap = this.deptGroupMap;
            clone.errorEntity = this.errorEntity;
            clone.direct_leader_codes = this.direct_leader_codes;
            clone.deptMap = this.deptMap;
            clone.dt = this.dt;
            clone.systemData = this.systemData;
            clone.directLeaderData = this.directLeaderData;
            clone.staffCodeMap = this.staffCodeMap;
            clone.companyFilter = this.companyFilter;
            clone.currentUser = this.currentUser;
            clone.fieldType = this.fieldType;
            clone.init_pwd = this.init_pwd;
            clone.client_uuid = this.client_uuid;
            return clone;
        }
        /**
         * æ ¹æ®éƒ¨é—¨å…¨ç§°èŽ·å–éƒ¨é—¨è¯¦æƒ…
         *
         * @param deptAllName
         * @return
         * @throws BaseException
         */
        private FieldSetEntity getStaffDept(String deptAllName) throws BaseException {
            if (deptMap == null) {
                deptMap = Maps.newHashMap();
            }
            if (deptMap.get(deptAllName) != null) {
                return deptMap.get(deptAllName);
            }
            List<FieldSetEntity> deptDatList = deptData.getFieldSetEntity(deptAllName);
            if (deptDatList == null || deptDatList.size() < 0) {
                return null;
            }
            return deptDatList.get(0);
        }
        /**
         * è§’色未找到错误回调
         */
        private CallBack<Object> roleNotExist = f -> {
            FieldSetEntity fs = (FieldSetEntity) f[0];
            Object role_name = f[1];
            DataLocation dataLocation = getDataLocation(fs);
            String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,%s åœ¨ç³»ç»Ÿä¸­ä¸å­˜åœ¨ï¼Œè¯·æ£€æŸ¥åˆ—值%s æ˜¯å¦æ­£ç¡®";
            error = String.format(error, dataLocation.getRowIndex(), dataLocation.getColIndex("role_uuids"),
                    dataLocation.getColName("role_uuids"), role_name);
            errorEntity.addError(dataLocation.getRowIndex(), error);
        };
        /**
         * å²—位 & å²—位等级未找到错误回调
         */
        private CallBack<Object> postNotExist = f -> {
            FieldSetEntity fs = (FieldSetEntity) f[0];
            String fieldName = (String) f[1];
            DataLocation datLocation = getDataLocation(fs);
            String error = "第 %s è¡Œï¼Œç¬¬ %s åˆ—,'%s' æ•°æ®åœ¨ç³»ç»Ÿä¸­ä¸å­˜åœ¨ï¼Œè¯·æ£€æŸ¥ '%s' æ˜¯å¦æ­£ç¡®";
            error = String.format(error, datLocation.getRowIndex(), datLocation.getColIndex(fieldName),
                    datLocation.getColName(fieldName), fs.getString(fieldName));
            errorEntity.addError(datLocation.getRowIndex(), error);
        };
        /**
         * åˆå§‹åŒ–系统数据
         */
        private void initializeSystemData() throws BaseException {
            //查询上级领导
            findDirectLeaderData();
            // æŸ¥è¯¢ç®¡ç†å‘˜ç®¡ç†çš„(公司下的)部门
            findDeptData();
            // ç®¡ç†å‘˜ç®¡ç†çš„角色
            findRoleData();
            // ç®¡ç†å‘˜ç®¡ç†çš„岗位 & å²—位等级
            findPostData();
            this.throwError();
        }
        /**
         * æŸ¥è¯¢æ‰€æœ‰å²—位 & å²—位等级
         */
        private void findPostData() throws BaseException {
            sql = new StringBuilder();
            sql.append(" select a.job_post_name uuid,a.uuid job_post_uuid,c.job_grade_name,c.uuid job_post_grades_uuid,a.dept_uuid FROM product_sys_job_posts a ");
            sql.append(" LEFT join product_sys_job_posts_grades_mapping b on  ");
            sql.append(" a.dept_uuid in (select uuid FROM product_sys_org_levels where org_level_type=1 and  ");
            sql.append(companyFilter);
            sql.append(" ) and a.uuid=b.job_post_uuid ");
            sql.append(" LEFT  join product_sys_job_post_grades c on b.job_grade_uuid=c.uuid ");
            sql.append(" group by  a.job_post_name,a.uuid ,c.job_grade_name,c.uuid,a.dept_uuid ");
            // æŸ¥è¯¢å²—位 & å²—位等级
            postData = getBaseDao().listTable(sql.toString(), new Object[]{});
            if (BaseUtil.dataTableIsEmpty(roleData)) {
                errorEntity.addError(0, "系统中没有可供选择的岗位或岗位等级");
            }
        }
        /**
         * æŸ¥è¯¢æ‰€æœ‰è§’色
         */
        private void findRoleData() throws BaseException {
            sql = new StringBuilder();
            sql.append(" select role_name as uuid,uuid as role_uuid,org_level_uuid FROM product_sys_role ");
            sql.append(" where is_used = 1  and ");
            sql.append(companyFilter);
            // æŸ¥è¯¢è§’色
            roleData = getBaseDao().listTable(sql.toString(), new Object[]{});
            if (BaseUtil.dataTableIsEmpty(roleData)) {
                errorEntity.addError(0, "系统中没有可供选择的角色");
            }
        }
        /**
         * æŸ¥è¯¢æ‰€æœ‰éƒ¨é—¨
         */
        private void findDeptData() throws BaseException {
            // æŸ¥è¯¢éƒ¨é—¨
            sql = new StringBuilder();
            sql.append(" select org_level_all uuid,uuid as dept_uuid,org_level_uuid,org_level_code,org_level_code_parent FROM product_sys_org_levels ");
            sql.append(" where org_level_type = 1 and ");
            sql.append(BaseUtil.buildQuestionMarkFilter(CmnConst.FIELD_ORG_LEVEL_ALL, deptGroupMap.size(), true));
            sql.append(" and ");
            sql.append(companyFilter);
            // æŸ¥è¯¢éƒ¨é—¨
            deptData = getBaseDao().listTable(sql.toString(), deptGroupMap.keySet().toArray());
            if (BaseUtil.dataTableIsEmpty(deptData)) {
                errorEntity.addError(0, "系统中没有可供选择的部门");
            }
        }
        /**
         * æŸ¥è¯¢å¯¼å…¥æ•°æ®æ‰€æœ‰çš„上级领导
         */
        private void findDirectLeaderData() throws BaseException {
            sql = new StringBuilder();
            sql.append(" SELECT staff_code uuid,tricode,user_id FROM product_sys_staffs ");
            sql.append(" where ");
            sql.append(BaseUtil.buildQuestionMarkFilter(CmnConst.FIELD_STAFF_CODE, direct_leader_codes.size(), true));
            if (direct_leader_codes.size() > 0) {
                sql.append(" and ");
            }
            sql.append(" org_level_uuid in (select uuid FROM product_sys_org_levels where org_level_type=0 and client_uuid=?) ");
            // æš‚时注释不用公司做限制
//                sql.append(" and ");
//                sql.append(companyFilter);
            // æŸ¥è¯¢ä¸Šçº§é¢†å¯¼
            List<String> params = Lists.newArrayList(direct_leader_codes.iterator());
            params.add(currentUser.getClient_uuid());
            directLeaderData = getBaseDao().listTable(sql.toString(), params.toArray());
        }
        /**
         * æŸ¥è¯¢æ‰€æœ‰å‘˜å·¥ç¼–码以及user表中的账号
         */
        private void findExistStaff() throws BaseException {
            sql = new StringBuilder(126);
            sql.append(" select  concat(b.client_uuid,'>',staff_code) staff_code,a.user_account as staff_avatar ");
            sql.append(" FROM product_sys_users a left join product_sys_staffs b on (b.client_uuid=? or b.uuid is null) and  a.user_id=b.user_id ");
            systemData = getBaseDao().listTable(sql.toString(), new Object[]{client_uuid});
        }
        /**
         * æ•°æ®æ ¼å¼æ•ˆéªŒ
         */
        private void repeatValidation() throws BaseException {
            // æ³¨ ï¼šstaff_avatar å­—段为 user表中 user_account çš„载体
            fieldRepeatValidation(errorEntity, dt, systemData, new String[]{CmnConst.FIELD_STAFF_CODE, "staff_avatar"});
        }
        /**
         * å¿…填效验 æ•°æ®å¤„理
         */
        private void requiredValidation() throws BaseException {
            errorEntity.mergeError(fieldRequiredValidation(dt, new String[]{"show_name", "staff_avatar", CmnConst.FIELD_STAFF_CODE,
                    CmnConst.FIELD_DEPT_UUID, "job_post_uuid", "role_uuids"}, fieldType, (FieldSetEntity[] f) -> {
                FieldSetEntity fs = f[0];
                //上级领导编码
                String direct_leader_code = fs.getString(CmnConst.FIELD_DIRECT_LEADER_CODE);
                //工作部门全称
                String deptAllName = fs.getString(CmnConst.FIELD_DEPT_UUID);
                String id_number = fs.getString("id_number");
                String age = fs.getString("age");
                Date birth_date = fs.getDate("birth_date");
                String sex = fs.getString("sex");
                String staff_code = fs.getString(CmnConst.FIELD_STAFF_CODE);
                if (!StringUtils.isEmpty(staff_code)) {
                    fs.setValue("~temp_staff_code~", staff_code);
                    fs.setValue(CmnConst.FIELD_STAFF_CODE, client_uuid + this.separator + staff_code);
                    staffCodeMap.put(staff_code, fs);
                }
                fs.setValue(CmnConst.CLIENT_UUID, client_uuid);
                if (!StringUtils.isEmpty(direct_leader_code)) {
                    //将上级领导编码统一放入集合中
                    // ä¸Šçº§é¢†å¯¼ç¼–码 = å‘˜å·¥ç¼–码
                    direct_leader_codes.add(direct_leader_code);
                }
                //按部门分组数据
                if (!StringUtils.isEmpty(deptAllName)) {
                    List<FieldSetEntity> fieldSets = deptGroupMap.get(deptAllName);
                    if (fieldSets == null) {
                        fieldSets = Lists.newArrayList();
                        deptGroupMap.put(deptAllName, fieldSets);
                    }
                    fieldSets.add(fs);
                }
                if (!StringUtils.isEmpty(id_number)) {
                    try {
                        if (birth_date == null) {
                            // æ ¹æ®èº«ä»½è¯å–出生日期
                            fs.setValue("birth_date", BaseUtil.getBirthday(id_number));
                        }
                        if (StringUtils.isEmpty(age)) {
                            // æ ¹æ®èº«ä»½è¯å–出年龄
                            fs.setValue("age", BaseUtil.getAge(id_number));
                        }
                        if (StringUtils.isEmpty(sex)) {
                            // æ ¹æ®èº«ä»½è¯å–出性别
                            fs.setValue("sex", BaseUtil.getSex(id_number));
                        }
                    } catch (Exception e) {
                    }
                }
            }));
        }
    }
    /**
     * é‡è½½å¯¼å…¥å‘˜å·¥æ–¹æ³•
     * å¤„理公司、部门、岗位、岗位等级、账号 ç›¸å…³æ•°æ®
     *
     * @param postData     ç³»ç»Ÿå²—位&岗位等级数据
     * @param roleData     ç³»ç»Ÿè§’色数据
     * @param roleNotExist è§’色不存在错误回调
     * @param postNotExist å²—位&岗位等级不存在错误回调
     * @param fs           å¯¼å…¥æ•°æ®
     * @param deptFieldSet éƒ¨é—¨æ•°æ®
     * @param deptAllName  éƒ¨é—¨å…¨ç§°
     * @throws BaseException
     */
    private void importStaffBefore(DataTableEntity postData, DataTableEntity
            roleData, CallBack<Object> roleNotExist, CallBack<Object> postNotExist, FieldSetEntity fs, FieldSetEntity deptFieldSet, String deptAllName) throws BaseException {
        String dept_uuid = fs.getString(CmnConst.UUID);
        String org_level_uuid = fs.getString(CmnConst.ORG_LEVEL_UUID);
        fs.setValue(CmnConst.FIELD_STAFF_CODE, fs.getString("~temp_staff_code~"));
        fs.setValue(CmnConst.FIELD_DEPT_UUID, dept_uuid);
        fs.setValue(CmnConst.ORG_LEVEL_UUID, org_level_uuid);
        String job_post_grade_uuid = fs.getString(CmnConst.FIELD_JOB_POST_GRADE);
        String job_post_name = fs.getString("job_post_uuid");
        // å²—位 & å²—位等级
        List<FieldSetEntity> postDataList = postData.getFieldSetEntity(deptAllName);
        if (postDataList == null || postDataList.size() <= 0) {
            // æ²¡æœ‰å²—位
            postNotExist.method(fs, "job_post_uuid");
        } else {
            // è®°å½•找到的岗位等级uuid ï¼Œå¤šä¸ªç”¨é€—号分隔
            String grade_uuid = "";
            // å²—位uuid
            String post_uuid = null;
            // å¾ªçŽ¯ç³»ç»Ÿä¸­å²—ä½æ•°æ®
            for (FieldSetEntity postFs : postDataList) {
                // åˆ¤æ–­å²—位是否在部门下 & å²—位名称和导入数据的岗位名称是否相同
                if (dept_uuid.equals(postFs.getString(CmnConst.FIELD_DEPT_UUID)) && job_post_name.equals(postFs.getString(CmnConst.FIELD_JOB_POST_NAME))) {
                    // ç³»ç»Ÿä¸­å²—位的uuid
                    String job_post_uuid = postFs.getString("job_post_uuid");
                    // å²—位uuid不为空时 åˆ¤æ–­å½“前postFs ä¸­çš„岗位uuid是否跟已找到的岗位相同
                    if (post_uuid != null && !post_uuid.equals(job_post_uuid)) {
                        continue;
                    }
                    if (post_uuid == null) {
                        // è®°å½•岗位uuid
                        post_uuid = job_post_uuid;
                    }
                    // èŽ·å–å²—ä½ä¸­çš„å²—ä½ç­‰çº§åç§°
                    String job_grade_name = postFs.getString(CmnConst.FIELD_JOB_GRADE_NAME);
                    // æ‹†åˆ†å¾ªçŽ¯å¯¼å…¥å²—ä½ç­‰çº§åç§°
                    for (String grade_name : job_post_grade_uuid.split(",")) {
                        // åˆ¤æ–­å²—位等级名称和系统中相同
                        if (job_grade_name.equals(grade_name)) {
                            if (!StringUtils.isEmpty(grade_uuid)) {
                                grade_uuid += ",";
                            }
                            grade_uuid += postFs.getString(CmnConst.FIELD_JOB_POST_GRADE);
                        }
                    }
                }
                // æ²¡æœ‰æ‰¾åˆ°å²—位
                if (StringUtils.isEmpty(post_uuid)) {
                    // æŠ›å‡ºå²—位未找到错误
                    postNotExist.method(fs, "job_post_uuid");
                } else {
                    // æ‰¾åˆ°å²—位
                    fs.setValue("job_post_uuid", post_uuid);
                }
                // æ²¡æœ‰æ‰¾åˆ°å²—位等级
                if (StringUtils.isEmpty(grade_uuid)) {
                    postNotExist.method(fs, CmnConst.FIELD_JOB_POST_GRADE);
                } else {
                    fs.setValue(CmnConst.FIELD_JOB_POST_GRADE, grade_uuid);
                }
            }
        }
        // å¯¼å…¥æ•°æ®ä¸­å²—位名称
        String[] role_uuids = (String[]) fs.getObject("role_uuids");
        String roleUuid = "";
        // è§’色处理
        roleFor:
        // å¾ªçŽ¯è§’è‰²åç§°
        for (String roleName : role_uuids) {
            // ä½¿ç”¨è§’色名称获取系统数据
            List<FieldSetEntity> roleList = roleData.getFieldSetEntity(roleName);
            // åœ¨ç³»ç»Ÿä¸­æ²¡æœ‰æ‰¾åˆ°è§’色名称一致的数据
            if (roleList == null || roleList.size() <= 0) {
                roleNotExist.method(fs, roleName);
            } else {
                // å¾ªçŽ¯ç³»ç»Ÿä¸­çš„è§’è‰²
                for (FieldSetEntity roleFs : roleList) {
                    // å› ç³»ç»Ÿä¸­è§’色所属公司可多选,在此处前后拼接逗号
                    String roleCompany = "," + roleFs.getString(CmnConst.ORG_LEVEL_UUID) + ",";
                    // åˆ¤æ–­è§’色是否有导入数据的公司
                    if (roleCompany.contains("," + org_level_uuid + ",")) {
                        String role_uuid = roleFs.getString("role_uuid");
                        if (!StringUtils.isEmpty(roleUuid)) {
                            roleUuid += ",";
                        }
                        roleUuid += role_uuid;
                        continue roleFor;
                    }
                }
                // æ²¡æœ‰æ‰¾åˆ°è§’色数据 æŠ›å‡ºé”™è¯¯
                roleNotExist.method(fs, roleName);
            }
        }
    }
    /**
     * èŽ·å–æ•°æ®ä½ç½®å¯¹è±¡
     *
     * @param fse
     * @return
     */
    private DataLocation getDataLocation(FieldSetEntity fse) {
        if (fse.getString("~dataLocation~") != null) {
            return (DataLocation) fse.getObject("~dataLocation~");
        } else {
            DataLocation dataLocation = new DataLocation(fse);
            fse.setValue("~dataLocation~", dataLocation);
            return dataLocation;
        }
    }
    /**
     * åˆå§‹åŒ–机构数据
     *
     * @param fse
     * @param level_type
     */
    public void initOrganizationFieldSet(FieldSetEntity fse, String client_uuid, String parentCode,
                                         int level_type) {
        fse.setValue(CmnConst.FIELD_ORG_LEVEL_CODE_PARENT, parentCode);
        fse.setValue(CmnConst.FIELD_ORG_LEVEL_CODE, BaseUtil.createCode(fse, CmnConst.TABLE_PRODUCT_SYS_ORG_LEVELS, CmnConst.FIELD_ORG_LEVEL_CODE, parentCode));
        BaseUtil.createCreatorAndCreationTime(fse);
        fse.remove(CmnConst.ORG_LEVEL_UUID);
        fse.setValue(CmnConst.CLIENT_UUID, client_uuid);
        fse.setValue(CmnConst.FIELD_ORG_LEVEL_STATUS, 0);
        fse.setValue(CmnConst.FIELD_ORG_LEVEL_TYPE, level_type);
        fse.setCodeFieldUpdateFlat(CmnConst.FIELD_ORG_LEVEL_CODE, false);
    }
    public void managerPermissionValidation(ImportErrorEntity errorEntity, SystemUser user) throws
            BaseException {
        FieldSetEntity managerFieldSet = user.getCurrentManager();
        if (managerFieldSet == null || user.getUserType() != 2) {
            errorEntity.newThrowBaseException("没有导入此数据的权限,请联系统管理员");
        } else if (StringUtils.isEmpty(managerFieldSet.getString(CmnConst.ORG_LEVEL_UUID))) {
            errorEntity.newThrowBaseException("公司权限不存在,请联系统管理员");
        }
    }
    /**
     * é”™è¯¯ä½ç½®
     */
    class DataLocation {
        //当前行
        private Integer rowIndex;
        //列名
        private List<String> colNameList;
        //字段列索引
        private Map<String, String> fieldIndex;
        DataLocation(FieldSetEntity fse) {
            //当前行
            this.rowIndex = fse.getInteger("~row~");
            //列名
            this.colNameList = (List<String>) fse.getObject("~colName~");
            //字段列索引
            this.fieldIndex = (Map<String, String>) fse.getObject("~fieldIndex~");
        }
        /**
         * èŽ·å–å½“å‰è¡Œç´¢å¼•
         *
         * @return
         */
        public Integer getRowIndex() {
            return rowIndex + 1;
        }
        /**
         * èŽ·å–å½“å‰åˆ—ç´¢å¼•
         *
         * @param fieldName
         * @return
         */
        public String getColIndex(String fieldName) {
            if (fieldIndex == null || StringUtils.isEmpty(fieldName)) {
                return null;
            }
            String colIndex = fieldIndex.get(fieldName);
            return !StringUtils.isEmpty(colIndex) ? String.valueOf(Integer.valueOf(colIndex) + 1) : "未知";
        }
        /**
         * èŽ·å–å½“å‰åˆ—åç§°
         *
         * @param fieldName
         * @return
         */
        public String getColName(String fieldName) {
            String colIndex = getColIndex(fieldName);
            if (this.colNameList == null || colIndex == null || "未知".equals(colIndex)) {
                return "未知列名";
            }
            return colNameList.get(Integer.valueOf(colIndex) - 1);
        }
    }
    static class ImportErrorEntity {
        interface errorMsg {
            errorMsg append(Object errorMsg);
        }
        private Map<Integer, String> errorMap;
        private boolean isError = false;
        /**
         * æ–°å¢žé”™è¯¯ è‡ªåŠ¨æ¢è¡Œ
         *
         * @param row
         * @param errorMsg
         * @return
         */
        public errorMsg addError(int row, String errorMsg) {
            if (errorMap == null) {
                errorMap = Maps.newHashMap();
            }
            isError = true;
            String error = errorMap.get(row);
            if (!StringUtils.isEmpty(error)) {
                error += "\n";
            } else {
                error = "";
            }
            error += errorMsg;
            errorMap.put(row, error);
            return (emg) -> this.append(row, String.valueOf(emg));
        }
        /**
         * åˆå¹¶é”™è¯¯
         *
         * @param errorEntity
         * @return
         */
        public ImportErrorEntity mergeError(ImportErrorEntity errorEntity) {
            Map<Integer, String> errorMap = errorEntity.errorMap;
            if (errorEntity.isError) {
                if (this.errorMap == null) {
                    this.errorMap = errorMap;
                    this.isError = true;
                    return this;
                } else {
                    errorMap.forEach((k, v) -> {
                        String error = this.errorMap.get(k);
                        if (!StringUtils.isEmpty(error)) {
                            error += "\n";
                        } else {
                            error = "";
                        }
                        error += v;
                        this.isError = true;
                        this.errorMap.put(k, error);
                    });
                }
            }
            return this;
        }
        /**
         * æ‹¼æŽ¥é”™è¯¯
         *
         * @param row
         * @param errorMsg
         * @return
         */
        public errorMsg append(int row, String errorMsg) {
            if (errorMap == null) {
                errorMap = Maps.newHashMap();
            }
            isError = true;
            String error = errorMap.get(row);
            if (StringUtils.isEmpty(error)) {
                error = "";
            }
            error += errorMsg;
            errorMap.put(row, error);
            return (emg) -> this.append(row, String.valueOf(emg));
        }
        public void newThrowBaseException() {
            newThrowBaseException(null, null);
        }
        public void newThrowBaseException(String msg, Exception exception) {
            if (!StringUtils.isEmpty(msg)) {
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), msg);
            } else if (errorMap != null) {
                List<Integer> es = Lists.newArrayList(errorMap.keySet().iterator());
                StringBuilder errorMsg = new StringBuilder();
                for (Integer e : es) {
                    String error = errorMap.get(e);
                    if (!StringUtils.isEmpty(error)) {
                        errorMsg.append(error).append("\n");
                    }
                }
                if (errorMsg.length() > 0) {
                    if (exception != null) {
                        throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), errorMsg.toString(), exception);
                    } else {
                        throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), errorMsg.toString());
                    }
                }
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), " æœªçŸ¥é”™è¯¯ï¼Œè¯·è”系管理员,error message is empty for 'throwExportDataError' Method ");
            }
            if (exception != null) {
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), " æœªçŸ¥é”™è¯¯ï¼Œè¯·è”系管理员,error message is empty for 'throwExportDataError' Method ", exception);
            }
            throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), " æœªçŸ¥é”™è¯¯ï¼Œè¯·è”系管理员,error message is empty for 'throwExportDataError' Method ");
        }
        public void newThrowBaseException(String msg) {
            newThrowBaseException(msg, null);
        }
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/service/SystemDataExportService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,329 @@
package com.product.module.data.service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.product.core.config.CoreConst;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.service.support.AbstractBaseService;
import com.product.module.data.config.CmnCode;
import com.product.module.data.config.CmnConst;
import com.product.module.data.utli.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
/**
 * @Author cheng
 * @Description æ•°æ®å¯¼å‡ºservice
 * @Date 2021/6/10 15:02
 * @Version 1.0
 */
@Service
public class SystemDataExportService extends AbstractBaseService {
    @Autowired
    SystemApiToMethods systemApiToMethods;
    @Override
    public BaseDao getBaseDao() {
        return super.getBaseDao();
    }
    public void reportDataExport(FieldSetEntity fse) throws BaseException {
        //报表uuid
        String uuid = fse.getUUID();
        //是否当前页
        boolean exportCurrentPage = fse.getBoolean("exportCurrentPage");
        //当前页号
        int pageIndex = fse.getInteger(CmnConst.CPAGE);
    }
    /**
     * æ•°æ®æŠ¥è¡¨å¯¼å‡º
     *
     * @param reqp
     * @return è¿”回Base64 EXCEL.XLSX
     * @throws BaseException
     * @throws IOException
     */
    public String reportDataExport(RequestParameterEntity reqp) throws BaseException {
        FieldSetEntity formData = reqp.getFormData();
        //总列数
        Integer totalColumn = formData.getInteger("totalColumn");
        //总行数
        Integer totalRows = formData.getInteger("totalRows");
        //头部区域行数
        Integer headCount = formData.getInteger("headCount");
        Map<String, File> files = reqp.getFiles();
        //固定文件名
        File portExcel = files.get("portExcel.xlsx");
        try (InputStream inputStream = new FileInputStream(portExcel); XSSFWorkbook wb = new XSSFWorkbook(inputStream)) {
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取头部样式
            XSSFCellStyle headStyle = getReportStyle(wb, IndexedColors.BLACK.getIndex(), true, (short) 15, new java.awt.Color(191, 191, 191));
            //获取数据区样式
            XSSFCellStyle dataStyle = getReportStyle(wb, IndexedColors.BLACK.getIndex(), false, (short) 13, new java.awt.Color(255, 255, 255));
            //所有同列最宽
            Map<Integer, Integer> m = new HashMap<>();
            for (int i = 0; i < totalRows; i++) {
                XSSFRow row = sheet.getRow(i);
                XSSFCellStyle style = null;
                if (i < headCount) {
                    //头部区域样式
                    style = headStyle;
                } else {
                    //数据区样式
                    style = dataStyle;
                }
                //遍历每一个单元格
                for (int j = 0; j < totalColumn; j++) {
                    //获取单元格对象
                    XSSFCell cell = row.getCell(j);
                    if (cell == null) {
                        //填充空的单元格
                        cell = row.createCell(j, CellType.STRING);
                    }
                    //设置单元格样式
                    cell.setCellStyle(style);
                    //获取单元格值
                    String val = cell.getStringCellValue();
                    if (val != null) {
                        //根据字节计算大致宽度
                        int i2 = val.getBytes().length * 256;
                        //宽度不能超过 256*256
                        if (i2 > 256 * 256) {
                            i2 = 256 * 255;
                        }
                        if (m.get(j) == null) {
                            m.put(j, i2);
                        } else {
                            //当前行的列是否比其他行的列宽
                            Integer width = m.get(j);
                            if (width < i2) {
                                m.put(j, i2);
                            }
                        }
                    }
                }
            }
            //设置每列的宽度
            for (Map.Entry<Integer, Integer> v : m.entrySet()) {
                sheet.setColumnWidth(v.getKey(), v.getValue());
            }
            //将workbook转换为字节流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //将excel输出到字节流
            wb.write(byteArrayOutputStream);
            //将字节流转为字节
            byte[] bytes = byteArrayOutputStream.toByteArray();
            //将字节转换为Base64
            String encode = Base64.getEncoder().encodeToString(bytes);
            //删除传入的文件
            if (portExcel != null && portExcel.exists()) {
                portExcel.delete();
            }
            //返回Base64字符串 æ‹¼æŽ¥XLSX文件格式前缀
            return "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + encode;
        } catch (Exception e) {
            throw new BaseException(CmnCode.EXPORT_REPORT_DATA_FIAL.getValue(), CmnCode.EXPORT_REPORT_DATA_FIAL.getValue() + e.getMessage());
        }
    }
    /**
     * å•元格样式
     *
     * @param workbook
     * @param color    å­—体颜色
     * @param bold     æ˜¯å¦åŠ ç²—
     * @param fontSize å­—体大小
     * @param bgc      èƒŒæ™¯è‰²
     * @return
     */
    public XSSFCellStyle getReportStyle(XSSFWorkbook workbook, short color, boolean bold, short fontSize, java.awt.Color bgc) {
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        //左右居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //上下居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // ä¸‹è¾¹æ¡†
        cellStyle.setBorderBottom(BorderStyle.THIN);
        // å·¦è¾¹æ¡†
        cellStyle.setBorderLeft(BorderStyle.THIN);
        // ä¸Šè¾¹æ¡†
        cellStyle.setBorderTop(BorderStyle.THIN);
        // å³è¾¹æ¡†
        cellStyle.setBorderRight(BorderStyle.THIN);
        //设置背景色
//        cellStyle.setFillForegroundColor(new XSSFColor());
        //填充模式
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        XSSFFont font = workbook.createFont();
        //字体颜色
        font.setColor(color);
        //加粗
        font.setBold(bold);
        //字体大小
        font.setFontHeightInPoints(fontSize);
        //字体样式
        font.setFontName("微软雅黑");
        //自动换行
        cellStyle.setWrapText(true);
        cellStyle.setFont(font);
        return cellStyle;
    }
    /**
     * é€šç”¨åˆ—表导出
     *
     * @param fse
     * @throws BaseException
     */
    public void generalListDataExport(FieldSetEntity fse) throws BaseException {
        //导出文件名称
        String file_name = fse.getString(CmnConst.FILE_NAME);
        //数据接口
        String upload_api_url = fse.getString(CmnConst.UPLOAD_API_URL);
        //数据接口所需参数
        FieldSetEntity export_param = fse.getSubDataTable(CmnConst.EXPORT_PARAM).getFieldSetEntity(0);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        RequestParameterEntity requestParameterEntity = (RequestParameterEntity) request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
        FieldSetEntity fs = new FieldSetEntity();
        fs.setTableName(fse.getString(CmnConst.TABLE_NAME));
        //开始页
        int start_cpage = export_param.getInteger(CmnConst.START_CPAGE);
        //结束页
        int end_cpage = export_param.getInteger(CmnConst.END_CPAGE);
        int pagesize = export_param.getInteger(CmnConst.PAGESIZE);
        export_param.setValue(CmnConst.CPAGE, ((start_cpage) * pagesize) / pagesize);
        export_param.setValue(CmnConst.PAGESIZE, pagesize * ((end_cpage - start_cpage) + 1));
        export_param.remove(CmnConst.START_CPAGE);
        export_param.remove(CmnConst.END_CPAGE);
        Map<Object, Object> values = export_param.getValues();
        for (Map.Entry<Object, Object> v : values.entrySet()) {
            fs.setValue(v.getKey().toString(), v.getValue());
        }
        requestParameterEntity.setFormData(fs);
        String result = (String) systemApiToMethods.run(upload_api_url, 1);
        if (JSON.isValidObject(result)) {
            JSONObject resultJson = JSON.parseObject(result);
            if (200 == resultJson.getInteger("code")) {
                //获取数据成功
                Object data = resultJson.get("data");
                if (data instanceof JSONObject) {
                } else if (data instanceof JSONArray) {
                    DataTableEntity export_field = export_param.getSubDataTable("export_field");
                    try {
                        writeExcel((JSONArray) data, export_field, file_name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new BaseException(resultJson.getString("code"), resultJson.getString("msg"));
            }
        } else {
            System.out.println("未知的数据类型");
        }
    }
    /**
     * è¾“出excel
     *
     * @param data
     * @param fieldInfo
     * @param main_title
     * @throws IOException
     */
    public void writeExcel(JSONArray data, DataTableEntity fieldInfo, String main_title) throws IOException {
        //标题
        List<List<String>> headTitles = Lists.newArrayList();
        List<String> fields = Lists.newArrayList();
        //导出的数据集
        List<String> titles = Lists.newArrayList();
        List<String> titleTemplate = Lists.newArrayList();
        titleTemplate.add(main_title);
        for (int i = 0; i < fieldInfo.getRows(); i++) {
            titles.add(fieldInfo.getString(i, CmnConst.FIELD_DESC));
            fields.add(fieldInfo.getString(i, CmnConst.FIELD_NAME));
        }
        List<List<Object>> lists = contentData(data, fields);
        titles.forEach(title -> {
            List<String> secondTitle = Lists.newArrayList(titleTemplate);
            secondTitle.add(title);
            headTitles.add(secondTitle);
        });
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        // è¿™é‡ŒURLEncoder.encode可以防止中文乱码 å½“ç„¶å’Œeasyexcel没有关系
        writeExcel(headTitles, lists, main_title, response);
    }
    /**
     * è¾“出excel
     *
     * @param excelHeaders excel表头
     * @param dataRows     æ•°æ®è¡Œ
     * @param sheetName    sheet名称
     * @throws IOException
     */
    public void writeExcel(List<List<String>> excelHeaders, List dataRows, String sheetName, HttpServletResponse response) throws IOException {
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        //允许访问header中的自定义参数
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        //设置文件名
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(sheetName + System.currentTimeMillis() + ".xlsx", "UTF-8"));
        // è¿™é‡ŒURLEncoder.encode可以防止中文乱码 å½“ç„¶å’Œeasyexcel没有关系
        // è¿™é‡Œéœ€è¦è®¾ç½®ä¸å…³é—­æµ
        try (ServletOutputStream outputStream = response.getOutputStream();) {
            EasyExcel.write(outputStream).
                    registerWriteHandler(new Custemhandler()).head(excelHeaders).sheet(sheetName).doWrite(dataRows);
        }
    }
    /**
     * ç»„装数据
     *
     * @param dataArray
     * @param fields
     * @return
     */
    private static List<List<Object>> contentData(JSONArray dataArray, List<String> fields) {
        List<List<Object>> contentList = Lists.newArrayList();
        dataArray.forEach(data -> {
            JSONObject dataJson = (JSONObject) data;
            List<Object> content = Lists.newArrayList();
            fields.forEach(field -> {
                content.add(dataJson.get(field));
            });
            contentList.add(content);
        });
        return contentList;
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/service/SystemDataUpLoadService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,882 @@
package com.product.module.data.service;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.product.common.collect.SetUtils;
import com.product.common.excel.EasyExcelUtil;
import com.product.common.lang.StringUtils;
import com.product.core.cache.DataPoolCacheImpl;
import com.product.core.config.Global;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldMetaEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.permission.PermissionService;
import com.product.core.service.support.AbstractBaseService;
import com.product.core.service.support.QueryFilterService;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.core.transfer.Transactional;
import com.product.file.service.FileManagerService;
import com.product.module.data.config.CmnCode;
import com.product.module.data.config.CmnConst;
import com.product.module.data.service.idel.ISystemDataUpLoadService;
import com.product.module.sys.entity.SystemUser;
import com.product.util.BaseUtil;
import com.product.util.SystemParamReplace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
@Service
public class SystemDataUpLoadService extends AbstractBaseService implements ISystemDataUpLoadService {
    @Autowired
    private BaseDao baseDao;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private QueryFilterService queryFilterService;
    @Autowired
    private PermissionService permissionService;
    public List<Map<String, Object>> getPrompt() throws BaseException {
        StringBuilder sql = new StringBuilder();
        sql.append(" select prompt_name `value` ,prompt_name `label` ,'prompt' type FROM product_sys_prompt ");
        sql.append(" union all ");
        sql.append(" select concat('《',dict_name,'》') dict_name,dict_name,'dict' type FROM product_sys_dict where is_used=1 group by dict_name ");
        FieldSetEntity f = new FieldSetEntity();
        f.setTableName("x");
        f.setValue("desc", "高级参照,普通参照");
        DataTableEntity dt = baseDao.listTable(sql.toString(), new Object[]{});
        List<Map<String, Object>> result = Lists.newArrayList();
        if (!BaseUtil.dataTableIsEmpty(dt)) {
            List<Map<String, Object>> promptList = Lists.newArrayList();
            List<Map<String, Object>> dictList = Lists.newArrayList();
            Map<String, Object> item;
            for (int i = 0; i < dt.getRows(); i++) {
                String type = dt.getString(i, "type");
                String value = dt.getString(i, "value");
                String label = dt.getString(i, "label");
                item = Maps.newHashMap();
                item.put("value", value);
                item.put("label", label);
                if ("prompt".equals(type)) {
                    promptList.add(item);
                } else {
                    dictList.add(item);
                }
            }
            item = Maps.newHashMap();
            item.put("label", "高级参照");
            item.put("children", promptList);
            item.put("value", "~高级参照~");
            result.add(item);
            item = Maps.newHashMap();
            item.put("label", "普通参照");
            item.put("children", dictList);
            item.put("value", "~普通参照~");
            result.add(item);
        }
        return result;
    }
    /**
     * æ¨¡æ¿ä¸Šä¼ 
     *
     * @param rpe
     * @return
     */
    @Override
    @Transactional
    public JSONObject uploadTemplate(RequestParameterEntity rpe) {
        FieldSetEntity paramFse = rpe.getFormData();
        String sourceFileName = paramFse.getString(CmnConst.FIELD_TEMPLATE_INFO);
        if (StringUtils.isEmpty(sourceFileName) || !sourceFileName.endsWith(".xlsx")) {
            throw new BaseException(CmnCode.UPLOAD_TEMPLATE_NOT_ALLOWED_FORMAT.getValue(), CmnCode.UPLOAD_TEMPLATE_NOT_ALLOWED_FORMAT.getText());
        }
        FieldSetEntity fse = fileManagerService.uploadFile(rpe);
        JSONObject resultObj = new JSONObject();
        resultObj.put(CmnConst.FIELD_TEMPLATE_INFO, fse.getString(CmnConst.FIELD_TEMPLATE_INFO));
        return resultObj;
    }
    /**
     * è§£æžæ¨¡æ¿ï¼ŒèŽ·å–Excel表头信息
     *
     * @param fse
     * @return
     */
    public JSONObject analysisTemplate(FieldSetEntity fse) {
        String attachmentUUID = fse.getString(CmnConst.FIELD_TEMPLATE_INFO);
        DataTableEntity modelDte = null;
        String modelUUID = fse.getUUID();
        boolean needAnalysisFlag = true;
        if (!StringUtils.isEmpty(modelUUID)) {
            FieldSetEntity preModelFse = baseDao.getFieldSetEntity(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, modelUUID, true);
            String preAttachmentUUID = preModelFse.getString(CmnConst.FIELD_TEMPLATE_INFO);
            modelDte = baseDao.listTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, "upload_sign=?", new Object[]{preModelFse.getString(CmnConst.FIELD_UPLOAD_SIGN)}, null, null, Integer.MAX_VALUE, 1, true);
            if (preAttachmentUUID.equals(attachmentUUID)) {
                // åŒæ ·çš„æ–‡ä»¶ï¼Œä¸éœ€è¦é‡æ–°è§£æž
                needAnalysisFlag = false;
            }
        }
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.TABLE_PRODUCT_SYS_ATTACHMENT, attachmentUUID, false);
        if (needAnalysisFlag) {
            // éœ€è¦é‡æ–°è§£æž
            String relativePath = attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_URL);
            String templateName = attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_TITLE);
            String path = Global.getSystemConfig("local.dir", "") + File.separator + relativePath + File.separator + templateName;
            File templateFile = new File(path);
            // åˆ›å»ºæ–‡ä»¶æµæ“ä½œå¯¹è±¡
            try (InputStream inputStream = new FileInputStream(templateFile)) {
                Map<String, List<List<String>>> map = EasyExcelUtil.readExcelByStringFromInputStream(inputStream, null);
                DataTableEntity subDte;
                Map<String, FieldSetEntity> subMap;
                FieldSetEntity mainFse;
                FieldSetEntity subFse;
                List<List<String>> list;
                int index = 0;
                for (Map.Entry<String, List<List<String>>> entry : map.entrySet()) {
                    list = entry.getValue();
                    if (list.isEmpty()) {
                        continue;
                    }
                    subDte = new DataTableEntity();
                    mainFse = null;
                    for (String excelHeader : list.get(list.size() - 1)) {
                        if (StringUtils.isEmpty(excelHeader)) {
                            throw new BaseException(CmnCode.UPLOAD_TEMPLATE_EXISTS_EMPTY_COL.getValue(), CmnCode.UPLOAD_TEMPLATE_EXISTS_EMPTY_COL.getText());
                        }
                        subFse = null;
                        if (modelDte != null && modelDte.getRows() > index) {
                            mainFse = modelDte.getFieldSetEntity(index);
                            subMap = dte2Map(mainFse.getSubDataTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB), CmnConst.FIELD_EXCEL_HEADER);
                            if (subMap.containsKey(excelHeader)) {
                                // åŽŸæœ‰çš„å­—æ®µ
                                subFse = subMap.get(excelHeader);
                            }
                        }
                        if (subFse == null) {
                            // æœ¬èº«æ²¡æœ‰çš„字段
                            subFse = new FieldSetEntity();
                            subFse.setTableName(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB);
                            subFse.setValue(CmnConst.FIELD_EXCEL_HEADER, excelHeader);
                        }
                        subDte.addFieldSetEntity(subFse);
                    }
                    if (mainFse == null) {
                        mainFse = new FieldSetEntity();
                        mainFse.setTableName(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL);
                        if (modelDte == null) {
                            modelDte = new DataTableEntity();
                        }
                        modelDte.addFieldSetEntity(mainFse);
                    } else {
                        mainFse.removeSubData(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB);
                    }
                    mainFse.setValue("start_row_index", list.size() - 1);
                    mainFse.addSubDataTable(subDte);
                    index++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_GET_INFO_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_GET_INFO_FAIL.getText());
            }
        }
        JSONObject resultObj = new JSONObject();
        resultObj.put("sheet_info", BaseUtil.dataTableEntityToJson(modelDte));
        resultObj.put(CmnConst.FIELD_UPLOAD_SIGN, SpringMVCContextHolder.getCurrentUser().getClient_uuid() + "_" + attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_TITLE) + "_" + System.currentTimeMillis());
        return resultObj;
    }
    /**
     * ä¿å­˜
     *
     * @param fse
     */
    @Override
    @Transactional
    public void saveTemplate(FieldSetEntity fse) {
        if (StringUtils.isEmpty(fse.getUUID())) {
            addTemplate(fse);
        } else {
            updateTemplate(fse);
        }
    }
    /**
     * æ–°å¢žæ¨¡æ¿
     *
     * @param fse
     */
    private void addTemplate(FieldSetEntity fse) {
        SystemUser curUser = SpringMVCContextHolder.getCurrentUser();
        String orgLevelUUID = curUser.getOrg_level_uuid();
        String clientUUID = curUser.getClient_uuid();
        String attachmentUUID = fse.getString(CmnConst.FIELD_TEMPLATE_INFO);
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.TABLE_PRODUCT_SYS_ATTACHMENT, attachmentUUID, false);
        String uploadSign = clientUUID + "_" + attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_TITLE) + "_" + System.currentTimeMillis();
        int sheetOrder = 1;
        fse.setValue(CmnConst.FIELD_SHEET_ORDER, sheetOrder);
        fse.setValue(CmnConst.FIELD_UPLOAD_SIGN, uploadSign);
        // ä¿å­˜æ•°æ®å¯¼å…¥æ¨¡æ¿ä¿¡æ¯
        DataTableEntity modelDte = fse.getSubDataTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL);
        if (!BaseUtil.dataTableIsEmpty(modelDte)) {
            FieldSetEntity tempFse;
            for (int i = 0; i < modelDte.getRows(); i++) {
                tempFse = modelDte.getFieldSetEntity(i);
                tempFse.setValue(CmnConst.FIELD_UPLOAD_SIGN, uploadSign);
                tempFse.setValue(CmnConst.FIELD_SHEET_ORDER, ++sheetOrder);
                BaseUtil.addOrgLeveLUUID(tempFse, Collections.singletonList(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB), orgLevelUUID, curUser);
                baseDao.saveFieldSetEntity(tempFse);
            }
            fse.removeSubData(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL);
        }
        BaseUtil.addOrgLeveLUUID(fse, Collections.singletonList(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB), orgLevelUUID, curUser);
        baseDao.saveFieldSetEntity(fse);
        String mvcUUID = fse.getString(CmnConst.FIELD_FUNCTION_UUID);
        String buttonTitle = fse.getString(CmnConst.FILED_BUTTON_TITLE);
        // todo å¾…测试,创建mvc相关内容
        dealMvcInfo(mvcUUID, buttonTitle, uploadSign);
    }
    /**
     * å¤„理mvc中导入配置信息
     *
     * @param mvcUUID
     * @param buttonTitle
     */
    private void dealMvcInfo(String mvcUUID, String buttonTitle, String uploadSign) {
        FieldSetEntity firstPageFse = getFirstPageFse(mvcUUID);
        if (firstPageFse == null) {
            throw new BaseException(CmnCode.GET_MVC_FIRST_PAGE_INFO_FAIL.getValue(), CmnCode.GET_MVC_FIRST_PAGE_INFO_FAIL.getText());
        }
        FieldSetEntity preImportButtonFse = getImportButtonFse(firstPageFse, mvcUUID);
        SystemUser curUser = SpringMVCContextHolder.getCurrentUser();
        if (preImportButtonFse == null) {
            // æœ¬èº«æ²¡æœ‰å¯¼å…¥æŒ‰é’®ï¼Œè‡ªåŠ¨åˆ›å»º todo
            // æŒ‰é’®
            FieldSetEntity importButtonFse = new FieldSetEntity();
            importButtonFse.setTableName(CmnConst.TABLE_PRODUCT_SYS_BUTTONS);
            importButtonFse.setValue(CmnConst.FILED_FUNCTION_UUID, mvcUUID);
            importButtonFse.setValue(CmnConst.FILED_BUTTON_NAME, "default_import");
            importButtonFse.setValue(CmnConst.FILED_BUTTON_TITLE, buttonTitle);
            importButtonFse.setValue(CmnConst.FILED_STATUS_UUID, 1);
            importButtonFse.setValue(CmnConst.FILED_CATEGORY_UUID, "import");
            importButtonFse.setValue(CmnConst.FILED_CLIENT_TYPE_UUID, "Web");
            importButtonFse.setValue(CmnConst.FILED_ROUTE_NAME, BaseUtil.getPageCode());
            importButtonFse.setValue("params", "{\"upload_sign\":\"" + uploadSign + "\"}");
            importButtonFse.setValue("button_category_uuid", "import");
            importButtonFse.setValue("button_type", 2);
            importButtonFse.setValue("is_main", 0);
            BaseUtil.createCreatorAndCreationTime(curUser, importButtonFse);
            baseDao.saveFieldSetEntity(importButtonFse);
//            // é¡µé¢
//            FieldSetEntity importPageFse = new FieldSetEntity();
//            importPageFse.setTableName(CmnConst.TABLE_PRODUCT_SYS_MVC_PAGE);
//            importPageFse.setValue(CmnConst.FILED_FUNCTION_UUID, mvcUUID);
//            importPageFse.setValue(CmnConst.FIELD_PAGE_NAME, "默认导入页面");
//            importPageFse.setValue(CmnConst.FIELD_PAGE_TYPE, 2);
//            importPageFse.setValue(CmnConst.FIELD_PAGE_TYPE, 2);
//            BaseUtil.createCreatorAndCreationTime(curUser, importPageFse);
//            baseDao.saveFieldSetEntity(importPageFse);
            // è¿žçº¿-列表界面-导入按钮
            FieldSetEntity importLinkFse1 = new FieldSetEntity();
            importLinkFse1.setTableName(CmnConst.TABLE_PRODUCT_SYS_MVC_LINK);
            importLinkFse1.setValue(CmnConst.FILED_FUNCTION_UUID, mvcUUID);
            importLinkFse1.setValue(CmnConst.FIELD_LINK_TYPE, 0);
            importLinkFse1.setValue(CmnConst.FIELD_LINE_FROM, firstPageFse.getUUID());
            importLinkFse1.setValue(CmnConst.FIELD_FROM_TYPE, 2);
            importLinkFse1.setValue(CmnConst.FIELD_LINE_TO, importButtonFse.getUUID());
            importLinkFse1.setValue(CmnConst.FIELD_TO_TYPE, 1);
            BaseUtil.createCreatorAndCreationTime(curUser, importLinkFse1);
            baseDao.saveFieldSetEntity(importLinkFse1);
//            // è¿žçº¿-导入按钮-导入页面
//            FieldSetEntity importLinkFse2 = new FieldSetEntity();
//            importLinkFse2.setTableName(CmnConst.TABLE_PRODUCT_SYS_MVC_LINK);
//            importLinkFse2.setValue(CmnConst.FILED_FUNCTION_UUID, mvcUUID);
//            importLinkFse2.setValue(CmnConst.FIELD_LINK_TYPE, 0);
//            importLinkFse2.setValue(CmnConst.FIELD_LINE_FROM, importButtonFse.getUUID());
//            importLinkFse2.setValue(CmnConst.FIELD_FROM_TYPE, 1);
//            importLinkFse2.setValue(CmnConst.FIELD_LINE_TO, importPageFse.getUUID());
//            importLinkFse2.setValue(CmnConst.FIELD_TO_TYPE, 2);
//            BaseUtil.createCreatorAndCreationTime(curUser, importLinkFse2);
//            baseDao.saveFieldSetEntity(importLinkFse2);
        } else {
            // æœ¬èº«å­˜åœ¨å¯¼å…¥æŒ‰é’®ï¼Œç›´æŽ¥æ›¿æ¢ç›¸åº”的数据 todo
            preImportButtonFse.setValue("", "");
            BaseUtil.updatedRegeneratorAndUpdateTime(curUser, preImportButtonFse);
            baseDao.saveFieldSetEntity(preImportButtonFse);
        }
    }
    /**
     * æå–指定mvc中【入口】后第一个页面
     *
     * @param mvcUUID
     * @return
     */
    private FieldSetEntity getFirstPageFse(String mvcUUID) {
        StringBuilder sql = new StringBuilder(256);
        sql.append("select p.* from (")
                .append("\n    select * FROM product_sys_function_buttons where is_main=1 and function_uuid=?")
                .append("\n) b")
                .append("\ninner join product_sys_link l on b.uuid=l.line_from")
                .append("\ninner join product_sys_mvc_page p on l.line_to=p.uuid");
        FieldSetEntity firstPageFse = baseDao.getFieldSetEntityBySQL(sql.toString(), new Object[]{mvcUUID}, false);
        return firstPageFse;
    }
    /**
     * å…¥å£åŽç¬¬ä¸€ä¸ªé¡µé¢ä¹‹åŽçš„导入
     *
     * @param firstPageFse
     * @param mvcUUID
     * @return
     */
    private FieldSetEntity getImportButtonFse(FieldSetEntity firstPageFse, String mvcUUID) {
        StringBuilder sql = new StringBuilder(256);
        sql.append("select b.* from (")
                .append("\n    select * FROM product_sys_mvc_page where uuid=?")
                .append("\n) p")
                .append("\ninner join product_sys_link l on p.uuid=l.line_to")
                .append("\ninner join (")
                .append("\n    select * FROM product_sys_function_buttons where function_uuid=? and button_category_uuid='import'")
                .append("\n) b on l.line_from=b.uuid");
        FieldSetEntity preImportButtonFse = baseDao.getFieldSetEntityBySQL(sql.toString(), new Object[]{firstPageFse.getUUID(), mvcUUID}, false);
        return preImportButtonFse;
    }
    /**
     * ä¿®æ”¹æ¨¡æ¿
     *
     * @param fse
     */
    private void updateTemplate(FieldSetEntity fse) {
        SystemUser curUser = SpringMVCContextHolder.getCurrentUser();
        // ä¿å­˜æ•°æ®å¯¼å…¥æ¨¡æ¿ä¿¡æ¯
        DataTableEntity modelDte = fse.getSubDataTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL);
        if (!BaseUtil.dataTableIsEmpty(modelDte)) {
            FieldSetEntity tempFse;
            for (int i = 0; i < modelDte.getRows(); i++) {
                tempFse = modelDte.getFieldSetEntity(i);
                BaseUtil.updatedRegeneratorAndUpdateTime(curUser, tempFse);
                baseDao.saveFieldSetEntity(tempFse);
            }
        }
        fse.removeSubData(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL);
        BaseUtil.updatedRegeneratorAndUpdateTime(curUser, fse);
        baseDao.saveFieldSetEntity(fse);
    }
    /**
     * æŸ¥è¯¢æ¨¡æ¿é…ç½®è¯¦æƒ…
     *
     * @param fse
     * @return
     */
    public FieldSetEntity findTemplate(FieldSetEntity fse) {
        String uploadSign = fse.getString(CmnConst.FIELD_UPLOAD_SIGN);
        DataTableEntity dt = baseDao.listTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, "upload_sign=?", new Object[]{uploadSign}, null, "sheet_order", Integer.MAX_VALUE, 1, true);
        if (!BaseUtil.dataTableIsEmpty(dt)) {
            FieldSetEntity fs = new FieldSetEntity();
            fs.setTableName(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL);
            DataTableEntity sub = new DataTableEntity();
            for (int i = 0; i < dt.getRows(); i++) {
                if (i == 0) {
                    fs.setValue(CmnConst.FIELD_TITLE, dt.getString(0, CmnConst.FIELD_TITLE));
                    fs.setValue(CmnConst.FIELD_FUNCTION_UUID, dt.getString(0, CmnConst.FIELD_FUNCTION_UUID));
                    fs.setValue(CmnConst.FILED_BUTTON_TITLE, dt.getString(0, CmnConst.FILED_BUTTON_TITLE));
                    fs.setValue(CmnConst.UUID, dt.getString(0, CmnConst.UUID));
                    fs.setValue(CmnConst.FIELD_UPLOAD_SIGN, dt.getString(0, CmnConst.FIELD_UPLOAD_SIGN));
                    fs.setValue(CmnConst.FIELD_TEMPLATE_INFO, dt.getString(0, CmnConst.FIELD_TEMPLATE_INFO));
                }
                String before_func = dt.getString(i, CmnConst.FIELD_BEFORE_FUNC);
                String after_func = dt.getString(i, CmnConst.FIELD_AFTER_FUNC);
                String table_name = dt.getString(i, CmnConst.TABLE_NAME);
                String startRowIndex = dt.getString(i, "start_row_index");
                FieldSetEntity f = new FieldSetEntity();
                f.setTableName("sheet_info");
                f.setValue(CmnConst.FIELD_BEFORE_FUNC, before_func);
                f.setValue(CmnConst.FIELD_AFTER_FUNC, after_func);
                f.setValue(CmnConst.UUID, dt.getString(i, CmnConst.UUID));
                f.setValue(CmnConst.TABLE_NAME, table_name);
                f.setValue("start_row_index", startRowIndex);
                f.setSubData(dt.getFieldSetEntity(i).getSubData());
                sub.addFieldSetEntity(f);
            }
            fs.addSubDataTable(sub);
            return fs;
        }
        return null;
    }
    /**
     * æ¨¡æ¿å°è´¦-左边树结构
     *
     * @param fse
     * @return
     */
    public DataTableEntity listTemplate(FieldSetEntity fse) {
        int pageSize = fse.getInteger(CmnConst.PAGESIZE) == null ? Integer.MAX_VALUE : fse.getInteger(CmnConst.PAGESIZE);
        int curPage = fse.getInteger(CmnConst.CPAGE) == null ? 1 : fse.getInteger(CmnConst.CPAGE);
        SystemUser user = SpringMVCContextHolder.getCurrentUser();
        StringBuilder filter = new StringBuilder(128);
        filter.append("org_level_uuid=? and length(title)>0");
        String queryFilter = queryFilterService.getQueryFilter(fse);
        if (!StringUtils.isEmpty(queryFilter)) {
            filter.append(" and ").append(queryFilter);
        }
        List<Object> paramList = Lists.newArrayList();
        paramList.add(user.getOrg_level_uuid());
        String[] filterParamArr = !StringUtils.isEmpty(fse.getString("~select_params~")) ? fse.getString("~select_params~").split(",") : null;
        if (filterParamArr != null) {
            Collections.addAll(paramList, filterParamArr);
        }
        return baseDao.listTable(fse.getTableName(), filter.toString(), paramList.toArray(), null, fse.getString(""), pageSize, curPage);
    }
    /**
     * æ•°æ®ä¸Šä¼ æ¨¡æ¿åˆ é™¤
     *
     * @param fse
     * @throws BaseException
     */
    @Override
    @Transactional
    public void deleteModel(FieldSetEntity fse) throws BaseException {
        String uploadSign = fse.getString(CmnConst.FIELD_UPLOAD_SIGN);
        DataTableEntity modelDte = baseDao.listTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, "upload_sign=?", new Object[]{uploadSign});
        if (BaseUtil.dataTableIsEmpty(modelDte)) {
            throw new BaseException(CmnCode.UPLOAD_TEMPLATE_DELETE_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_DELETE_FAIL.getText());
        }
        FieldSetEntity mainModelFse = null;
        FieldSetEntity tempFse;
        List<String> uuidParamList = Lists.newArrayList();
        for (int i = 0; i < modelDte.getRows(); i++) {
            tempFse = modelDte.getFieldSetEntity(i);
            uuidParamList.add(tempFse.getUUID());
            if (!StringUtils.isEmpty(tempFse.getString(CmnConst.FIELD_FUNCTION_UUID))) {
                mainModelFse = tempFse;
            }
        }
        if (mainModelFse == null) {
            throw new BaseException(CmnCode.UPLOAD_TEMPLATE_GET_MAIN_INFO_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_GET_MAIN_INFO_FAIL.getText());
        }
        // åˆ é™¤mvc相关的表信息
        String mvcUUID = mainModelFse.getString(CmnConst.FIELD_FUNCTION_UUID);
        FieldSetEntity firstPageFse = getFirstPageFse(mvcUUID);
        // å¯¼å…¥æŒ‰é’®
        FieldSetEntity importButtonFse = baseDao.getFieldSetEntityByFilter(CmnConst.TABLE_PRODUCT_SYS_BUTTONS, "function_uuid=? and button_name='default_import'", new Object[]{mvcUUID}, false);
        if (importButtonFse != null) {
            // è¿žçº¿-导入按钮-导入页面
//            FieldSetEntity secondLinkFse = baseDao.getFieldSetEntityByFilter(CmnConst.TABLE_PRODUCT_SYS_MVC_LINK, "function_uuid=? and link_type=0 and from_type=1 and line_from=?", new Object[]{mvcUUID, importButtonFse.getUUID()}, false);
            // åˆ é™¤-导入页面
//            baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_MVC_PAGE, new Object[]{secondLinkFse.getString(CmnConst.FIELD_LINE_TO)});
            // åˆ é™¤-连线-导入按钮-导入页面
//            baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_MVC_LINK, "function_uuid=? and link_type=0 and from_type=1 and line_from=?", new Object[]{mvcUUID, importButtonFse.getUUID()});
            // åˆ é™¤-连线-列表界面-导入按钮
            baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_MVC_LINK, "function_uuid=? and link_type=0 and from_type=2 and to_type=1 and line_from=? and line_to=?", new Object[]{mvcUUID, firstPageFse.getUUID(), importButtonFse.getUUID()});
            // åˆ é™¤-导入按钮
            baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_BUTTONS, new Object[]{importButtonFse.getUUID()});
        }
        // åˆ é™¤é™„ä»¶
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.TABLE_PRODUCT_SYS_ATTACHMENT, mainModelFse.getString(CmnConst.FIELD_TEMPLATE_INFO), false);
        if (attachmentFse != null) {
            String relativePath = attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_URL);
            String templateName = attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_TITLE);
            String path = Global.getSystemConfig("local.dir", "") + File.separator + relativePath + File.separator + templateName;
            File templateFile = new File(path);
            templateFile.delete();
            // åˆ é™¤é™„件表
            baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_ATTACHMENT, new Object[]{attachmentFse.getUUID()});
        }
        // åˆ é™¤æ¨¡æ¿å­è¡¨
        String filter = BaseUtil.buildQuestionMarkFilter(CmnConst.FIELD_MODEL_UUID, uuidParamList.size(), true);
        baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB, filter, uuidParamList.toArray());
        // åˆ é™¤æ¨¡æ¿ä¸»è¡¨
        baseDao.delete(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, uuidParamList.toArray());
    }
    /**
     * æ¨¡æ¿ä¸‹è½½
     *
     * @param fse
     * @param response
     * @throws IOException
     */
    public void downloadTemplate(FieldSetEntity fse, HttpServletResponse response) throws IOException {
        String upload_sign = fse.getString("upload_sign");
        FieldSetEntity templateFse = baseDao.getFieldSetEntityByFilter(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, "upload_sign=? AND length(title)>0", new Object[]{upload_sign}, false);
        String attachmentUUID = templateFse.getString(CmnConst.FIELD_TEMPLATE_INFO);
        fse.setValue(CmnConst.UUID, attachmentUUID);
        fileManagerService.getFileContent(fse, response);
    }
    /**
     * ä¸šåŠ¡åŠŸèƒ½å¯¼å…¥-上传文件
     *
     * @param rpe
     * @return
     */
    @Override
    @Transactional
    public String recordDataImport(RequestParameterEntity rpe) {
        FieldSetEntity ff = fileManagerService.uploadFile(rpe);
        FieldSetEntity fse = rpe.getFormData();
        fse.setValue(CmnConst.FIELD_IS_SUCCESS, 0);
        SystemUser curUser = SpringMVCContextHolder.getCurrentUser();
        fse.setValue(CmnConst.FIELD_ORG_LEVEL_UUID, curUser.getOrg_level_uuid());
        BaseUtil.createCreatorAndCreationTime(curUser, fse);
        fse.setValue("import_info", ff.getString("import_info"));
        baseDao.saveFieldSetEntity(fse);
        return fse.getUUID();
    }
    /**
     * ä¸šåŠ¡åŠŸèƒ½å¯¼å…¥-解析并保存到数据库
     *
     * @param fse
     * @return
     */
    @Override
    @Transactional
    public void recordDataSave(FieldSetEntity fse) {
        SystemUser curUser = SpringMVCContextHolder.getCurrentUser();
        FieldSetEntity logFse = baseDao.getFieldSetEntity(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_RECORD, fse.getUUID(), false);
        if (logFse == null) {
            throw new BaseException(CmnCode.UPLOAD_TEMPLATE_GET_UPLOAD_RECORD_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_GET_UPLOAD_RECORD_FAIL.getText());
        }
        // èŽ·å–æ¨¡æ¿ä¿¡æ¯
        DataTableEntity templateDte = baseDao.listTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL, "upload_sign=?", new Object[]{logFse.getString(CmnConst.FIELD_UPLOAD_SIGN)}, null, "sheet_order", Integer.MAX_VALUE, 1, true);
        // èŽ·å–å¯¼å…¥æ–‡ä»¶ä¿¡æ¯
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.TABLE_PRODUCT_SYS_ATTACHMENT, logFse.getString(CmnConst.FIELD_IMPORT_INFO), false);
        String relativePath = attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_URL);
        String templateName = attachmentFse.getString(CmnConst.FIELD_ATTACHMENT_TITLE);
        Map<String, List<List<String>>> dataMap = new HashMap<>();
        try {
            String filePath = Global.getSystemConfig("local.dir", "") + File.separator + relativePath + File.separator + templateName;
            dataMap = EasyExcelUtil.readExcelByString(filePath);
            if ("product_project_budget".equals(templateDte.getString(0, CmnConst.TABLE_NAME))) {
                for (int i = 1; i < dataMap.size(); i++) {
                    templateDte.addFieldSetEntity(templateDte.getFieldSetEntity(0).clones());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // å°è£…到dte中
        List<DataTableEntity> beforeSaveDataList = Lists.newArrayList();
        List<String> titleList;
        List<List<String>> dataList;
        List<String> rowList;
        String singleValue;// å•元格内的值
        int index = 0;
        FieldSetEntity curTemplateFse;
        Map<String, FieldSetEntity> curSubMap;
        List<List<List<String>>> headerDataList = Lists.newArrayList();
        List<Map<String, FieldSetEntity>> fieldInfoList = Lists.newArrayList();
        FieldSetEntity curFieldFse;
        FieldSetEntity recordFse;// ä¸šåŠ¡è¡¨fse
        DataTableEntity recordDte;// ä¸šåŠ¡è¡¨dte
        for (Map.Entry<String, List<List<String>>> entry : dataMap.entrySet()) {
            dataList = entry.getValue();
            if (dataList.isEmpty()) {
                continue;
            }
            recordDte = new DataTableEntity();
            curTemplateFse = templateDte.getFieldSetEntity(index);
            curSubMap = dte2Map(curTemplateFse.getSubDataTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB), CmnConst.FIELD_EXCEL_HEADER);
            fieldInfoList.add(curSubMap);
            // å­—段对应的excel è¡¨å¤´ç´¢å¼•
            Map<String, String> fieldIndex = Maps.newHashMap();
            //表头开始行 cheng update 2023å¹´6月30日15:48:22 å¤šè¡Œå¤´æ—¶ï¼Œè¡¨å¤´å¼€å§‹è¡Œä¸ä¸€å®šæ˜¯ç¬¬ä¸€è¡Œ
            int startRowIndex = 1;
            if (!StringUtils.isEmpty(curTemplateFse.getString("start_row_index")) && NumberUtil.isNumber(curTemplateFse.getString("start_row_index"))) {
                startRowIndex = Integer.parseInt(curTemplateFse.getString("start_row_index"));
                if (startRowIndex < 1) {
                    startRowIndex = 1;
                }
            }
            titleList = dataList.get(startRowIndex);
            if (startRowIndex > 0) {
                headerDataList.add(dataList.subList(0, startRowIndex));
            } else {
                headerDataList.add(new ArrayList<>());
            }
            for (int i = startRowIndex + 1; i < dataList.size(); i++) {
                rowList = dataList.get(i);
                recordFse = new FieldSetEntity();
                recordFse.setTableName(curTemplateFse.getString(CmnConst.FIELD_TABLE_NAME));
                //字段对应的列
                int j = 0;
                for (; j < titleList.size(); j++) {
                    if (rowList.size() < (j + 1)) {
                        singleValue = null;
                    } else {
                        singleValue = rowList.get(j);
                    }
                    curFieldFse = curSubMap.get(titleList.get(j));
                    recordFse.setValue(curFieldFse.getString(CmnConst.FIELD_FIELD_NAME), singleValue);
                    if (i == 1 || rowList.size() > fieldIndex.size()) {
                        fieldIndex.put(curFieldFse.getString(CmnConst.FIELD_FIELD_NAME), String.valueOf(j));
                    }
                }
                recordFse.setValue("~colName~", titleList);
                recordFse.setValue("~fieldIndex~", fieldIndex);
                // fieldSet å¯¹åº”的行
                recordFse.setValue("~row~", i);
                recordDte.addFieldSetEntity(recordFse);
            }
            beforeSaveDataList.add(recordDte);
            index++;
        }
        // æ•°æ®è§£æžä¿å­˜
        String orgLevelUUID = curUser.getOrg_level_uuid();
        String actualValue;
        FieldMetaEntity meta;
        Object[] fieldArr;
        DataTableEntity tempDte;
        String fieldName;
        for (int i = 0; i < beforeSaveDataList.size(); i++) {
            tempDte = beforeSaveDataList.get(i);
            // ä¿å­˜å‰å¤„理
            try {
                tempDte = spDeal(templateDte.getFieldSetEntity(i).getString(CmnConst.FIELD_BEFORE_FUNC), tempDte, headerDataList.get(i));
                if (BaseUtil.dataTableIsEmpty(tempDte)) {
                    throw new BaseException(CmnCode.UPLOAD_TEMPLATE_BEFORE_FUNC_EXEC_NO_DATA.getValue(), CmnCode.UPLOAD_TEMPLATE_BEFORE_FUNC_EXEC_NO_DATA.getText());
                }
            } catch (BaseException e) {
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_BEFORE_FUNC_EXEC_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_BEFORE_FUNC_EXEC_FAIL.getText());
            }
            meta = tempDte.getMeta();
            fieldArr = meta.getFields();
            curTemplateFse = templateDte.getFieldSetEntity(i);
            curSubMap = dte2Map(curTemplateFse.getSubDataTable(CmnConst.TABLE_PRODUCT_SYS_DATA_UPLOAD_MODEL_SUB), CmnConst.FIELD_FIELD_NAME);
            boolean isMultiFlag;
            StringBuilder errorMsg = new StringBuilder(8);
            for (int j = 0; j < tempDte.getRows(); j++) {
                recordFse = tempDte.getFieldSetEntity(j);
                for (Object fieldNameObj : fieldArr) {
                    if (fieldNameObj == null) {
                        continue;
                    }
                    fieldName = fieldNameObj.toString();
                    singleValue = recordFse.getString(fieldName);
                    curFieldFse = curSubMap.get(fieldName);
                    if (curFieldFse != null) {
                        // æå–真实值
                        if (!StringUtils.isEmpty(curFieldFse.getString(CmnConst.FIELD_PROMPT_NAME))) {
                            isMultiFlag = curFieldFse.getString(CmnConst.FIELD_IS_MULTI) == null ? false : "1".equals(curFieldFse.getString(CmnConst.FIELD_IS_MULTI));
                            // æ ¹æ®å‚照名称,参照类型,显示域的值,获取隐藏域的值
                            actualValue = getRealValue(curFieldFse.getString(CmnConst.FIELD_PROMPT_NAME), singleValue, isMultiFlag);
                        } else {
                            actualValue = singleValue;
                        }
                        recordFse.setValue(curFieldFse.getString(CmnConst.FIELD_FIELD_NAME), actualValue);
                    }
                }
                try {
                    BaseUtil.createCreatorAndCreationTime(curUser, recordFse);
                    baseDao.saveFieldSetEntity(recordFse);
                } catch (BaseException e) {
                    e.printStackTrace();
//                    errorMsg.append("导入数据错误:\n\t");
                    errorMsg.append(String.format("第%s个sheet,第%s行,%s", i + 1, j + 1, e.getMessageInfo() != null ? e.getMessageInfo() : "")).append("\n");
//                    throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), String.format("%s: ç¬¬%s个sheet,第%s行", CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getText(), i + 1, j + 1), e);
                } catch (Exception e) {
                    errorMsg.append(String.format("第%s个sheet,第%s行,%s", i + 1, j + 1, e.getMessage() != null ? e.getMessage() : "")).append("\n");
//                    throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), String.format("%s: ç¬¬%s个sheet,第%s行", CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getText(), i + 1, j + 1));
                }
            }
            if (errorMsg.length() > 0) {
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_IMPORT_DATA_FAIL.getValue(), errorMsg.toString());
            }
            // ä¿å­˜åŽå¤„理
            try {
                spDeal(templateDte.getFieldSetEntity(i).getString(CmnConst.FIELD_AFTER_FUNC), tempDte, headerDataList.get(i));
            } catch (BaseException e) {
                SpringMVCContextHolder.getSystemLogger().error(e);
            } catch (Exception e) {
                throw new BaseException(CmnCode.UPLOAD_TEMPLATE_AFTER_FUNC_EXEC_FAIL.getValue(), CmnCode.UPLOAD_TEMPLATE_AFTER_FUNC_EXEC_FAIL.getText());
            }
        }
        // æ›´æ–°è®°å½•表情况
        logFse.setValue(CmnConst.FIELD_IS_SUCCESS, 1);
        BaseUtil.updatedRegeneratorAndUpdateTime(curUser, fse);
        baseDao.saveFieldSetEntity(logFse);
    }
    /**
     * dte按照指定fse中的值作为key转换为map
     *
     * @param dte
     * @param keyFieldName
     * @return
     */
    private Map<String, FieldSetEntity> dte2Map(DataTableEntity dte, String keyFieldName) {
        Map<String, FieldSetEntity> resultMap = Maps.newHashMap();
        FieldSetEntity tempFse;
        for (int i = 0; i < dte.getRows(); i++) {
            tempFse = dte.getFieldSetEntity(i);
            resultMap.put(tempFse.getString(keyFieldName), tempFse);
        }
        return resultMap;
    }
    public static void main(String[] args) {
        Class<?> a = DataTableEntity.class;
        Class<DataTableEntity> b = DataTableEntity.class;
        System.out.println(a.equals(b));
    }
    /**
     * äº‹ä»¶å‰æˆ–者事件后调用逻辑方法的特殊处理
     *
     * @param functionContent
     * @param dte
     * @param headerDataList
     * @return
     */
    private DataTableEntity spDeal(String functionContent, DataTableEntity dte, List<List<String>> headerDataList) throws BaseException {
        if (functionContent == null) {
            return dte;
        }
        functionContent = functionContent.trim();
        if (StringUtils.isEmpty(functionContent)) {
            return dte;
        }
        String className = functionContent.substring(0, functionContent.indexOf("."));
        String methodName = functionContent.substring(functionContent.indexOf(".") + 1, functionContent.indexOf("("));
        //根据className获取类
        Object bean = SpringUtil.getBean(className);
        //使用huTool的反射工具类获取方法,方法的参数类型为DataTableEntity、List<List<String>>
        Method method = ReflectUtil.getMethod(bean.getClass(), methodName, DataTableEntity.class, List.class);
        if (method != null) {
            Type genericReturnType = method.getGenericReturnType();
            //判断method返回值为DataTableEntity.class
            boolean isBackDataTable = genericReturnType.getTypeName().equals("com.product.core.entity.DataTableEntity");
            //判断第二个参数的泛型类型
            Type[] types = method.getGenericParameterTypes();
            Type type = types[1];
            //判断类型是否为List<List<String>>,如果是则调用方法
            if (isBackDataTable && type.getTypeName().equals("java.util.List<java.util.List<java.lang.String>>")) {
                return ReflectUtil.invoke(bean, methodName, dte, headerDataList);
            }
        }
        return ReflectUtil.invoke(bean, methodName, dte);
    }
    /**
     * èŽ·å–çœŸå®žå€¼
     *
     * @param promptName
     * @param showValue
     * @return
     */
    private String getRealValue(String promptName, String showValue, boolean isMultiFlag) {
        String realValue = showValue;
        DataTableEntity promptDte;
        FieldSetEntity promptFse;
        if (promptName.startsWith("《")) {
            // æ™®é€šå‚ç…§
            promptName = promptName.replace("《", "").replace("》", "");
            promptDte = DataPoolCacheImpl.getInstance().getCacheData(CmnConst.CACHE_COMMON_PROMPT, new String[]{promptName});
            if (!BaseUtil.dataTableIsEmpty(promptDte)) {
                Set<String> showSet = SetUtils.string2Set(showValue, ",");
                Set<String> realSet = Sets.newLinkedHashSet();
                for (int i = 0; i < promptDte.getRows(); i++) {
                    promptFse = promptDte.getFieldSetEntity(i);
                    if (isMultiFlag) {
                        if (showSet.contains(promptFse.getString(CmnConst.FIELD_DICT_LABEL))) {
                            realSet.add(promptFse.getString(CmnConst.FIELD_DICT_VALUE));
                        }
                    } else {
                        if (showValue.equals(promptFse.getString(CmnConst.FIELD_DICT_LABEL))) {
                            realValue = promptFse.getString(CmnConst.FIELD_DICT_VALUE);
                            break;
                        }
                    }
                }
                if (!realSet.isEmpty()) {
                    realValue = SetUtils.set2String(realSet, ",");
                }
            }
        } else {
            // é«˜çº§å‚ç…§
            promptFse = BaseUtil.getSingleInfoByCache(CmnConst.CACHE_ADVANCED_PROMPT, new String[]{promptName});
            String sourceTableName = promptFse.getString(CmnConst.FILED_SOURCE_TABLE);
            String filter = promptFse.getString(CmnConst.FILED_FILTER);
            String showFieldName = promptFse.getString(CmnConst.FILED_VIEW_FIELD);
            Set<String> showSet = SetUtils.string2Set(showValue, ",");
            String promptFilter = BaseUtil.buildQuestionMarkFilter(showFieldName, isMultiFlag ? showSet.size() : 1, true);
            StringBuilder sql = new StringBuilder(256);
            String realFieldName = promptFse.getString(CmnConst.FILED_VALUE_FIELD);
            sql.append("select GROUP_CONCAT(").append(realFieldName).append(") real_value from ").append(sourceTableName).append(" where ").append(promptFilter);
            if (!StringUtils.isEmpty(filter)) {
                filter = SystemParamReplace.systemParamsReplace(filter);
                sql.append(" and ").append(filter);
            }
            // è¡¥å……特定字段数据过滤
            if (!StringUtils.isEmpty(promptFse.getString("org_filter_field")) || !StringUtils.isEmpty(promptFse.getString("user_filter_field"))) {
                String dataFilter = permissionService.getDataFilter(sourceTableName,
                        promptFse.getString("user_filter_field"), promptFse.getString("org_filter_field"));
                if (!StringUtils.isEmpty(dataFilter)) {
                    sql.append(" and ").append(dataFilter);
                }
            }
            FieldSetEntity sourceFse = baseDao.getFieldSetEntityBySQL(sql.toString(), showSet.toArray(), false);
            if (sourceFse != null) {
                realValue = sourceFse.getString("real_value");
            }
        }
        return realValue;
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/service/idel/IOrganizationImportService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,53 @@
package com.product.module.data.service.idel;
import com.product.core.entity.DataTableEntity;
import com.product.core.exception.BaseException;
/**
 * @ClassName IOrganizationImportService
 * @Description ç»„织机构导入数据处理
 * @Author cheng
 * @Date 2021/12/2 16:09
 */
public interface IOrganizationImportService {
    /**
     * å¯¼å…¥å…¬å¸ ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param fse
     * @throws BaseException
     */
    DataTableEntity importCompanyBefore(DataTableEntity fse) throws BaseException;
    /**
     * å¯¼å…¥éƒ¨é—¨ ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param fse
     * @throws BaseException
     */
    DataTableEntity importDeptBefore(DataTableEntity fse) throws BaseException;
    /**
     * å¯¼å…¥å²—位等级 ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param fse
     * @throws BaseException
     */
    DataTableEntity importPostLevelBefore(DataTableEntity fse) throws BaseException;
    /**
     * å¯¼å…¥å²—位 ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param fse
     * @throws BaseException
     */
    DataTableEntity importPostBefore(DataTableEntity fse) throws BaseException;
    /**
     * å¯¼å…¥å‘˜å·¥ ä¹‹å‰ æ•°æ®å¤„理
     *
     * @param fse
     * @throws BaseException
     */
    DataTableEntity importStaffBefore(DataTableEntity fse) throws BaseException;
}
product-server-data-export-import/src/main/java/com/product/module/data/service/idel/ISystemDataUpLoadService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,28 @@
package com.product.module.data.service.idel;
import com.alibaba.fastjson.JSONObject;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
/**
 * Copyright Â© 6c
 *
 * @Date: 2021-06-30 09:18
 * @Author: 6c
 * @Description:
 */
public interface ISystemDataUpLoadService {
    void deleteModel(FieldSetEntity fse) throws BaseException;
    JSONObject uploadTemplate(RequestParameterEntity rpe);
    void saveTemplate(FieldSetEntity fse);
    String recordDataImport(RequestParameterEntity rpe);
    void recordDataSave(FieldSetEntity fse);
}
product-server-data-export-import/src/main/java/com/product/module/data/utli/Custemhandler.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,67 @@
package com.product.module.data.utli;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Custemhandler extends AbstractColumnWidthStyleStrategy {
    private static final int MAX_COLUMN_WIDTH = 255;
    private Map<Integer, Map<Integer, Integer>> cache = new HashMap<Integer, Map<Integer, Integer>>(8);
    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head,
                                  Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (!needSetWidth) {
            return;
        }
        Map<Integer, Integer> maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo());
        if (maxColumnWidthMap == null) {
            maxColumnWidthMap = new HashMap<Integer, Integer>(16);
            cache.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
        }
        Integer columnWidth = dataLength(cellDataList, cell, isHead);
        if (columnWidth < 0) {
            return;
        }
        if (columnWidth > MAX_COLUMN_WIDTH) {
            columnWidth = MAX_COLUMN_WIDTH;
        }
        Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
        if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
            maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
        }
    }
    private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        }
        CellData cellData = cellDataList.get(0);
        CellDataTypeEnum type = cellData.getType();
        if (type == null) {
            return -1;
        }
        switch (type) {
            case STRING:
                return cellData.getStringValue().getBytes().length;
            case BOOLEAN:
                return cellData.getBooleanValue().toString().getBytes().length;
            case NUMBER:
                return cellData.getNumberValue().toString().getBytes().length;
            default:
                return -1;
        }
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/utli/CustomMergeStrategy.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,98 @@
package com.product.module.data.utli;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
public class CustomMergeStrategy extends AbstractMergeStrategy {
    /**
     * åˆ†ç»„,每几行合并一次
     */
    private List<List<Integer>> mergeColDataGroupCountList;
    /**
     * ç›®æ ‡åˆå¹¶åˆ—index
     */
    private List<Integer> targetColumnIndex;
    /**
     *     éœ€è¦å¼€å§‹åˆå¹¶å•元格的首行index
      */
    private Integer rowIndex;
    /**
     *     mergeColDataList为待合并目标列的值
      */
    public CustomMergeStrategy(List<List<String>> mergeColDataList, List<Integer> targetColumnIndex) {
        this.mergeColDataGroupCountList = getGroupCountList(mergeColDataList);
        this.targetColumnIndex = targetColumnIndex;
    }
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if (null == rowIndex) {
            rowIndex = cell.getRowIndex();
        }
        // ä»…从首行以及目标列的单元格开始合并,忽略其他
        if (cell.getRowIndex() == rowIndex && targetColumnIndex.contains(cell.getColumnIndex())) {
            //找到对应的需要合并的列
            AtomicInteger i = new AtomicInteger(0);
            Optional<Integer> first = targetColumnIndex.stream().filter(col -> {
                i.getAndIncrement();
                return col == cell.getColumnIndex();
            }).findFirst();
            mergeGroupColumn(sheet, first.get());
        }
    }
    private void mergeGroupColumn(Sheet sheet, Integer index) {
        int rowCount = rowIndex;
        for (Integer count : mergeColDataGroupCountList.get(index)) {
            if (count == 1) {
                rowCount += count;
                continue;
            }
            // åˆå¹¶å•元格
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1,
                    targetColumnIndex.get(index), targetColumnIndex.get(index));
            sheet.addMergedRegionUnsafe(cellRangeAddress);
            rowCount += count;
        }
    }
    /**
     *     è¯¥æ–¹æ³•将目标列根据值是否相同连续可合并,存储可合并的行数
      */
    private List<List<Integer>> getGroupCountList(List<List<String>> exportDataList) {
        if (CollUtil.isEmpty(exportDataList)) {
            return new ArrayList<>();
        }
        List<List<Integer>> groupCountListList = new ArrayList<>();
        exportDataList.forEach(dataList->{
            List<Integer> groupCountList = new ArrayList<>();
            int count = 1;
            for (int i = 1; i < dataList.size(); i++) {
                if (dataList.get(i).equals(dataList.get(i - 1))) {
                    count++;
                } else {
                    groupCountList.add(count);
                    count = 1;
                }
            }
            // å¤„理完最后一条后
            groupCountList.add(count);
            groupCountListList.add(groupCountList);
        });
        return groupCountListList;
    }
}
product-server-data-export-import/src/main/java/com/product/module/data/utli/SystemApiToMethods.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,243 @@
package com.product.module.data.utli;
import com.product.core.exception.BaseException;
import com.product.module.data.config.CmnCode;
import com.product.module.sys.version.ApiVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * cheng
 */
@Component
public class SystemApiToMethods {
    @Autowired
    ConfigurableApplicationContext applicationContext;
    /**
     * åªè¯»map
     */
    Map<String, Bean> beans;
    public Boolean getBeanIsExist(String api) {
        Bean bean = this.beans.get(api);
        return bean != null;
    }
    /**
     * é€šè¿‡api调用Controller层入口
     *
     * @param api
     * @return
     * @throws BaseException
     */
    public Object run(String api, Integer verion) throws BaseException {
        if (api == null) {
            return null;
        }
        if (api.indexOf("/") != 0) {
            api = "/" + api;
        }
        //通过上下文获取 request response
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return run(request, response, api, verion);
    }
    public boolean isVersion(String api) {
        String str = api;
        String pattern = ".*/v[0-9]*\\d$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        return m.matches();
    }
    public static void main(String args[]) {
    }
    /**
     * é€šè¿‡api调用Controller层入口
     *
     * @param request
     * @param response
     * @param api
     * @return
     * @throws BaseException
     */
    public Object run(HttpServletRequest request, HttpServletResponse response, String api, Integer version) throws BaseException {
        if (beans == null || api == null) return null;
        try {
            if (api.indexOf("/") != 0) {
                api = "/" + api;
            }
            api += version == null ? "" : !isVersion(api) ? "/v" + version : "";
            if (!getBeanIsExist(api)) {
                throw new BaseException(CmnCode.EXPORT_GET_API_METHOD_FILA.getValue(), CmnCode.EXPORT_GET_API_METHOD_FILA.getText() + api);
            }
            Bean bean = this.beans.get(api);
            if (bean != null) {
                Class<?>[] parameterType = bean.getParameterType();
                if (parameterType != null) {
                    Object[] params = new Object[parameterType.length];
                    for (int i = 0; i < parameterType.length; i++) {
                        Class<?> aClass = parameterType[i];
                        Class<?> httpServletRequestClass = HttpServletRequest.class;
                        Class<?> HttpServletResponseClass = HttpServletResponse.class;
                        if (aClass == httpServletRequestClass) {
                            params[i] = request;
                            continue;
                        }
                        if (aClass == HttpServletResponseClass) {
                            params[i] = response;
                            continue;
                        }
                        params[i] = null;
                    }
                    return bean.method.invoke(bean.bean, params);
                }
                return bean.method.invoke(bean.bean);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e);
        }
    }
    /**
     * å¯åŠ¨æ—¶åˆå§‹åŒ–æ‹¿åˆ°æ‰€æœ‰çš„è¯·æ±‚åœ°å€
     */
    @PostConstruct
    private void getAll() {
        //获取restcontroller注解的类名
        String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(RestController.class);
        Map<String, Bean> beanMap = new HashMap<>();
        //获取类对象
        for (String str : beanNamesForAnnotation) {
            Object bean = applicationContext.getBean(str);
            Class<?> forName = bean.getClass();
            //获取requestmapping注解的类
            RequestMapping declaredAnnotation = forName.getAnnotation(RequestMapping.class);
            if (declaredAnnotation != null) {
                String[] value = (declaredAnnotation.value());
                for (Method method : forName.getDeclaredMethods()) {
                    ApiVersion version = method.getAnnotation(ApiVersion.class);
                    RequestMapping api_value = method.getAnnotation(RequestMapping.class);
                    PostMapping annotation = method.getAnnotation(PostMapping.class);
                    if (api_value != null) {
                        Bean bean1 = new Bean();
                        String class_url = value[0] + api_value.value()[0].replace("{version}", "v" + (version == null ? "1" : String.valueOf(version.value())));
                        bean1.apiUrl = class_url;
                        bean1.version = version == null ? 1 : version.value();
                        bean1.bean = bean;
                        bean1.method = method;
                        beanMap.put(class_url, bean1);
                    } else if (annotation != null) {
                        Bean bean1 = new Bean();
                        String class_url = value[0] + annotation.value()[0].replace("{version}", "v" + (version == null ? "1" : "" + version.value()));
                        bean1.apiUrl = class_url;
                        bean1.version = version == null ? 1 : version.value();
                        bean1.bean = bean;
                        bean1.method = method;
                        beanMap.put(class_url, bean1);
                    }
                }
            }
            PostMapping annotation = forName.getAnnotation(PostMapping.class);
            if (annotation != null) {
                String[] value = annotation.value();
                for (Method method : forName.getDeclaredMethods()) {
                    ApiVersion version = method.getAnnotation(ApiVersion.class);
                    PostMapping api_value = method.getAnnotation(PostMapping.class);
                    if (api_value != null) {
                        Bean bean1 = new Bean();
                        String class_url = value[0] + api_value.value()[0].replace("{version}", "v" + (version == null ? "1" : "" + version.value()));
                        bean1.apiUrl = class_url;
                        bean1.version = version == null ? 1 : version.value();
                        bean1.bean = bean;
                        bean1.method = method;
                        beanMap.put(class_url, bean1);
                    }
                }
            }
        }
        this.beans = Collections.unmodifiableMap(beanMap);
    }
    private class Bean implements Serializable {
        private String apiUrl;
        private int version;
        private Object bean;
        private Method method;
        private ParameterizedType parameterizedType;
        public Method getMethod() {
            return method;
        }
        public void setMethod(Method method) {
            this.method = method;
        }
        public String getApiUrl() {
            return apiUrl;
        }
        public void setApiUrl(String apiUrl) {
            this.apiUrl = apiUrl;
        }
        public int getVersion() {
            return version;
        }
        public void setVersion(int version) {
            this.version = version;
        }
        public Object getBean() {
            return bean;
        }
        public void setBean(Object bean) {
            this.bean = bean;
        }
        private Class<?>[] getParameterType() {
            if (this.bean != null && this.method != null) {
                return this.method.getParameterTypes();
            }
            return null;
        }
    }
}