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

import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.system.bpm.web.common.BpmConst;
import cc.smtweb.system.bpm.web.sys.user.dataRightGroup.IDataRightTreeWorker;
import cc.smtweb.system.bpm.web.sys.user.dept.Dept;
import cc.smtweb.system.bpm.web.sys.user.dept.DeptCache;
import cc.smtweb.system.bpm.web.sys.user.party.Party;
import cc.smtweb.system.bpm.web.sys.user.party.PartyCache;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author yaoq
 * @Date 2022年09月22日 15:48
 * @Description
 */
public class DeptDataRightTreeWork implements IDataRightTreeWorker {

    @Override
    public SwMap buildExtraValue(long key, String value) {
        SwMap swMap = new SwMap();
        swMap.put("id", key);
        swMap.put("text", value);
        return swMap;
    }

    @Override
    public List<SwMap> getExtraValues() {
        List<SwMap> list = new ArrayList<>();
        list.add(buildExtraValue(BpmConst.DataRight.ALL_DEPT, "所有部门"));
        list.add(buildExtraValue(BpmConst.DataRight.CUR_VALUE, "所属部门"));
        Set<Party> partys = filterParty(PartyCache.getInstance().getTopSet());
        if (CommUtil.isEmpty(partys)) return list;
        partys.forEach(party -> {
            list.add(buildExtraValue(party.getId(), party.getName()));
        });
        return list;
    }

    @Override
    public List<SwMap> getChildren(long id) {
        List<SwMap> list = new ArrayList<>();
        if (id <= 0) {
            list.addAll(getExtraValues());
            return list;
        }
        Set<Dept> depts = DeptCache.getInstance().getByP(String.valueOf(id));
        if (!CommUtil.isEmpty(depts)) {
            depts.forEach(dept -> {
                list.add(buildExtraValue(dept.getId(), dept.getName()));
            });
        }
        Set<Party> partys = filterParty(PartyCache.getInstance().getChildren(id));
        if (CommUtil.isEmpty(partys)) return list;
        partys.forEach(party -> {
            list.add(buildExtraValue(party.getId(), party.getName()));
        });
        return list;
    }

    private Set<Party> filterParty(Set<Party> partySet) {
        if (CommUtil.isEmpty(partySet)) return partySet;
        return partySet.stream().filter((party) ->
                !CommUtil.isEmpty(DeptCache.getInstance().getAllByPartyEx(party.getId()))).collect(Collectors.toSet());
    }

    @Override
    public String getText(long value) {
        if (BpmConst.DataRight.CUR_VALUE == value) return "所属部门";
        if (BpmConst.DataRight.ALL_DEPT == value) return "所有部门";
        return PartyCache.getInstance().getNameById(value);
    }
}
