package cc.smtweb.system.bpm.web.sys.user.dataRightGroup;

import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.framework.core.util.JsonUtil;
import cc.smtweb.system.bpm.web.design.form.define.PageDataset;
import cc.smtweb.system.bpm.web.engine.dynPage.DynPageLoadHandler;
import cc.smtweb.system.bpm.web.engine.dynPage.DynPageSaveHandler;
import cc.smtweb.system.bpm.web.engine.dynPage.DynPageTreeHandler;
import cc.smtweb.system.bpm.web.sys.user.dataRight.DataRightDefine;
import cc.smtweb.system.bpm.web.sys.user.dataRight.DataRightDefineCache;

import java.util.List;
import java.util.Map;

/**
 * @Author: tanghp
 * @Date: 2022-08-01 17:47
 * @Desc:
 */
public class DataRightGroupHandler {
    private final static String drgValueTree = "drgValueTree";

    static class DrgSaveHandler extends DynPageSaveHandler {

        @Override
        protected DefaultEntity readBeanFromPage(PageDataset pageDataSet, SwMap data) {
            DataRightGroup bean = (DataRightGroup) super.readBeanFromPage(pageDataSet, data);
            bean.setContent(JsonUtil.encodeString(data.readListMap("sdrg_content")));
            return bean;
        }
    }

    static class DrgLoadHandle extends DynPageLoadHandler {

        @Override
        public DynPageTreeHandler getTreeWorker(SwMap filter, PageDataset pageDataSet) {
            if (pageDataSet.name.equals("drgValueTree")) {
                return new DrgValueTreeHandler(form.getId(), filter, pageDataSet);
            }
            return super.getTreeWorker(filter, pageDataSet);
        }

        @Override
        protected void afterLoadBean(PageDataset dataset, SwMap bean) {
            super.afterLoadBean(dataset, bean);
            bean.put("sdrg_content", JsonUtil.parseList(bean.readString("sdrg_content"), Map.class));
        }
    }

    static class DrgValueTreeHandler extends DynPageTreeHandler {

        public DrgValueTreeHandler(long pageId, SwMap filter, PageDataset pageDataSet) {
            super(pageId, filter, pageDataSet);
        }

        @Override
        protected List<SwMap> getChildren(long id) {
            DataRightDefine define = DataRightDefineCache.getInstance().get(filter.readLong("type"));
            if (define == null) return null;
            IDataRightTreeWorker worker;
            try {
                worker = IDataRightTreeFactory.getInstance().getWork(define.getCode());
            } catch (Exception e) {
                throw new SwException(e);
            }
            return worker.getChildren(id);
        }

        @Override
        protected long getId(SwMap bean) {
            return bean.readLong("id");
        }

        @Override
        protected String getText(SwMap bean) {
            return bean.readString("text");
        }
    }
}
