package cn.stylefeng.team.meta.modular.factory;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.team.meta.api.entity.MetaDefinition;
import cn.stylefeng.team.meta.api.entity.MetaModel;
import cn.stylefeng.team.meta.api.enums.MetaModelTypeEnum;
import cn.stylefeng.team.meta.modular.enums.MetaModelExceptionEnum;
import cn.stylefeng.team.meta.modular.pojo.request.MetaModelRequest;
import cn.stylefeng.team.meta.modular.service.MetaDefinitionService;
import cn.stylefeng.team.meta.modular.service.MetaModelService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

public class MetaModelFactory {

    public static MetaDefinition commonAddModel(MetaModelRequest metaModelRequest) {

        MetaModelFactory.validateNewModelType(metaModelRequest);

        MetaModel metaModel = new MetaModel();

        BeanUtil.copyProperties(metaModelRequest, metaModel);

        metaModel.setMetaModelId(IdWorker.getId());

        MetaDefinition pointDefinition = null;
        if (MetaModelTypeEnum.NEW_MODEL.getCode().equals(metaModelRequest.getMetaModelType())) {

            MetaDefinition metaDefinition = ModelDefinitionFactory.initDefinition(metaModel);

            metaModel.setCurrentVersion(metaDefinition.getFldVersion());
            metaModel.setCurrentDefinitionId(metaDefinition.getMetaDefinitionId());
            pointDefinition = metaDefinition;
        } else {

            MetaDefinitionService metaDefinitionService = SpringUtil.getBean(MetaDefinitionService.class);
            pointDefinition = metaDefinitionService.findModelNewestDefinition(metaModelRequest.getLinkModelId());
        }

        MetaModelService metaModelService = SpringUtil.getBean(MetaModelService.class);
        metaModelService.save(metaModel);

        return pointDefinition;
    }

    private static void validateNewModelType(MetaModelRequest metaModelRequest) {

        if (metaModelRequest.getMetaModelType() == null) {
            metaModelRequest.setMetaModelType(MetaModelTypeEnum.NEW_MODEL.getCode());
        }

        if (MetaModelTypeEnum.OUT_MODEL.getCode().equals(metaModelRequest.getMetaModelType())) {
            if (metaModelRequest.getLinkModelId() == null) {
                throw new ServiceException(MetaModelExceptionEnum.NEED_OUT_TABLE);
            }
        }

    }

}
