package com.cim.idm.mwmsextend.event.consumable;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.mwmsextend.generic.util.CommonValidation;
import com.cim.idm.wmsextend.generic.util.SMessageUtil;
import com.cim.idm.wmspackage.user.UserServiceProxy;
import com.cim.idm.wmspackage.user.management.data.UserInfo;
import com.cim.idm.wmspackage.user.management.data.UserInfoKey;
import com.cim.idm.wmspackage.user.management.impl.EncryptUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;

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

public class PortalUserCreateEvent {
	
	private static Log log = LogFactory.getLog(PortalUserCreateEvent.class);
	public void event(EventInfo eventInfo, Document message) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element body = root.getChild("Body");
		String sendSubjectName = root.getChild("Header").getChildText("ORIGINALSOURCESUBJECTNAME");
		
		String portalId = SMessageUtil.getElementValueByName(body, "ID");
		String clientID = SMessageUtil.getElementValueByName(body, "CLIENTID");
		String account = SMessageUtil.getElementValueByName(body, "ACCOUNT");
		String name = SMessageUtil.getElementValueByName(body, "NAME");
		String phone = SMessageUtil.getElementValueByName(body, "PHONE");
		String email = SMessageUtil.getElementValueByName(body, "EMAIL");
		String enabled = SMessageUtil.getElementValueByName(body, "ENABLED");
		String password = SMessageUtil.getElementValueByName(body, "PASSWORD");
		
		if (portalId != null && portalId != "") {
			String querySql = "SELECT PORTALID, USERID FROM USERINFO WHERE PORTALID = :PORTALID";
			Map<String, String> queryMap = new HashMap<>();
			queryMap.put("PORTALID", portalId);
			List<Map<String, Object>> userList = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySql, queryMap);
			if (!userList.isEmpty()) {
				throw new CustomException("PORTAL-10001",portalId,account);
			}
		}
		
		UserInfo userInfo = new UserInfo();
		UserInfoKey userInfoKey =new UserInfoKey();
		
		userInfoKey.setUserId(account);
		userInfo.setKey(userInfoKey);
		userInfo.setUserName(name);
		userInfo.setSiteName("B20");
		userInfo.setPassword(EncryptUtil.encrypt(password));
		userInfo.setEmail(email == null ? "" : email);
		userInfo.setPhoneNumber(phone == null ? "" : phone);
		userInfo.setPortalId(portalId);
		
		UserServiceProxy.getUserInfoService().insert(userInfo);
	}
	
}

