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.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 PortalUserUpdateEvent {
	
	private static Log log = LogFactory.getLog(PortalUserUpdateEvent.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 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");
		
		CommonValidation.checkNotNull("ID", portalId);
		
		String findSql = "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(findSql, queryMap);
		if(userList.isEmpty()) {
			throw new CustomException("PORTAL-10002",portalId);
		}
		
		String updateSql = "UPDATE USERINFO SET  PORTALID = :PORTALID,USERNAME =:USERNAME,PASSWORD = :PASSWORD,PHONENUMBER =:PHONE,EMAIL =:EMAIL WHERE USERID=:USERID";
		Map<String, String> bindMap = new HashMap<>();
		bindMap.put("PORTALID", portalId);
		bindMap.put("USERNAME", name);
		bindMap.put("PHONE", phone);
		bindMap.put("EMAIL", email);
		bindMap.put("PASSWORD", EncryptUtil.encrypt(password));
		bindMap.put("USERID", userList.get(0).get("USERID").toString());
		
		log.info("cim portal modify user:"+userList.get(0).get("USERID").toString());
		IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
	}
	
}

