package net.wicp.tams.app.duckula.controller.service.cas.impl;

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

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.bean.constant.UnitType;
import net.wicp.tams.app.duckula.controller.bean.models.SysOrg;
import net.wicp.tams.app.duckula.controller.bean.models.SysOrgExample;
import net.wicp.tams.app.duckula.controller.dao.SysOrgMapper;
import net.wicp.tams.app.duckula.controller.service.cas.IOrgService;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.json.EasyUiAssist;
import net.wicp.tams.common.apiext.json.easyuibean.EasyUINode;
import net.wicp.tams.common.apiext.json.easyuibean.EasyUINodeConf;
import net.wicp.tams.common.callback.IConvertValue;

@Service
@Slf4j
public class OrgService implements IOrgService {
	@Autowired
	private SysOrgMapper sysOrgMapper;

	@Override
	public String createOrgTree(IConvertValue i18nConvert) {
		List<SysOrg> orglist = sysOrgMapper.selectByExample(new SysOrgExample());
		if (CollectionUtils.isNotEmpty(orglist)) {
			EasyUINodeConf conf = new EasyUINodeConf("id", "orgName", "parentId");
			conf.setTextConvert(i18nConvert);
			// conf.setIconClsCol(":icon-dept");//设置节点图标为 部门
			conf.setAttrCols("unitType", "orgIdPath");
			try {
				List<EasyUINode> roots = EasyUiAssist.getTreeRoot(orglist, conf);
				if (CollectionUtils.isNotEmpty(roots)) {
					Map<String, EasyUINode> nodes = roots.get(0).getSubs();// 因为只有一根根节点
					roots.get(0).setIconCls("icon-org");// 设置根节点为 机构的图标
					for (String nodeId : nodes.keySet()) {
						EasyUINode node = nodes.get(nodeId);
						UnitType unitType = UnitType.findByName(node.getAttribute("unitType"));
						switch (unitType) {
						case ORG:
							node.setIconCls("icon-org");
							break;
						case DEPT:
							node.setIconCls("icon-dept");
							break;
						default:
							break;
						}
					}
				}
				String retstr = EasyUiAssist.getTreeFromList(roots);
				return retstr;
			} catch (Exception e) {
				log.error("构造组织树出错", e);
			}
		}
		return "[]";
	}

	@Override
	public Result delOrg(Integer orgid) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<SysOrg> findAncestOrg(long orgid) {
		// TODO Auto-generated method stub
		return null;
	}

}
