package com.hzya.frame.sys.template.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.sys.contrastTask.dao.ISysContrastTaskDao;
import com.hzya.frame.sys.contrastTask.service.ISysContrastTaskService;
import com.hzya.frame.sys.databaseFields.dao.IDatabaseFieldsMapper;
import com.hzya.frame.sys.databaseFields.entity.DatabaseFields;
import com.hzya.frame.sys.databaseNames.dao.IDatabaseNamesMapper;
import com.hzya.frame.sys.databaseNames.entity.DatabaseNames;
import com.hzya.frame.sys.entity.TemplateSave;
import com.hzya.frame.sys.entity.TemplateSaveFields;
import com.hzya.frame.sys.template.entity.TemplateDataDetailDto;
import com.hzya.frame.sys.template.entity.TemplateDataDto;
import com.hzya.frame.sys.templateButton.dao.ISysTemplateButtonDao;
import com.hzya.frame.sys.templateButton.entity.SysTemplateButtonEntity;
import com.hzya.frame.sys.templateFields.dao.ITemplateFieldsMapper;
import com.hzya.frame.sys.templateFields.entity.TemplateFields;
import com.hzya.frame.sys.templateRelation.dao.ITemplateRelationMapper;
import com.hzya.frame.sys.templateRelation.entity.TemplateRelation;
import com.hzya.frame.sys.templateView.dao.ITemplateViewMapper;
import com.hzya.frame.sys.templateView.entity.TemplateView;
import com.hzya.frame.sys.templateViewAccredit.dao.ITemplateViewAccreditMapper;
import com.hzya.frame.sys.templateViewAccredit.entity.TemplateViewAccredit;
import com.hzya.frame.sys.userTemplateButton.dao.ISysUserTemplateButtonDao;
import com.hzya.frame.sys.userTemplateButton.entity.SysUserTemplateButtonEntity;
import com.hzya.frame.sys.userTemplateView.dao.IUserTemplateViewMapper;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.exception.BaseSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import com.hzya.frame.serviceUtil.ServiceUtil;
import com.hzya.frame.sys.template.entity.Template;
import com.hzya.frame.sys.template.service.ITemplateService;
import com.hzya.frame.sys.template.dao.ITemplateMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description: 模版表  service
 * @tableName: sys_template
 * @entityName: Template
 * @author: gjh
 * @history: 1.0
 */
@Service(value = "templateService")
public class TemplateServiceImpl extends ServiceUtil implements ITemplateService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    protected ITemplateMapper templateMapper;
    @Resource
    protected ITemplateViewMapper templateviewMapper;//模板视图表
    @Resource
    protected IUserTemplateViewMapper usertemplateviewMapper;//用户模板视图展示表
    @Resource
    protected ITemplateViewAccreditMapper templateviewaccreditMapper;//模板视图授权
    @Resource
    protected ITemplateRelationMapper templaterelationMapper;//模版关系表
    @Resource
    protected ITemplateFieldsMapper templatefieldsMapper;//模版字段表
    @Resource
    protected IDatabaseNamesMapper databasenamesMapper;//数据库表名表
    @Resource
    protected IDatabaseFieldsMapper databaseFieldsMapper;//数据库字段表
    @Resource
    private ISysContrastTaskDao sysContrastTaskDao;
    @Resource
    private ISysTemplateButtonDao sysTemplateButtonDao;
    @Resource
    private ISysUserTemplateButtonDao sysUserTemplateButtonDao;
    @Resource
    private TaskExecutor taskExecutor;
    @Resource
    private ISysContrastTaskService sysContrastTaskService;

    private String idOption = "{\"id\":\"id\",\"type\":\"input\",\"title\":\"id\",\"hidden\":true,\"tableSort\":\"0\",\"disabled\":true,\"required\":true,\"row\":12}";
    private String formmainOption = "{}";
    private String sortsOption = "{}";
    private String createUserIdOption = "{}";
    private String createTimeOption = "{}";
    private String modifyUserIdOption = "{}";
    private String modifyTimeOption = "{}";
    private String stsOption = "{}";
    private String orgOption = "{}";
    private String arrayOption = "{}";

    /**
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 添加模版以及模版类型数据结构
     **/
    @Override
    public JsonResultEntity saveTemplate(JSONObject object) {
        TemplateDataDto entity = getData("jsonStr", object, TemplateDataDto.class);
        if (entity == null
                || entity.getServiceName() == null || "".equals(entity.getServiceName())
                || entity.getTableName() == null || "".equals(entity.getTableName())
                || entity.getTemplateDataDetailDtoList() == null || entity.getTemplateDataDetailDtoList().size() == 0) {
            return BaseResult.getFailureMessageEntity("请求数据错误，请联系管理员");
        }
        //处理保存数据

        //校验服务是否已经存在
        if (checkServiceName(entity.getServiceName())) {
            return BaseResult.getFailureMessageEntity("服务名已经存在，请重新输入");
        }
        //校验表是否已经存在
        if (checkTableName(entity.getServiceName())) {
            return BaseResult.getFailureMessageEntity("表已经存在，请重新输入");
        }
        //保存数据
        try {
            doSaveTemplate(entity, false);
        } catch (BaseSystemException e) {
            logger.error("保存数据错误：{}", e.getMessage());
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("保存数据成功");
    }

    @Override
    public JsonResultEntity updateTemplate(JSONObject object) {
        TemplateDataDto entity = getData("jsonStr", object, TemplateDataDto.class);
        if (entity == null
                || entity.getServiceName() == null || "".equals(entity.getServiceName())
                || entity.getTableName() == null || "".equals(entity.getTableName())
                || entity.getTemplateDataDetailDtoList() == null || entity.getTemplateDataDetailDtoList().size() == 0) {
            return BaseResult.getFailureMessageEntity("请求数据错误，请联系管理员");
        }
        //处理保存数据
        Template template = new Template();
        template.setServiceName(entity.getServiceName());// Service服务名
        template.setSts("Y");
        List<Template> templateList = templateMapper.entity_list_base(template);
        //校验服务是否已经存在
        if (templateList == null || templateList.size() != 1) {
            return BaseResult.getFailureMessageEntity("服务名错误，请检查");
        }
        //校验表是否已经存在
        if (!checkTableName(entity.getServiceName())) {
            return BaseResult.getFailureMessageEntity("表不存在，请检查");
        }
        //保存数据
        try {
            doUpdateTemplate(entity, false, templateList.get(0));
        } catch (BaseSystemException e) {
            logger.error("保存数据错误：{}", e.getMessage());
            return BaseResult.getFailureMessageEntity(e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("保存数据成功");
    }

    /**
     * @param entity 需要修改的数据
     * @param flag   是否是明细表
     * @return void
     * @Author lvleigang
     * @Description 保存模版的相关数据
     * @Date 4:19 下午 2023/8/16
     **/
    private void doUpdateTemplate(TemplateDataDto entity, boolean flag, Template oldTemplate) {
        //修改数据库表
        DatabaseNames databaseNames = updateDatabaseNames(entity, oldTemplate);
        //修改数据库表字段
        List<DatabaseFields> databaseFields = updateDatabaseFields(entity, flag);
        //修改表
        altercreateTable(databaseNames, databaseFields);
        //修改模版表
        Template template = updateTemplateValue(entity,oldTemplate);
        //修改模版关联表
        List<TemplateRelation> templateRelationList = updateTemplateRelation(entity,template);
        //修改模版字段表
        List<TemplateFields> templateFieldsList = updateTemplateFields(databaseFields, templateRelationList, entity, template, databaseNames);
        //修改模板视图表
        List<TemplateView> templateViews = updateTemplateView(templateFieldsList,template);
        //修改明细表
        //判断是否有明细
        if (entity.getTemplateDataDtoList() != null && entity.getTemplateDataDtoList().size() > 0) {
            for (int i = 0; i < entity.getTemplateDataDtoList().size(); i++) {
                //判断是新增还是修改
                //处理保存数据
                Template childTemplate = new Template();
                childTemplate.setServiceName(entity.getTemplateDataDtoList().get(i).getServiceName());// Service服务名
                childTemplate.setSts("Y");
                List<Template> templateList = templateMapper.entity_list_base(childTemplate);
                //校验服务是否已经存在
                if (templateList == null || templateList.size() == 0) {
                    doSaveTemplate(entity.getTemplateDataDtoList().get(i), true);
                } else if (templateList.size() == 1) {
                    doUpdateTemplate(entity, false, templateList.get(0));
                } else {
                    //系统错误
                    throw new BaseSystemException("服务：" + entity.getTemplateDataDtoList().get(i).getServiceName() + "存在多个，请修改");
                }
            }
        }
    }

    /**
     * @Author lvleigang
     * @Description  修改模板视图表
     * @Date 2:35 下午 2023/8/18
     * @param templateFieldsList
     * @return java.util.List<com.hzya.frame.sys.templateView.entity.TemplateView>
     **/
    private List<TemplateView> updateTemplateView(List<TemplateFields> templateFieldsList,Template templatet) {
        TemplateView deleteTemplateView = new TemplateView();
        deleteTemplateView.setServiceName(templatet.getServiceName());
        deleteTemplateView.setSts("Y");
        deleteTemplateView.setModifyUserId(StpUtil.getLoginIdAsString());
        templateviewMapper.entity_logicDelete_Multi_Condition(deleteTemplateView);

        List<TemplateView> templateViews = new ArrayList<>();
        for (int i = 0; i < templateFieldsList.size(); i++) {
            TemplateView templateView1 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "1", JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getString("searchSort") != null ? JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getLong("searchSort") : null, templateFieldsList.get(i).getServiceName());//查询
            templateView1.setCreate();
            TemplateView templateView2 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "2", JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getString("tableSort") != null ? JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getLong("tableSort") : null, templateFieldsList.get(i).getServiceName());
            templateView2.setCreate();
            TemplateView templateView3 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "3", templateFieldsList.get(i).getSorts(), templateFieldsList.get(i).getServiceName());//新增
            templateView3.setCreate();
            TemplateView templateView4 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "4", templateFieldsList.get(i).getSorts(), templateFieldsList.get(i).getServiceName());//编辑
            templateView4.setCreate();
            TemplateView templateView5 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "5", templateFieldsList.get(i).getSorts(), templateFieldsList.get(i).getServiceName());//查看
            templateView5.setCreate();

            if ("id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
                templateViews.add(templateView2);
                templateViews.add(templateView4);
                templateViews.add(templateView5);
            } else if ("formmain_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("sorts".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("create_user_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("create_time".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("modify_user_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("modify_time".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("sts".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("org_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else {
                if (templateFieldsList.get(i).getFieldsOption().contains("searchSort")) {
                    templateViews.add(templateView1);
                }
                if (templateFieldsList.get(i).getFieldsOption().contains("tableSort")) {
                    templateViews.add(templateView2);
                }
                templateViews.add(templateView3);
                templateViews.add(templateView4);
                templateViews.add(templateView5);
            }
        }
        for (int i = 0; i < templateViews.size(); i++) {
            templateviewMapper.entity_insert(templateViews.get(i));
        }
        return templateViews;
    }

    /**
     * @Author lvleigang
     * @Description  修改模版字段表
     * @Date 2:11 下午 2023/8/18
     * @param databaseFields
     * @param templateRelationList
     * @param entity
     * @param template
     * @param databaseNames
     * @return java.util.List<com.hzya.frame.sys.templateFields.entity.TemplateFields>
     **/
    private List<TemplateFields> updateTemplateFields(List<DatabaseFields> databaseFields, List<TemplateRelation> templateRelationList, TemplateDataDto entity, Template template, DatabaseNames databaseNames) {
        TemplateFields oldTemplateFields = new TemplateFields();
        oldTemplateFields.setServiceName(template.getServiceName());
        oldTemplateFields.setSts("Y");
        List<TemplateFields>  oldTemplateFieldsList = templatefieldsMapper.entity_list_base(oldTemplateFields);
        List<TemplateFields> templateFieldsList = new ArrayList<>();
        if (databaseFields != null && databaseFields.size() > 0) {
            for (int i = 0; i < databaseFields.size(); i++) {
                TemplateFields templateFields = new TemplateFields();
                templateFields.setCreate();
                templateFields.setTemplateId(template.getId());//模版id
                templateFields.setServiceName(entity.getServiceName());//Service服务名
                templateFields.setTableName(entity.getTableName());//Table名称（英文名称）
                templateFields.setFieldsId(databaseFields.get(i).getId());//字段表id
                templateFields.setDatabaseId(databaseNames.getId());//数据库表id
                templateFields.setFieldsName(databaseFields.get(i).getFieldsName());//字段名称
                templateFields.setFieldsRemark(databaseFields.get(i).getFieldsRemark());//字段备注
                templateFields.setFieldsType(databaseFields.get(i).getFieldsType());//类型 Vachar,number,decimal,datetime,array(如为array字段需设置明细数据)
                templateFields.setFieldsLength(databaseFields.get(i).getFieldsLength());//长度
                templateFields.setFieldsRequired(databaseFields.get(i).getFieldsRequired());//是否必填
                templateFields.setFieldsSole(databaseFields.get(i).getFieldsSole());//是否唯一性
                templateFields.setFieldsOption(databaseFields.get(i).getFieldsOption());//字段属性 设置字段的渲染属性，存json Todo
                templateFields.setSorts(templateFieldsList.size() + 1L);//排序
            }
        }
        if (templateRelationList != null && templateRelationList.size() > 0) {
            for (int i = 0; i < templateRelationList.size(); i++) {
                TemplateFields templateFields = new TemplateFields();
                templateFields.setCreate();
                templateFields.setTemplateId(template.getId());//模版id
                templateFields.setServiceName(entity.getServiceName());//Service服务名
                templateFields.setTableName(entity.getTableName());//Table名称（英文名称）
                templateFields.setFieldsName(templateRelationList.get(i).getParentTableFields());//字段名称
                templateFields.setFieldsRemark(templateRelationList.get(i).getParentTableRemark());//字段备注
                templateFields.setFieldsType("5");//类型 Vachar,number,decimal,datetime,array(如为array字段需设置明细数据)
                templateFields.setFieldsOption(arrayOption);//字段属性 设置字段的渲染属性，存json Todo
                templateFields.setDetailFields(templateRelationList.get(i).getParentTableFields());
                templateFields.setDetailService(templateRelationList.get(i).getChildServiceName());
                templateFields.setDetailTable(templateRelationList.get(i).getChildTableName());
                templateFields.setSorts(templateFieldsList.size() + 1L);//排序
            }
        }
        for (int i = 0; i < templateFieldsList.size(); i++) {
            boolean checkFlag = false;
            for (int i1 = 0; i1 < oldTemplateFieldsList.size(); i1++) {
                if (templateFieldsList.get(i).getFieldsName().equals(oldTemplateFieldsList.get(i1).getFieldsName())) {
                    checkFlag = true;
                    templateFieldsList.get(i).setId(oldTemplateFieldsList.get(i1).getId());//id
                    templateFieldsList.get(i).setCreateUserId(oldTemplateFieldsList.get(i1).getCreateUserId());//创建人
                    templateFieldsList.get(i).setCreateTime(oldTemplateFieldsList.get(i1).getCreateTime());//创建时间
                    break;
                }
            }
            if (checkFlag) {//修改
                templatefieldsMapper.entity_update(templateFieldsList.get(i));
            } else {//新增
                templatefieldsMapper.entity_insert(templateFieldsList.get(i));
            }
        }
        return templateFieldsList;
    }

    /**
     * @Author lvleigang
     * @Description  修改模版关联表
     * @Date 1:55 下午 2023/8/18
     * @param entity
     * @param template
     * @return java.util.List<com.hzya.frame.sys.templateRelation.entity.TemplateRelation>
     **/
    private List<TemplateRelation> updateTemplateRelation(TemplateDataDto entity, Template template) {
        List<TemplateRelation> templateRelationList = new ArrayList<>();
        //先删除原先的
        TemplateRelation delectTemplateRelation = new TemplateRelation();
        delectTemplateRelation.setParentServiceName(template.getServiceName());//Service服务名
        delectTemplateRelation.setSts("Y");
        templaterelationMapper.entity_logicDelete_Multi_Condition(delectTemplateRelation);

        //判断是否有明细表
        if (entity.getTemplateDataDtoList() != null && entity.getTemplateDataDtoList().size() > 0) {
            for (int i = 0; i < entity.getTemplateDataDtoList().size(); i++) {
                TemplateRelation templateRelation = setTemplateRelation(entity.getServiceName(), entity.getTableName(), entity.getTemplateDataDtoList().get(i));
                templateRelationList.add(templateRelation);
                templaterelationMapper.entity_insert(templateRelation);
            }
        }
        return templateRelationList;
    }

    /**
     * @Author lvleigang
     * @Description  修改模版表
     * @Date 1:45 下午 2023/8/18
     * @param entity
     * @return com.hzya.frame.sys.template.entity.Template
     **/
    private Template updateTemplateValue(TemplateDataDto entity,Template oldTemplate) {
        oldTemplate.setUpdate();
        oldTemplate.setTemplateName(entity.getTableRemark());//模版名称
        oldTemplate.setTemplateCode(entity.getTableName());//模板编码
        oldTemplate.setTemplateType(entity.getTemplateType());// 类型		1单据,2档案
        oldTemplate.setServiceName(entity.getServiceName());// Service服务名
        oldTemplate.setTableName(entity.getTableName());// 表名（英文名称）
        templateMapper.entity_update(oldTemplate);
        return oldTemplate;
    }

    /**
     * @param databaseNames
     * @param databaseFields
     * @return void
     * @Author lvleigang
     * @Description 创建或修改表
     * @Date 11:02 上午 2023/8/18
     **/
    private void altercreateTable(DatabaseNames databaseNames, List<DatabaseFields> databaseFields) {
        //先判断表是否存在
        if (!checkTable(databaseNames.getTableName())) {
            //创建表
            Map<String, Object> maps = new HashMap<>();
            maps.put("databaseNames", databaseNames);
            maps.put("databaseFields", databaseFields);
            Integer i = templateMapper.createTable(maps);
        } else {
            //修改表
            //数据类型 1、修改 2、新增
            //修改数据库名称
            Map<String, String> tablename = new HashMap<>();
            tablename.put("tableName", databaseNames.getTableName());
            tablename.put("tableRemark", databaseNames.getTableRemark());
            templateMapper.alterTableName(tablename);
            Map<String, String> maps = new HashMap<>();
            maps.put("databaseNames", "databaseNames");
            maps.put("databaseFields", "databaseFields");
            Integer i = templateMapper.alterTable(maps);
        }
    }

    /**
     * @param entity
     * @param flag
     * @return java.util.List<com.hzya.frame.sys.databaseFields.entity.DatabaseFields>
     * @Author lvleigang
     * @Description 修改数据库表字段
     * @Date 10:30 上午 2023/8/18
     **/
    private List<DatabaseFields> updateDatabaseFields(TemplateDataDto entity, boolean flag) {
        //设置数据库表字段
        List<DatabaseFields> databaseFieldsList = new ArrayList<>();
        //设置id
        databaseFieldsList.add(createDataBaseField(entity.getServiceName(), entity.getTableName(), "id", "主键id", "1", "50", idOption, "1", "1", 1L));
        //明细表的时候添加主表id字段
        if (flag) {
            databaseFieldsList.add(createDataBaseField(entity.getServiceName(), entity.getTableName(), "formmain_id", "主表id", "1", "50", formmainOption, "1", "2", 2L));
        }
        //添加业务字段
        for (int i = 0; i < entity.getTemplateDataDetailDtoList().size(); i++) {
            TemplateDataDetailDto templateDataDetailDto = entity.getTemplateDataDetailDtoList().get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("maxlength", templateDataDetailDto.getFieldsLength());
            jsonObject.put("required", "1".equals(templateDataDetailDto.getFieldsRequired()) ? "true" : "false");
            jsonObject.put("title", templateDataDetailDto.getFieldsRemark());
            jsonObject.put("type", templateDataDetailDto.getFieldsType());
            jsonObject.put("id", templateDataDetailDto.getFieldsName());
            if (templateDataDetailDto.getFieldsOption() != null && templateDataDetailDto.getFieldsOption().size() > 0) {
                jsonObject.putAll(templateDataDetailDto.getFieldsOption());
            }
            databaseFieldsList.add(createDataBaseField(entity.getServiceName(), entity.getTableName(), templateDataDetailDto.getFieldsName(), templateDataDetailDto.getFieldsRemark(), templateDataDetailDto.getDataBaseType(), templateDataDetailDto.getFieldsLength(), jsonObject.toJSONString(), templateDataDetailDto.getFieldsRequired(), templateDataDetailDto.getFieldsSole(), databaseFieldsList.size() + 1));
        }
        //设置系统字段
        setSysFields(databaseFieldsList, entity.getServiceName(), entity.getTableName());

        //查询原字段
        DatabaseFields databaseFields = new DatabaseFields();
        databaseFields.setServiceName(entity.getServiceName());
        databaseFields.setSts("Y");
        List<DatabaseFields> oldList = databaseFieldsMapper.entity_list_base(databaseFields);
        //保存数据
        for (int i = 0; i < databaseFieldsList.size(); i++) {
            boolean checkFlag = false;
            for (int i1 = 0; i1 < oldList.size(); i1++) {
                if (databaseFieldsList.get(i).getFieldsName().equals(oldList.get(i1).getFieldsName())) {
                    checkFlag = true;
                    databaseFieldsList.get(i).setId(oldList.get(i1).getId());//id
                    databaseFieldsList.get(i).setCreateUserId(oldList.get(i1).getCreateUserId());//创建人
                    databaseFieldsList.get(i).setCreateTime(oldList.get(i1).getCreateTime());//创建时间
                    break;
                }
            }
            if (checkFlag) {//修改
                databaseFieldsMapper.entity_update(databaseFieldsList.get(i));
                databaseFieldsList.get(i).setDataType("1");//数据类型 1、修改 2、新增
            } else {//新增
                databaseFieldsMapper.entity_insert(databaseFieldsList.get(i));
                databaseFieldsList.get(i).setDataType("2");//数据类型 1、修改 2、新增
            }
        }
        return databaseFieldsList;
    }

    /**
     * @param entity
     * @param oldTemplate
     * @return com.hzya.frame.sys.databaseNames.entity.DatabaseNames
     * @Author lvleigang
     * @Description 数据库表名表
     * @Date 4:55 下午 2023/8/17
     **/
    private DatabaseNames updateDatabaseNames(TemplateDataDto entity, Template oldTemplate) {
        //查询数据库表名表
        DatabaseNames databaseNames = new DatabaseNames();
        databaseNames.setServiceName(oldTemplate.getServiceName());
        databaseNames.setSts("Y");
        List<DatabaseNames> databaseNamesList = databasenamesMapper.entity_list_base(databaseNames);
        if (databaseNamesList != null && databaseNamesList.size() == 1) {
            databaseNames = databaseNamesList.get(0);
        } else {
            throw new BaseSystemException("服务：" + oldTemplate.getServiceName() + "数据库表名表错误，请修改");
        }
        databaseNames.setSts("Y");
        databaseNames.setUpdate();
        databaseNames.setServiceName(entity.getServiceName());//Service服务名
        databaseNames.setTableName(entity.getTableName());//表名（英文名称）
        databaseNames.setTableRemark(entity.getTableRemark());//表名（中文名称）
        databaseNames.setRemark(entity.getTableRemark());//备注
        databasenamesMapper.entity_update(databaseNames);
        return databaseNames;
    }

    /**
     * @param oldTemplate
     * @return void
     * @Author lvleigang
     * @Description 删除原表数据
     * @Date 4:22 下午 2023/8/17
     **/
    private void deleteDatabaseNames(Template oldTemplate) {
        DatabaseNames databaseNames = new DatabaseNames();
        databaseNames.setServiceName(oldTemplate.getServiceName());
        databaseNames.setModifyUserId(StpUtil.getLoginIdAsString());
        databasenamesMapper.entity_logicDelete_Multi_Condition(databaseNames);
    }

    /**
     * @param entity 需要保存的数据
     * @param flag   是否是明细表
     * @return void
     * @Author lvleigang
     * @Description 保存模版的相关数据
     * @Date 4:19 下午 2023/8/16
     **/
    private void doSaveTemplate(TemplateDataDto entity, boolean flag) throws BaseSystemException {
        //保存数据库表
        DatabaseNames databaseNames = savaDatabaseNames(entity);
        //保存数据库表字段
        List<DatabaseFields> databaseFields = saveDatabaseFields(entity, flag);
        //创建表
        createTable(databaseNames, databaseFields);
        //设置模版表
        Template template = savaTemplate(entity);
        //设置模版关联表
        List<TemplateRelation> templateRelationList = saveTemplateRelation(entity);
        //设置模版字段表
        List<TemplateFields> templateFieldsList = saveTemplateFields(databaseFields, templateRelationList, entity, template, databaseNames);
        //设置模版按钮
        List<SysTemplateButtonEntity> sysTemplateButtonEntityList = setButton(template.getId(), entity.getServiceName(), entity.getTableName());
        //设置模板视图表
        List<TemplateView> templateViews = saveTemplateView(templateFieldsList);
        //设置模板视图授权表
        TemplateViewAccredit templateViewAccredit = saveTemplateViewAccredit(template);
        //设置用户模板授权表 todo 这个暂时不设置，用户没有设置读取模版设置内容
        //设置用户模版按钮
        List<SysUserTemplateButtonEntity> sysUserTemplateButtonEntityList = setUserButton(sysTemplateButtonEntityList);
        //保存明细表
        //判断是否有明细
        if (entity.getTemplateDataDtoList() != null && entity.getTemplateDataDtoList().size() > 0) {
            for (int i = 0; i < entity.getTemplateDataDtoList().size(); i++) {
                doSaveTemplate(entity.getTemplateDataDtoList().get(i), true);
            }
        }
    }

    /**
     * @param template
     * @return java.util.List<com.hzya.frame.sys.templateViewAccredit.entity.TemplateViewAccredit>
     * @Author lvleigang
     * @Description 设置模板视图授权表
     * @Date 3:22 下午 2023/8/17
     **/
    private TemplateViewAccredit saveTemplateViewAccredit(Template template) {
        TemplateViewAccredit templateViewAccredit = new TemplateViewAccredit();
        templateViewAccredit.setCreate();
        templateViewAccredit.setTemplateId(template.getId());
        templateViewAccredit.setUserId(StpUtil.getLoginIdAsString());
        templateviewaccreditMapper.entity_insert(templateViewAccredit);
        return templateViewAccredit;
    }

    /**
     * @param templateFieldsList
     * @return java.util.List<com.hzya.frame.sys.templateView.entity.TemplateView>
     * @Author lvleigang
     * @Description 设置模板视图表
     * @Date 3:19 下午 2023/8/17
     **/
    private List<TemplateView> saveTemplateView(List<TemplateFields> templateFieldsList) {
        List<TemplateView> templateViews = new ArrayList<>();
        for (int i = 0; i < templateFieldsList.size(); i++) {
            TemplateView templateView1 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "1", JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getString("searchSort") != null ? JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getLong("searchSort") : null, templateFieldsList.get(i).getServiceName());//查询
            templateView1.setCreate();
            TemplateView templateView2 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "2", JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getString("tableSort") != null ? JSONObject.parseObject(templateFieldsList.get(i).getFieldsOption()).getLong("tableSort") : null, templateFieldsList.get(i).getServiceName());
            templateView2.setCreate();
            TemplateView templateView3 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "3", templateFieldsList.get(i).getSorts(), templateFieldsList.get(i).getServiceName());//新增
            templateView3.setCreate();
            TemplateView templateView4 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "4", templateFieldsList.get(i).getSorts(), templateFieldsList.get(i).getServiceName());//编辑
            templateView4.setCreate();
            TemplateView templateView5 = new TemplateView(templateFieldsList.get(i).getTemplateId(), templateFieldsList.get(i).getId(), "5", templateFieldsList.get(i).getSorts(), templateFieldsList.get(i).getServiceName());//查看
            templateView5.setCreate();

            if ("id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
                templateViews.add(templateView2);
                templateViews.add(templateView4);
                templateViews.add(templateView5);
            } else if ("formmain_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("sorts".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("create_user_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("create_time".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("modify_user_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("modify_time".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("sts".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else if ("org_id".equals(templateFieldsList.get(i).getFieldsName().toLowerCase())) {
            } else {
                if (templateFieldsList.get(i).getFieldsOption().contains("searchSort")) {
                    templateViews.add(templateView1);
                }
                if (templateFieldsList.get(i).getFieldsOption().contains("tableSort")) {
                    templateViews.add(templateView2);
                }
                templateViews.add(templateView3);
                templateViews.add(templateView4);
                templateViews.add(templateView5);
            }
        }
        for (int i = 0; i < templateViews.size(); i++) {
            templateviewMapper.entity_insert(templateViews.get(i));
        }
        return templateViews;
    }

    /**
     * @param sysTemplateButtonEntityList
     * @return java.util.List<com.hzya.frame.sys.userTemplateButton.entity.SysUserTemplateButtonEntity>
     * @Author lvleigang
     * @Description 设置用户模板授权表
     * @Date 3:09 下午 2023/8/17
     **/
    private List<SysUserTemplateButtonEntity> setUserButton(List<SysTemplateButtonEntity> sysTemplateButtonEntityList) {
        List<SysUserTemplateButtonEntity> sysUserTemplateButtonEntityList = new ArrayList<>();
        if (sysTemplateButtonEntityList != null && sysTemplateButtonEntityList.size() > 0) {
            for (int i = 0; i < sysTemplateButtonEntityList.size(); i++) {
                SysUserTemplateButtonEntity u3 = new SysUserTemplateButtonEntity();
                u3.setId(UUIDUtils.getUUID());
                u3.setTemplateId(sysTemplateButtonEntityList.get(i).getTemplateId());
                u3.setServiceName(sysTemplateButtonEntityList.get(i).getServiceName());
                u3.setButtonId(sysTemplateButtonEntityList.get(i).getId());
                u3.setUserId(StpUtil.getLoginIdAsString());
                u3.setCreateUserId(StpUtil.getLoginIdAsString());
                u3.setModifyUserId(StpUtil.getLoginIdAsString());
                u3.setCreateTime(new Date());
                u3.setModifyTime(new Date());
                u3.setSts("Y");
                sysUserTemplateButtonDao.save(u3);
            }
        }
        return sysUserTemplateButtonEntityList;
    }

    /**
     * @param id
     * @param serviceName
     * @param tableName
     * @return java.util.List<com.hzya.frame.sys.templateButton.entity.SysTemplateButtonEntity>
     * @Author lvleigang
     * @Description 设置模版按钮
     * @Date 2:45 下午 2023/8/17
     **/
    private List<SysTemplateButtonEntity> setButton(String id, String serviceName, String tableName) {
        List<SysTemplateButtonEntity> sysTemplateButtonEntityList = new ArrayList<>();
        SysTemplateButtonEntity tem1 = new SysTemplateButtonEntity();
        tem1.setId(UUIDUtils.getUUID());
        tem1.setTemplateId(id);
        tem1.setServiceName(serviceName);
        tem1.setTableName(tableName);
        tem1.setButtonType("search");
        tem1.setButtonTitle("搜索");
        tem1.setButtonStyle("success");
        tem1.setButtonSort("1");
        tem1.setButtonIcon("el-icon-search");
        tem1.setCreateUserId(StpUtil.getLoginIdAsString());
        tem1.setModifyUserId(StpUtil.getLoginIdAsString());
        tem1.setCreateTime(new Date());
        tem1.setModifyTime(new Date());
        tem1.setSts("Y");
        sysTemplateButtonDao.save(tem1);
        sysTemplateButtonEntityList.add(tem1);
        SysTemplateButtonEntity tem2 = new SysTemplateButtonEntity();
        tem2.setId(UUIDUtils.getUUID());
        tem2.setTemplateId(id);
        tem2.setServiceName(serviceName);
        tem2.setTableName(tableName);
        tem2.setButtonType("resize");
        tem2.setButtonTitle("重置");
        tem2.setButtonStyle("primary");
        tem2.setButtonSort("2");
        tem2.setButtonIcon("el-icon-refresh");
        tem2.setCreateUserId(StpUtil.getLoginIdAsString());
        tem2.setModifyUserId(StpUtil.getLoginIdAsString());
        tem2.setCreateTime(new Date());
        tem2.setModifyTime(new Date());
        tem2.setSts("Y");
        sysTemplateButtonDao.save(tem2);
        sysTemplateButtonEntityList.add(tem2);
        SysTemplateButtonEntity tem3 = new SysTemplateButtonEntity();
        tem3.setId(UUIDUtils.getUUID());
        tem3.setTemplateId(id);
        tem3.setServiceName(serviceName);
        tem3.setTableName(tableName);
        tem3.setButtonType("new");
        tem3.setButtonTitle("新建");
        tem3.setButtonStyle("primary");
        tem3.setButtonSort("3");
        tem3.setButtonIcon("el-icon-edit");
        tem3.setCreateUserId(StpUtil.getLoginIdAsString());
        tem3.setModifyUserId(StpUtil.getLoginIdAsString());
        tem3.setCreateTime(new Date());
        tem3.setModifyTime(new Date());
        tem3.setSts("Y");
        sysTemplateButtonDao.save(tem3);
        sysTemplateButtonEntityList.add(tem3);
        return sysTemplateButtonEntityList;
    }

    /**
     * @param databaseFields
     * @param templateRelationList
     * @param entity
     * @param template
     * @return java.util.List<com.hzya.frame.sys.templateFields.entity.TemplateFields>
     * @Author lvleigang
     * @Description 设置模版字段表
     * @Date 11:47 上午 2023/8/17
     **/
    private List<TemplateFields> saveTemplateFields(List<DatabaseFields> databaseFields, List<TemplateRelation> templateRelationList, TemplateDataDto entity, Template template, DatabaseNames databaseNames) {
        List<TemplateFields> templateFieldsList = new ArrayList<>();
        if (databaseFields != null && databaseFields.size() > 0) {
            for (int i = 0; i < databaseFields.size(); i++) {
                TemplateFields templateFields = new TemplateFields();
                templateFields.setCreate();
                templateFields.setTemplateId(template.getId());//模版id
                templateFields.setServiceName(entity.getServiceName());//Service服务名
                templateFields.setTableName(entity.getTableName());//Table名称（英文名称）
                templateFields.setFieldsId(databaseFields.get(i).getId());//字段表id
                templateFields.setDatabaseId(databaseNames.getId());//数据库表id
                templateFields.setFieldsName(databaseFields.get(i).getFieldsName());//字段名称
                templateFields.setFieldsRemark(databaseFields.get(i).getFieldsRemark());//字段备注
                templateFields.setFieldsType(databaseFields.get(i).getFieldsType());//类型 Vachar,number,decimal,datetime,array(如为array字段需设置明细数据)
                templateFields.setFieldsLength(databaseFields.get(i).getFieldsLength());//长度
                templateFields.setFieldsRequired(databaseFields.get(i).getFieldsRequired());//是否必填
                templateFields.setFieldsSole(databaseFields.get(i).getFieldsSole());//是否唯一性
                templateFields.setFieldsOption(databaseFields.get(i).getFieldsOption());//字段属性 设置字段的渲染属性，存json Todo
                templateFields.setSorts(templateFieldsList.size() + 1L);//排序
            }
        }
        if (templateRelationList != null && templateRelationList.size() > 0) {
            for (int i = 0; i < templateRelationList.size(); i++) {
                TemplateFields templateFields = new TemplateFields();
                templateFields.setCreate();
                templateFields.setTemplateId(template.getId());//模版id
                templateFields.setServiceName(entity.getServiceName());//Service服务名
                templateFields.setTableName(entity.getTableName());//Table名称（英文名称）
                templateFields.setFieldsName(templateRelationList.get(i).getParentTableFields());//字段名称
                templateFields.setFieldsRemark(templateRelationList.get(i).getParentTableRemark());//字段备注
                templateFields.setFieldsType("5");//类型 Vachar,number,decimal,datetime,array(如为array字段需设置明细数据)
                templateFields.setFieldsOption(arrayOption);//字段属性 设置字段的渲染属性，存json Todo
                templateFields.setDetailFields(templateRelationList.get(i).getParentTableFields());
                templateFields.setDetailService(templateRelationList.get(i).getChildServiceName());
                templateFields.setDetailTable(templateRelationList.get(i).getChildTableName());
                templateFields.setSorts(templateFieldsList.size() + 1L);//排序
            }
        }
        for (int i = 0; i < templateFieldsList.size(); i++) {
            templatefieldsMapper.entity_insert(templateFieldsList.get(i));
        }
        return templateFieldsList;
    }

    /**
     * @param entity
     * @return java.util.List<com.hzya.frame.sys.templateRelation.entity.TemplateRelation>
     * @Author lvleigang
     * @Description 设置模版关联表
     * @Date 11:33 上午 2023/8/17
     **/
    private List<TemplateRelation> saveTemplateRelation(TemplateDataDto entity) {
        List<TemplateRelation> templateRelationList = new ArrayList<>();
        //判断是否有明细表
        if (entity.getTemplateDataDtoList() != null && entity.getTemplateDataDtoList().size() > 0) {
            for (int i = 0; i < entity.getTemplateDataDtoList().size(); i++) {
                TemplateRelation templateRelation = setTemplateRelation(entity.getServiceName(), entity.getTableName(), entity.getTemplateDataDtoList().get(i));
                templateRelationList.add(templateRelation);
                templaterelationMapper.entity_insert(templateRelation);
            }
        }
        return templateRelationList;
    }

    /**
     * @param serviceName
     * @param tableName
     * @param templateDataDto
     * @return com.hzya.frame.sys.templateRelation.entity.TemplateRelation
     * @Author lvleigang
     * @Description 设置保存参数
     * @Date 11:37 上午 2023/8/17
     **/
    private TemplateRelation setTemplateRelation(String serviceName, String tableName, TemplateDataDto templateDataDto) {
        TemplateRelation templateRelation = new TemplateRelation();
        templateRelation.setCreate();
        templateRelation.setParentServiceName(serviceName);//Service服务名
        templateRelation.setParentTableName(tableName);//Service服务名
        templateRelation.setParentTableFields(templateDataDto.getServiceName() + "_Detail");//主表逻辑字段，返回前台字段
        templateRelation.setParentTableRemark(templateDataDto.getTableRemark());//主表逻辑字段，返回前台显示
        templateRelation.setChildServiceName(templateDataDto.getServiceName());//
        templateRelation.setChildTableName(templateDataDto.getTableName());//
        return templateRelation;
    }

    /**
     * @param entity
     * @return com.hzya.frame.sys.template.entity.Template
     * @Author lvleigang
     * @Description 设置模版表
     * @Date 11:25 上午 2023/8/17
     **/
    private Template savaTemplate(TemplateDataDto entity) {
        Template template = new Template();
        template.setCreate();
        template.setTemplateName(entity.getTableRemark());//模版名称
        template.setTemplateCode(entity.getTableName());//模板编码
        template.setTemplateType(entity.getTemplateType());// 类型		1单据,2档案
        template.setServiceName(entity.getServiceName());// Service服务名
        template.setTableName(entity.getTableName());// 表名（英文名称）
        templateMapper.entity_insert(template);
        return template;
    }

    /**
     * @param databaseNames
     * @param databaseFields
     * @return void
     * @Author lvleigang
     * @Description 创建表
     * @Date 4:36 下午 2023/7/11
     **/
    private void createTable(DatabaseNames databaseNames, List<DatabaseFields> databaseFields) {
        //先判断表是否存在
        if (!checkTable(databaseNames.getTableName())) {
            //创建表
            Map<String, Object> maps = new HashMap<>();
            maps.put("databaseNames", databaseNames);
            maps.put("databaseFields", databaseFields);
            Integer i = templateMapper.createTable(maps);
        }
    }

    /**
     * @param tableName
     * @return java.lang.Long
     * @Author lvleigang
     * @Description 获取最大的排序
     * @Date 3:58 下午 2023/7/11
     **/
    private boolean checkTable(String tableName) {
        Map<String, String> maps = new HashMap<>();
        maps.put("tableName", tableName);
        Integer i = templateMapper.checkTable(maps);
        if (i != null && i > 0) {
            return true;
        }
        return false;
    }

    /**
     * @param entity
     * @param flag
     * @return java.util.List<com.hzya.frame.sys.databaseFields.entity.DatabaseFields>
     * @Author lvleigang
     * @Description 保存数据库表字段
     * @Date 10:10 上午 2023/8/17
     **/
    private List<DatabaseFields> saveDatabaseFields(TemplateDataDto entity, boolean flag) {
        //设置数据库表字段
        List<DatabaseFields> databaseFieldsList = new ArrayList<>();
        //设置id
        databaseFieldsList.add(createDataBaseField(entity.getServiceName(), entity.getTableName(), "id", "主键id", "1", "50", idOption, "1", "1", 1L));
        //明细表的时候添加主表id字段
        if (flag) {
            databaseFieldsList.add(createDataBaseField(entity.getServiceName(), entity.getTableName(), "formmain_id", "主表id", "1", "50", formmainOption, "1", "2", 2L));
        }
        //添加业务字段
        for (int i = 0; i < entity.getTemplateDataDetailDtoList().size(); i++) {
            TemplateDataDetailDto templateDataDetailDto = entity.getTemplateDataDetailDtoList().get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("maxlength", templateDataDetailDto.getFieldsLength());
            jsonObject.put("required", "1".equals(templateDataDetailDto.getFieldsRequired()) ? "true" : "false");
            jsonObject.put("title", templateDataDetailDto.getFieldsRemark());
            jsonObject.put("type", templateDataDetailDto.getFieldsType());
            jsonObject.put("id", templateDataDetailDto.getFieldsName());
            if (templateDataDetailDto.getFieldsOption() != null && templateDataDetailDto.getFieldsOption().size() > 0) {
                jsonObject.putAll(templateDataDetailDto.getFieldsOption());
            }
            databaseFieldsList.add(createDataBaseField(entity.getServiceName(), entity.getTableName(), templateDataDetailDto.getFieldsName(), templateDataDetailDto.getFieldsRemark(), templateDataDetailDto.getDataBaseType(), templateDataDetailDto.getFieldsLength(), jsonObject.toJSONString(), templateDataDetailDto.getFieldsRequired(), templateDataDetailDto.getFieldsSole(), databaseFieldsList.size() + 1));
        }
        //设置系统字段
        setSysFields(databaseFieldsList, entity.getServiceName(), entity.getTableName());

        //保存数据
        for (int i = 0; i < databaseFieldsList.size(); i++) {
            databaseFieldsMapper.entity_insert(databaseFieldsList.get(i));
        }
        return databaseFieldsList;
    }

    /**
     * @param databaseFieldsList
     * @param serviceName
     * @param tableName
     * @return void
     * @Author lvleigang
     * @Description 设置系统字段
     * @Date 10:59 上午 2023/8/17
     **/
    private void setSysFields(List<DatabaseFields> databaseFieldsList, String serviceName, String tableName) {

        //添加排序
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "sorts", "排序", "2", "20", sortsOption, "2", "2", databaseFieldsList.size() + 1));

        //添加创建人id
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "create_user_id", "创建人id", "1", "50", createUserIdOption, "1", "2", databaseFieldsList.size() + 1));

        //添加创建时间
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "create_time", "创建时间", "4", null, createTimeOption, "1", "2", databaseFieldsList.size() + 1));

        //添加修改人id
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "modify_user_id", "修改人id", "1", "50", modifyUserIdOption, "1", "2", databaseFieldsList.size() + 1));

        //添加修改时间
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "modify_time", "修改时间", "4", null, modifyTimeOption, "1", "2", databaseFieldsList.size() + 1));

        //添加sts
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "sts", "状态(Y正常N删除)", "1", "1", stsOption, "1", "2", databaseFieldsList.size() + 1));

        //添加org_id
        databaseFieldsList.add(createDataBaseField(serviceName, tableName, "org_id", "组织机构ID", "1", "50", orgOption, "2", "2", databaseFieldsList.size() + 1));

    }

    /**
     * @param serviceName    Service服务名
     * @param tableName      表名
     * @param fieldsName     字段名称
     * @param fieldsRemark   字段备注
     * @param fieldsType     类型
     * @param fieldsLength   长度
     * @param fieldsOption   属性
     * @param fieldsRequired 是否必填
     * @param fieldsSole     是否唯一性
     * @param sorts          排序
     * @return com.hzya.frame.sys.databaseFields.entity.DatabaseFields
     * @Author lvleigang
     * @Description
     * @Date 10:21 上午 2023/8/17
     **/
    private DatabaseFields createDataBaseField(String serviceName, String tableName, String fieldsName, String fieldsRemark, String fieldsType, String fieldsLength, String fieldsOption, String fieldsRequired, String fieldsSole, long sorts) {
        DatabaseFields databaseFields = new DatabaseFields();
        databaseFields.setCreate();
        databaseFields.setServiceName(serviceName);//Service服务名
        databaseFields.setTableName(tableName);//表名（英文名称）
        databaseFields.setFieldsName(fieldsName);//字段名称
        databaseFields.setFieldsRemark(fieldsRemark);//字段备注
        databaseFields.setFieldsType(fieldsType);//类型
        databaseFields.setFieldsLength(fieldsLength);//长度
        databaseFields.setFieldsOption(fieldsOption);//属性
        databaseFields.setFieldsRequired(fieldsRequired);//属性
        databaseFields.setFieldsSole(fieldsSole);//属性
        databaseFields.setSorts(sorts);//排序
        return databaseFields;
    }

    /**
     * @param entity
     * @return com.hzya.frame.sys.databaseNames.entity.DatabaseNames
     * @Author lvleigang
     * @Description 保存数据库表
     * @Date 10:08 上午 2023/8/17
     **/
    private DatabaseNames savaDatabaseNames(TemplateDataDto entity) {
        DatabaseNames databaseNames = new DatabaseNames();
        databaseNames.setCreate();
        databaseNames.setServiceName(entity.getServiceName());//Service服务名
        databaseNames.setTableName(entity.getTableName());//表名（英文名称）
        databaseNames.setTableRemark(entity.getTableRemark());//表名（中文名称）
        databaseNames.setRemark(entity.getTableRemark());//备注
        databasenamesMapper.entity_insert(databaseNames);
        return databaseNames;
    }

    /**
     * @param serviceName
     * @return boolean
     * @Author lvleigang
     * @Description 校验服务是否已经存在
     * @Date 3:57 下午 2023/8/16
     **/
    private boolean checkServiceName(String serviceName) {
        Template template = new Template();
        template.setServiceName(serviceName);// Service服务名
        template.setSts("Y");
        int count = templateMapper.entity_count(template);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param tableName
     * @return boolean
     * @Author lvleigang
     * @Description 校验表是否已经存在
     * @Date 3:57 下午 2023/8/16
     **/
    private boolean checkTableName(String tableName) {
        Template template = new Template();
        template.setTableName(tableName);
        template.setSts("Y");
        int count = templateMapper.entity_count(template);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }
}
