package cc.smtweb.system.bpm.web.design.db;

import cc.smtweb.framework.core.annotation.SwBody;
import cc.smtweb.framework.core.annotation.SwService;
import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.cache.ModelTableCache;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.mvc.service.*;
import cc.smtweb.framework.core.session.UserSession;
import cc.smtweb.system.bpm.web.design.form.CodeBuildHandler;

/**
 * Created by Akmm at 2022/3/22 9:12
 */
@SwService
public class ModelTableService extends AbstractCompService {
    @Override
    protected AbstractHandler createHandler(String type) {
        switch (type) {
            case TYPE_LOAD:
                return new DefaultLoadHandler<ModelTable>(ModelTable.ENTITY_NAME);
            case TYPE_SAVE:
                return new ModelTableSaveHanlder();
            case TYPE_DEL:
                return new DefaultDelHandler<ModelTable>(ModelTable.ENTITY_NAME);
            case TYPE_LIST:
                return new DefaultListHandler<ModelTable>(ModelTable.ENTITY_NAME);
            case TYPE_COMBO:
                return new ModelTableComboHandler();

        }
        return null;
    }

    //获取表的字段列表
    public R loadFields(@SwBody SwMap params, UserSession us) {
        try {
            final long tableId = params.readLong("tableId");
            ModelTable table = ModelTableCache.getInstance().get(tableId);
            if (table == null) return R.error("没有找到对应的表定义信息【" + tableId + "】！");

            return R.success(SwListData.create(table.getFields(), 0));
        } catch (Exception e) {
            return R.error("操作失败！", e);
        }
    }

    //生成bean
    public R buildBean(@SwBody SwMap params, UserSession us) {
        CodeBuildHandler handler = new CodeBuildHandler();
        if (params == null) params = new SwMap();
        if (us == null) us = UserSession.createSys();
        handler.init(params, us);
        try {
            return handler.buildBeanByTable();
        } catch (Exception e) {
            return R.error("操作失败！", e);
        }
    }
}
