package com.gx.obe.management.thread;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.utils.MessageCallBack;
import org.eclipse.swt.graphics.Image;

import com.gx.obe.WebserviceConstants;
import com.gx.obe.business.enumeration.ExpertEnum;
import com.gx.obe.business.enumeration.UserEnum;
import com.gx.obe.business.http.HttpResponse;
import com.gx.obe.business.http.HttpUrl;
import com.gx.obe.business.http.HttpUtils;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.http.util.Base64;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.MD5Utils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.SpellHelper;
import com.gx.obe.util.utils.StringUtil;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.web.entity.auth.AuthUser;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.UserRoleService;
import com.gx.obe.web.service.UserService;
import com.gx.obe.web.service.expert.ExpertService;
import com.gx.utils.ActionLogUtils;
import com.gx.utils.NowTimeUtils;
import com.swtdesigner.ResourceManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @Description: 下载评标专家线程
 * @author guoyr
 */
public class DownloadExpertThread extends Thread {
	private UserService userService ;
	private UserRoleService userRoleService;
	private ExpertService expertService;
	private CallBack callBack;
	private TenderProjectEntity tenderProjectEntity;
	private Image defaultAvatorImage = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/idCard.png");// 默认头像
	private MessageCallBack messageCallBack;;
	private List<Expert> expertList = new ArrayList<Expert>();
	
	public DownloadExpertThread(TenderProjectEntity tenderProjectEntity, String webserviceAddress, CallBack callBack) {
		this.callBack = callBack;
		this.tenderProjectEntity = tenderProjectEntity;
		messageCallBack = new MessageCallBack(callBack);
		userRoleService = new UserRoleService();
		expertService = new ExpertService();
	}
	
	@Override
	public void run() {
		
		String method = PropertiesUtils.getWebserviceProperty(WebserviceConstants.DOWNLOAD_EXPERT_INFO, "tenderProjectInfoHS.do?getExpertList");
		HttpUrl httpUrl = HttpUtils.getProjectHttpUrl(tenderProjectEntity, method);
		httpUrl.setAttribute("PhaseType",  tenderProjectEntity.getPhaseType());
		boolean flag = false;
		messageCallBack.callBackMsg(MessageFormat.format(Messages.Tips_downloadingAndWaitFormat, Messages.EvalExpert));
		flag = resolveXml(tenderProjectEntity, tenderProjectEntity, HttpUtils.doPost(httpUrl));
		ActionLogUtils.addServerLog(tenderProjectEntity.getId(), "下载专家", httpUrl, flag);
		
		messageCallBack.callBackMsg("\r\n");
		
		//只有中电建才需要
//		DownloadWorkersThread downloadWorkersThread = new DownloadWorkersThread(tenderProjectEntity, callBack);
//		downloadWorkersThread.start();
//		downloadWorkersThread.join();
		
		messageCallBack.callBackMsg(MessageFormat.format(Messages.Tips_downloadFinishedFormat, Messages.EvalExpert));
		if(null != callBack){
			callBack.after();
		}
	}
	
	/**
	 * @Description: 解析返回的xml
	 * @author guoyr
	 * @param xmlStr
	 * @return
	 */
	private boolean resolveXml(TenderProjectEntity tenderProjectEntity, TenderProjectEntity childProject, HttpResponse httpResponse){
		boolean flag = false;
		if(null == httpResponse || !httpResponse.getStatus()) {
			return false;
		}
		
		List<Expert> oldExpertList = expertService.getExpertByTenderId(tenderProjectEntity.getId());
		Map<String,Expert> oldExpertMap = new HashMap<String,Expert>();
		if(null != oldExpertList && oldExpertList.size() > 0) {
			for(Expert expert : oldExpertList) {
				oldExpertMap.put(expert.getUser().getUserAccount(), expert);
			}
		}
		
		JSONArray supplierListArray = httpResponse.getDataJSONArray("expertList");
		if(null != supplierListArray){
			Object[] supplierJsonList =  supplierListArray.toArray();
			
			if(null != supplierJsonList && supplierJsonList.length > 0){
				for(Object object : supplierJsonList){
					JSONObject expertJson = (JSONObject)object;
					AuthUser user = new AuthUser();
					user.setUserAccount((String)expertJson.get("account"));
					user.setSpecialty((String)expertJson.get("specialty"));
					user.setGender((String)expertJson.get("gender"));
					user.setUserName((String)expertJson.get("userName"));
					user.setUserIdcard((String)expertJson.get("idCard"));
					user.setPhone((String)expertJson.get("phone"));
					user.setProfessionalTitle((String)expertJson.get("professionalTitle"));
					if(null != expertJson.get("passWord") && !"".equals(expertJson.get("passWord"))){
						user.setUserPassword((String)expertJson.get("passWord"));
					}else{
						user.setUserPassword(MD5Utils.getMD5String(PropertiesUtils.getProperty(ConfigConstants.EXPERT_DEFAULT_PASSWORD, "123456")));
					}
					
					user.setCompany((String)expertJson.get("company"));
					Expert expert = new Expert();
					expert.setUser(user);
					if(null != expertJson.get("isLeader") && "01".equals(expertJson.get("isLeader"))){
						expert.setIsLeader(ExpertEnum.LEADER_YES);
					}
					if(null != expertJson.get("expertType") && "01".equals(expertJson.get("expertType"))){
						expert.setExpertType(ExpertEnum.BIDDING);
					}
//					expert.setExpertType(ExpertEnum.EXPERT);
					String type = ObjectUtils.getObjString(expertJson.get("type"));
					int busType = type.contains("01") ? ExpertEnum.EXPERT_BUS : 0;
					int tecType = type.contains("02") ? ExpertEnum.EXPERT_TEC : 0;
					int priceType = type.contains("03") ? ExpertEnum.EXPERT_PRICE : 0;
					expert.setEvalBidType(busType | tecType | priceType);
					setExpertMessgae(expert);
					
					if(null != oldExpertMap.get((String)expertJson.get("account"))) {
						oldExpertMap.remove((String)expertJson.get("account"));
					}
				}
				
			}else {
				flag = true;
				return flag;
			}
		}
		
//		 Iterator<Entry<String, Expert>> it = oldExpertMap.entrySet().iterator();
//		 while(it.hasNext()){
//			 Entry<String, Expert> entry = it.next();
//			 expertService.deleteById(entry.getValue().getId());
//		  }
		
		if(null != expertList && expertList.size() > 0){
			// 批量保存或修改
			if(expertService.batchSaveOrUpdate(expertList)){
				flag = true;
				messageCallBack.callBackMsg(Messages.Tips_downloaded+expertList.size() +"位"+Messages.EvalExpert+"！");
			}else {
				messageCallBack.callBackMsg(false, Messages.Tips_expertDownloadFailed);
			}
		}else{
			messageCallBack.callBackMsg(false, Messages.Tips_notFoundDownloadableExpert);
		}
		return flag;
	}
	
	/**
	 * @Description: 设置专家信息
	 * @author guoyr
	 * @param member
	 * @param expertList 
	 */
	private void setExpertMessgae(Expert member){
		AuthUser user = createUserAndAuthRole(member);
		if(null != user){
			// 根据项目ID和用户ID查询专家信息。
			Expert tempExpert = expertService.getExpert(tenderProjectEntity.getId(), user.getId());
			if(null == tempExpert){// 添加专家信息
				messageCallBack.callBackMsg(true,  MessageFormat.format(Messages.Tips_downloadingFormat, null != member && null != member.getUser() ? member.getUser().getUserName() : ""));
				tempExpert = null != member ? member : new Expert();
				tempExpert.setCreateTime(NowTimeUtils.getNowDate());
				tempExpert.setCreateUserId(Constants.USER.getId());
				if(StringUtil.empty(tempExpert.getIsLeader())){
					tempExpert.setIsLeader(ExpertEnum.LEADER_NO);
				}
			}else{// 修改专家信息
				messageCallBack.callBackMsg(true,  MessageFormat.format(Messages.Tips_updatingFormat, null != member && null != member.getUser() ? member.getUser().getUserName() : ""));
//				messageCallBack.callBackMsg(true, Messages.Tips_hasBeenUpdated + Messages.Expert+"["+(null != member && null != member.getUser() ? member.getUser().getUserName() : "")+"]。");
				tempExpert.setIsLeader(member.getIsLeader());
				tempExpert.setExpertType(member.getExpertType());
			}
			tempExpert.setProjectId(null != tenderProjectEntity.getParentId() ? tenderProjectEntity.getParentId() : tenderProjectEntity.getId());
			tempExpert.setTenderId(tenderProjectEntity.getId());
//			tempExpert.setSignType(null);
			tempExpert.setUser(user);
			tempExpert.setUserId(user.getId());
			expertList.add(tempExpert);
		}else {
			messageCallBack.callBackMsg(false,  MessageFormat.format(Messages.Tips_downloadFailFormat, "["+(null != member && null != member.getUser() ? member.getUser().getUserName() : "")+"]"));
		}
	}
	
	/**
	 * @Description: 创建用户并为用户分配角色
	 * @author guoyr
	 * @param evalExpert
	 * @return
	 */
	private AuthUser createUserAndAuthRole(Expert evalExpert){
		if(null != evalExpert){
			AuthUser user = null != evalExpert.getUser() ? evalExpert.getUser() : new AuthUser();
//			String account = "";// 专家账号
			// 如果没有专家名称，则随机生成。否则根据专家名称转为拼音作为账号。
//			if(null == user.getUserName()){
//				int maxValue = expertService.getMaxExpertAccountName();
////				account = "zj" + (maxValue+1);
//			}else{
//				// 如果用户名为中文可转为英文账号，否则转为""。
//				account = SpellHelper.getEname(user.getUserName());
//				account = StringUtils.isNotEmpty(account) ? account : user.getUserName();
//			}
			if(StringUtil.empty(user.getUserAccount())){
				user.setUserAccount(SpellHelper.getEname(user.getUserName()));
			}
			if(null == userService){
				userService = new UserService();
			}
			// 根据帐号查询用户信息。
			AuthUser tempUser = userService.getUserByIdOrAccont(user.getUserAccount(), user.getUserIdcard());
			 
			if(null == tempUser){// 添加用户信息
				//如果发现用户没有密码，默认密码是1
				if(StringUtil.empty(user.getUserPassword())){
					user.setUserPassword(MD5Utils.getMD5String(PropertiesUtils.getProperty(ConfigConstants.EXPERT_DEFAULT_PASSWORD, "1")));// 密码(MD5加密)
				}
				user.setId(UuidUtils.getUUID());
				user.setGender(UserEnum.MALE);
				user.setUserType(UserEnum.EXPERT);
				user.setCreateTime(NowTimeUtils.getNowDate());
				user.setUseStatus(CommonEnum.REAL_STATUS);
				user.setAvatar(Base64.encode(ImageResolver.getImageBytes(defaultAvatorImage)));// 默认头像
				user.setSource(UserEnum.USER_SOURCE_REMOTE);
				if(userService.createUserInfo(user) == null)return null;
				//则默认为专家分配专家角色
				userRoleService.createUserRole(user.getId(), new String[]{UserEnum.ROLE_TYPE_EXPERT});
			}else{// 修改用户信息
				user.setId(tempUser.getId());
				userService.updateAssignProperty(user, new String[]{"userName", "userPassword", "professionalTitle", "userIdcard", "phone", "specialty", "company"});
				userRoleService.initUserRole(user.getId(), UserEnum.ROLE_TYPE_EXPERT);
			}
			return user;
		}
		return null;
	}
	
}
