package cn.stylefeng.team.form.modular.manage.factory;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.team.form.api.entity.FormDefinition;
import cn.stylefeng.team.form.api.entity.FormModel;
import cn.stylefeng.team.form.api.pojo.FormDesignVo;
import cn.stylefeng.team.form.modular.manage.service.FormDefinitionService;
import cn.stylefeng.team.project.api.util.Version;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

public class FormDefinitionFactory {

    public static FormDefinition initDefinition(FormModel formModel) {

        FormDefinition definition = new FormDefinition();

        definition.setFormDefinitionId(IdWorker.getId());

        definition.setBusinessCategoryId(formModel.getBusinessCategoryId());
        definition.setBusinessId(formModel.getBusinessId());
        definition.setFormModelId(formModel.getFormModelId());

        definition.setFldVersion(new Version().toString());

        FormDefinitionService formDefinitionService = SpringUtil.getBean(FormDefinitionService.class);
        formDefinitionService.save(definition);

        return definition;
    }

    public static FormDefinition upgradeDefinition(FormDefinition oldFormDefinition, FormDesignVo newFormConfig) {

        FormDefinition metaDefinition = new FormDefinition();
        BeanUtil.copyProperties(oldFormDefinition, metaDefinition);

        metaDefinition.setFormDefinitionId(IdWorker.getId());

        Version version = new Version(oldFormDefinition.getFldVersion());
        version.upgrade();
        metaDefinition.setFldVersion(version.toString());

        metaDefinition.setFormConfig(newFormConfig);

        return metaDefinition;
    }

}
