package net.wicp.tams.duckula.ops.pages.cas;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.TextStreamResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
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.dao.SysOrgMapper;
import net.wicp.tams.app.duckula.controller.service.cas.impl.OrgService;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.UUIDGenerator;
import net.wicp.tams.common.apiext.json.EasyUiAssist;
import net.wicp.tams.common.apiext.json.JSONUtil;
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;
import net.wicp.tams.component.SymbolConstantsCus;
import net.wicp.tams.component.tools.TapestryAssist;
import net.wicp.tams.duckula.ops.pages.ParentPageBean;

@Import(stack = "easyuistack")
public class OrgManager extends ParentPageBean<SysOrg> {

	@Inject
	private SysOrgMapper sysOrgMapper;

	@Inject
	private OrgService orgService;

	@Property
	private boolean isEmptyOrg;

	@Property
	private String orgTree;

	public String getOrgData() throws Exception {
		// List<SysOrg> selectList = new ArrayList<SysOrg>();
		List<SysOrg> selectList = sysOrgMapper.selectList(new QueryWrapper<SysOrg>());
		EasyUINodeConf conf = new EasyUINodeConf("id", "orgName", "parentId");
		conf.setFieldCols("orgIdPath", "orgCode");
		List<EasyUINode> treeRoot = EasyUiAssist.getTreeRoot(selectList, conf);
		String retstr = EasyUiAssist.getTreeFromList(treeRoot);
		return retstr;
		// EasyUiAssist.getJsonForTreeGridAlias(fromList, easyUINodeConf, recordNum);
	}

	/***
	 * 创建公司
	 * 
	 * @param rootName
	 * @return
	 */
	@OnEvent(SymbolConstantsCus.EVENT_SELTREEGRID_CREATEROOT)
	private Result createRoot(String rootName) {
		SysOrg saveobj = new SysOrg();
		saveobj.setOrgName(rootName);
		String code = "com-" + UUIDGenerator.getUniqueLong();
		saveobj.setOrgCode(code);
		saveobj.setOrgIdPath("/" + code);
		saveobj.setUnitType(UnitType.ORG.name());
		sysOrgMapper.insert(saveobj);
		return Result.getSuc();
	}

	public TextStreamResponse onCreateRoot() {
		String orgName = request.getParameter("orgName");
		if (StringUtils.isEmpty(orgName)) {
			return retErrorInfo("没有指定机构/公司名称");
		}
		SysOrg org = new SysOrg();
		org.setOrgName(orgName);
		org.setAddress("");
		org.setUnitType(UnitType.ORG.name());
		sysOrgMapper.insert(org);
		String code = "com-" + UUIDGenerator.getUniqueLong();
		org.setOrgCode(code);
		org.setOrgIdPath("/" + org.getId());
		sysOrgMapper.updateById(org);
		return retSuccInfo();
	}

	public TextStreamResponse onSaveUnit() {
		String unitTypeStr = request.getParameter("unitType");
		String unitName = request.getParameter("unitName");
		long parentId = Long.parseLong(request.getParameter("parentId"));
		String address = request.getParameter("address");
		if (StringUtils.isEmpty(unitTypeStr)) {
			return retErrorInfo("没有此组织类型");
		}
		Result retobj = Result.getSuc();
		JSONObject json = retobj.retJsonObj();
		JSONObject retnode = new JSONObject();
		UnitType unitType = UnitType.findByName(unitTypeStr);
		SysOrg parentorg = sysOrgMapper.selectById(parentId);
		switch (unitType) {
		case ORG:
		case DEPT:
			SysOrg saveobj = new SysOrg();
			saveobj.setOrgName(unitName);
			saveobj.setUnitType(unitType.name());
			saveobj.setAddress(address);
			saveobj.setParentId(parentId);
			saveobj.setOrgIdPath(parentorg.getOrgIdPath());
			sysOrgMapper.insert(saveobj);
			saveobj.setOrgIdPath(saveobj.getOrgIdPath() + "," + saveobj.getId());
			sysOrgMapper.updateByPrimaryKeySelective(saveobj);
			retnode.put("id", saveobj.getId());
			retnode.put("text", saveobj.getOrgName());
			retnode.put("iconCls", unitType.getIcon());
			retnode.put("attributes",
					JSONUtil.packParams("unitType", unitType.name(), "orgPath", saveobj.getOrgIdPath()));
			break;
		case GROUP:
			/*
			 * CaGroup group = new CaGroup(); group.setGroupName(unitName);
			 * group.setCaOrganization(parentorg); session.save(group); retnode.put("id",
			 * group.getId()); retnode.put("text", group.getGroupName());
			 * retnode.put("iconCls", unitType.getIcon()); retnode.put("attributes", new
			 * JSONObject("unitType", unitType.name()));
			 */
			break;
		default:
			break;
		}
		json.put("retnode", retnode);
		return retStream(json.toJSONString());
	}

	public TextStreamResponse onDelUnit() {
		String orgId = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			return retErrorInfo("需要参数:组织ID");
		}
		sysOrgMapper.deleteById(Long.parseLong(orgId));
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	@SetupRender
	void init() {
		orgTree = orgService.createOrgTree(new IConvertValue<Object>() {
			@Override
			public String getStr(Object obj) {
				SysOrg org = (SysOrg) obj;
				String key = org.getOrgName();
				if (StringUtil.isNull(key) || !messages.contains(key)) {
					return key;
				}
				return messages.get(key);
			}
		});
		isEmptyOrg = StringUtils.isEmpty(orgTree) || "[]".equals(orgTree);
	}

	@Override
	public void doSave(SysOrg t, boolean isInsert) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doDel(String id) {
		// TODO Auto-generated method stub

	}

	@Override
	public BaseMapper<SysOrg> getBaseMapper() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void packageQuery(SysOrg t, QueryWrapper<SysOrg> queryWrapper) {
		// TODO Auto-generated method stub

	}
}
