package com.awspaas.user.apps.donenow_crm.event;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.BOQueryAPI;
import com.actionsoft.sdk.service.model.UserModel;
import com.alibaba.fastjson.JSON;
import com.alipay.remoting.util.StringUtils;
import com.awspaas.user.apps.donenow_crm.constant.CrmConstant;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.List;


public class ContactFormAfterSaveEvent
		extends ExecuteListener
{
	public String getDescription() {
		return "表单保存后事件";
	}

	public String getProvider() {
		return "上海声联";
	}

	public String getVersion() {
		return "1.0";
	}

	public void execute(ProcessExecutionContext process) throws Exception {
		UserContext uc = process.getUserContext();
		String boName = process.getParameterOfString("$BONAME");
		System.out.println("单位boName:" + boName);
		BO contactBo = process.getFormData();
		saveContactData(uc,contactBo,boName,true);

	}

	public String saveContactData(UserContext uc,BO contactBo,String boName,boolean type) {
		String roleNO = "roledn_customer";
		String deptId = DBSql.getString("SELECT ID FROM ORGDEPARTMENT WHERE EXT1=?", new Object[] { contactBo.getString("ACCOUNT_ID")});

		if (contactBo != null&&CrmConstant.BO_EU_DNCRM_CONTACT.equals(boName)&&StringUtils.isNotBlank(deptId)) {
			String roleId = DBSql.getString("SELECT ID from orgrole where roleno='"+roleNO+"'");
			if (StringUtils.isBlank(roleId)) {
				System.out.println("roleModel为空:");
				return "";
			}
			String sql="SELECT * FROM ORGUSER WHERE EXT5='"+contactBo.getId()+"'";
			RowMap map = DBSql.getMap(sql);
			System.out.println("userMap:" +JSON.toJSONString(map));
			System.out.println("userMap:" + (map == null));

			//用户表中是否已经存在该人
			if (map != null) {
				System.out.println("用户更新:");
				//说明联系人姓名没有修改过
				if(contactBo.getString("NAME").equals(map.getString("USERNAME"))) {
					SDK.getORGAPI().updateUser(map.getString("USERID"), contactBo.getString("NAME"), "", contactBo.getString("EMAIL"), contactBo.getString("MOBILE_PHONE"), "", "", "", "", contactBo.getId());
				}
				//联系人姓名修改过了，要修改USERID
				else {
					String userId=getPinYinUserId(contactBo.getString("NAME"));
					DBSql.update("UPDATE ORGUSER SET USERID='"+userId+"' WHERE EXT5='"+contactBo.getId()+"'");
					UserCache.getCache().reload();
					SDK.getORGAPI().updateUser(userId, contactBo.getString("NAME"), "", contactBo.getString("EMAIL"), contactBo.getString("MOBILE_PHONE"), "", "", "", "", contactBo.getId());

					//更新联系表的USERID字段
					contactBo.set("USERID", userId);
					SDK.getBOAPI().update(CrmConstant.BO_EU_DNCRM_CONTACT, contactBo);
				}

			} else {
				System.out.println("用户新增");
				String pinYinUserId = getPinYinUserId(contactBo.getString("NAME"));
				SDK.getORGAPI().createUser(deptId, pinYinUserId, contactBo.getString("NAME"), roleId, "", "", false, contactBo.getString("EMAIL"), contactBo.getString("MOBILE_PHONE"), "", "", "", "", contactBo.getId());
				////更新联系表的USERID字段
				contactBo.set("USERID", pinYinUserId);
				SDK.getBOAPI().update(CrmConstant.BO_EU_DNCRM_CONTACT, contactBo);
			}

		}
		//主联系人保存需要往客户表同步联系人数据
		if(type&&"1".equals(contactBo.getString("IS_PRIMARY_CONTACT"))) {
			BO accoutnBo = SDK.getBOAPI().query(CrmConstant.BO_EU_DNCRM_ACCOUNT).detailById(contactBo.getString("ACCOUNT_ID"));
			if(null!=accoutnBo) {
				accoutnBo.set("CONTACT_NAME", contactBo.get("NAME"));
				accoutnBo.set("CONTACT_SUFFIX_ID", contactBo.get("SUFFIX_ID"));
				accoutnBo.set("CONTACT_TITLE", contactBo.get("TITLE"));
				accoutnBo.set("CONTACT_EMAIL", contactBo.get("EMAIL"));
				accoutnBo.set("PHONE", contactBo.get("MOBILE_PHONE"));
				accoutnBo.set("ALTERNATE_PHONE1", contactBo.get("PHONE"));
				SDK.getBOAPI().update(CrmConstant.BO_EU_DNCRM_ACCOUNT, accoutnBo);
			}
		}
		return "";
	}
	public String getPinYinUserId(String userName) {
		HanyuPinyinOutputFormat hanyuPinyinOutputFormat=new HanyuPinyinOutputFormat();
		String  tempStr="C-";
		try {
			String value =  PinyinHelper.toHanyuPinyinString(userName, hanyuPinyinOutputFormat, "").replaceAll("\\d+", "");
			if(StringUtils.isNotBlank(value)) {
				tempStr+= value.replaceAll("\\s", "");
			}else {
				tempStr+= userName.replaceAll("\\s", "");
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Integer count = DBSql.getInt("SELECT COUNT(1) FROM ORGUSER WHERE USERID LIKE CONCAT(?,'%')", new Object[] {tempStr});
		if(count>0) {
			return tempStr+(count+1);
		}else {
			return tempStr;
		}

	}
}
