package com.palmnest.service.estateserve.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.bean.UserInfo;
import com.palmnest.application.core.util.*;
import com.palmnest.application.core.util.hangdian.EncryptionUtils;
import com.palmnest.application.core.util.http.HttpClientResult;
import com.palmnest.application.core.util.http.HttpClientUtils;
import com.palmnest.application.dto.output.app.AppUserDto;
import com.palmnest.dao.estateserve.*;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.*;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.AsynchronousDataService;
import com.palmnest.service.Executable;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ContractIinformationOrderManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.service.ws.FacePlusClient;
import com.palmnest.service.ws.OFXShopSysClient;
import com.palmnest.webapp.controller.weixiao.AES;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.CookieStore;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * AppUserManager接口的实现
 *
 * @author yubing
 * @since 2017-1-14
 */
@Slf4j
@Service("appUserManager")
public class AppUserManagerImpl extends GenericManagerImpl<AppUser, Integer> implements AppUserManager {


	private AppUserDao appUserDao;

	@Autowired
	private ContractIinformationOrderManager contractIinformationOrderManager;
	@Autowired
	private SmsAuthCodeDao                   smsAuthCodeDao;
	@Autowired
	private ScWxuserDao                      scWxuserDao;
	@Autowired
	private PropertyDao                      propertyDao;
	@Autowired
	private VisitorInFoDao                   visitorInFoDao;
	@Autowired
	private ReplayContentDao                 replayContentDao;
	@Autowired
	private WeChatApiManager                 weChatApiManager;
	@Autowired
	private ContractIinformationOrderDao     contractIinformationOrderDao;
	@Autowired
	private VirtUserDao                      virtUserDao;
	@Autowired
	private PasswordEncoder                  passwordEncoder;
	@Autowired
	private PublicNoDao                      publicNoDao;

	//线程异步处理数据Serveice
	@Autowired
	private AsynchronousDataService asynchronousWorkService;

	private String webUrl = PropertiesKit.readPropertiesValue("webUrl", "wechat.properties");
	String app_key       = PropertiesKit.readPropertiesValue("weixiao_app_key", "wechat.properties");
	String url_sync_info = PropertiesKit.readPropertiesValue("weixiao_url_sync_info", "wechat.properties");
	String app_secret    = PropertiesKit.readPropertiesValue("weixiao_app_secret", "wechat.properties");

	@Autowired
	public void setAppUserDao(AppUserDao appUserDao) {
		this.appUserDao = appUserDao;
		this.dao = appUserDao;
	}

	@Override
	public Pagenation<AppUser> queryAppUser(int pageNo,
											List<Criterion> filterList) {
		int                 pageSize  = 10;
		Map<String, String> aliasMap  = Collections.<String, String>emptyMap();
		List<Order>         orderList = new ArrayList<Order>();
		orderList.add(Order.desc("userId"));
		return this.appUserDao.queryPage(pageNo, pageSize, aliasMap, filterList, orderList, AppUser.class);
	}

	@Override
	public AppUser getAppUserByOpenId(String developId, String openId) {
		return appUserDao.getAppUserByOpenId(developId, openId);
	}

	@Override
	public AppUser getAppUsersByPhone(String userMobile) {
		return appUserDao.getAppUsersByPhone(userMobile);
	}

	@Override
	public Integer saveOrUpdateAppUser(AppUser appUser) {
		Integer userId = appUser.getId();
		if (appUser.getId() == null) {
			appUser.setId(appUserDao.getUserId());
			appUser.setCreateTime(new Date());
			appUserDao.saveObj(appUser);
			userId = appUser.getId();
		} else {
			appUser.setModifyTime(new Date());
			appUserDao.updateObj(appUser);
		}
		return userId;
	}

	@Override
	public Map<String, Object> assignBindPhone(String openId, String developId,
											   String userMobile, String authCode) {
		log.info("userMobile:" + userMobile);
		log.info("openId:" + openId);
		log.info("developId:" + developId);
		Map<String, Object> resultMap   = new HashMap<String, Object>();
		SmsAuthCode         smsAuthCode = smsAuthCodeDao.getSmsAuthCode(userMobile, authCode, "1", 15);
		if (smsAuthCode != null) {
			AppUser appUser = getAppUsersByPhone(userMobile);
			//如果用户不存在
			if (appUser == null) {
				WxUser wxUser = scWxuserDao.getScWxuserByOpenId(openId);
				//如果微信粉丝用户不存在
				if (wxUser == null) {
					wxUser = new WxUser();
					wxUser.setDevelopId(developId);
					wxUser.setOpenId(openId);
					UserInfo userinfo = weChatApiManager.getUserInfo(developId, openId);
					if (userinfo != null) {
						if (StringUtils.isNotEmpty(userinfo.getNickname())) {
							String nickName = StringUtil.StringFilter(EmojiFilterUtils
									.filterEmoji(userinfo.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*")));
							wxUser.setNickName(nickName);
						} else {
							wxUser.setNickName("微信用户");
						}
						wxUser.setCity(userinfo.getCity());
						wxUser.setCountry(userinfo.getCountry());
						wxUser.setProvince(userinfo.getProvince());
						wxUser.setLanguage(userinfo.getLanguage());
						wxUser.setHeadimgUrl(userinfo.getHeadimgurl());
					}
					wxUser.setSubscribeTime(new Date());
					wxUser.setIsSubscribe("subscribe");
					wxUser.setAccountType(Constants.AccountType_USER);
				}
				appUser = new AppUser();
				appUser.setUserMobile(userMobile);
				appUser.setIsResponsible(1);
				appUser.setUserName(wxUser.getNickName());
				appUser.setNickName(wxUser.getNickName());
				appUser.setUserPhotoUrl(wxUser.getHeadimgUrl());
				appUser.setStatus(ElementConstant.USER_CERT_STATUSNO);
				appUser.setCreateTime(new Date());
				appUser.setIsEnabled(ElementConstant.YESORNO_1);
				appUser.setStatus("0");            //待审核
				appUser.setRoleType("2");        //普通员工
				appUser.setNoticePower("0");    //默认不接收审核消息
				if (wxUser.getOrganizationId() != null) {
					appUser.setOrganizationId(wxUser.getOrganizationId());
				}
				appUserDao.saveObj(appUser);

				//更新微信用户信息
				wxUser.setUserId(appUser.getId());
				wxUser.setIsBinding(Constants.BINDING);
				if (wxUser.getId() == null) {
					scWxuserDao.saveObj(wxUser);
				} else {
					scWxuserDao.updateObj(wxUser);
				}
				resultMap.put("flag", "success");
				resultMap.put("appUser", appUser);
			}
			//如果用户存在
			else {
				if (StringUtils.isEmpty(appUser.getStatus())) {
					appUser.setStatus("0");
					appUserDao.updateObj(appUser);
				}
				WxUser wxUser = scWxuserDao.getScWxuserByUserId(appUser.getId());
				//此号码已有微信用户绑定
				if (wxUser != null) {
					//1.如果用户已经绑定了微信，则老用户解绑，新用户绑定
					if (!openId.equals(wxUser.getOpenId())) {
						wxUser.setUserId(null);
						wxUser.setIsBinding(Constants.UNBINDING);
						scWxuserDao.updateObj(wxUser);

						WxUser newWxUser = scWxuserDao.getScWxuserByOpenId(openId);
						if (saveOrUpdateWxUser(appUser, newWxUser, developId, openId)) {
							resultMap.put("flag", "success");
							resultMap.put("appUser", appUser);
						} else {
							resultMap.put("flag", "error");
						}
					} else {
						resultMap.put("appUser", appUser);
						resultMap.put("flag", "success");
					}
				}
				//此号码未有微信用户绑定
				else {
					WxUser newWxUser = scWxuserDao.getScWxuserByOpenId(openId);
					if (saveOrUpdateWxUser(appUser, newWxUser, developId, openId)) {
						resultMap.put("flag", "success");
						resultMap.put("appUser", appUser);
					} else {
						resultMap.put("flag", "error");
					}
				}
			}
			//更新验证码状态
			smsAuthCode.setIsEnabled(ElementConstant.YESORNO_0);
			smsAuthCode.setValidateTime(new Date());
			smsAuthCodeDao.updateObj(smsAuthCode);

			assignSyncUser(appUser, ElementConstant.OPRATETYPE_ADD);
		} else {
			resultMap.put("flag", "codeError");
		}
		return resultMap;
	}

	public boolean saveOrUpdateWxUser(AppUser appUser, WxUser wxUser, String developId, String openId) {
		log.info("saveOrUpdateWxUser-----");
		boolean flag = true;
		if (wxUser != null) {
			wxUser.setUserId(appUser.getId());
			wxUser.setIsBinding(Constants.BINDING);
			wxUser.setOrganizationId(appUser.getOrganizationId());
			scWxuserDao.updateObj(wxUser);
		} else {
			wxUser = new WxUser();
			wxUser.setDevelopId(developId);
			wxUser.setOpenId(openId);
			UserInfo userinfo = weChatApiManager.getUserInfo(developId, openId);
			if (userinfo != null) {
				if (StringUtils.isNotEmpty(userinfo.getNickname())) {
					String nickName = StringUtil.StringFilter(EmojiFilterUtils
							.filterEmoji(userinfo.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*")));
					wxUser.setNickName(nickName);
				} else {
					wxUser.setNickName("微信用户");
				}
				wxUser.setCity(userinfo.getCity());
				wxUser.setCountry(userinfo.getCountry());
				wxUser.setProvince(userinfo.getProvince());
				wxUser.setLanguage(userinfo.getLanguage());
				wxUser.setHeadimgUrl(userinfo.getHeadimgurl());
			}
			wxUser.setSubscribeTime(new Date());
			wxUser.setIsSubscribe("subscribe");
			wxUser.setUserId(appUser.getId());
			wxUser.setIsBinding(Constants.BINDING);
			wxUser.setOrganizationId(appUser.getOrganizationId());
			scWxuserDao.save(wxUser);
		}
		return flag;
	}

	@Override
	public String updateAppUser(AppUser appUser, String imgServerIds, String headRealtiveUrl, String developId, String dataUrl) {
		String retCode = "success";
		try {
			//删除旧的UserImageInfo
			visitorInFoDao.deleteUserImageInfoByUserId(appUser.getId(), "1");
			if (StringUtils.isNotBlank(headRealtiveUrl)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("photo", Constants.IMAGE_ROOT + headRealtiveUrl);
				CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
				if (cookieStore != null) {
					Integer imageId = FacePlusClient.photo(paramMap, cookieStore,null);
					if (imageId == null) {
						retCode = "error";
						log.info("updateAppUser() FacePlusClient.photo error.");
					} else {
						UserImageInfo userImageInfo = new UserImageInfo();
						userImageInfo.setImageFacePlusId(imageId);
						userImageInfo.setImageUrl(headRealtiveUrl);
						userImageInfo.setImageType("1");
						userImageInfo.setUserId(appUser.getId());
						userImageInfo.setImageFaceUrl(dataUrl);
						propertyDao.save(userImageInfo);
					}
				} else {
					UserImageInfo userImageInfo = new UserImageInfo();
					userImageInfo.setImageFacePlusId(null);
					userImageInfo.setImageUrl(headRealtiveUrl);
					userImageInfo.setImageType("1");
					userImageInfo.setUserId(appUser.getId());
					userImageInfo.setImageFaceUrl(dataUrl);
					propertyDao.save(userImageInfo);
				}
			}
			if ("success".equals(retCode)) {
				appUser.setImageUrl01(null);
				appUser.setImageUrl02(null);
				appUser.setImageUrl03(null);
				if (StringUtils.isNotBlank(imgServerIds)) {
					String imageUrl[] = imgServerIds.split(";");
					for (int i = 0; i < imageUrl.length; i++) {
						if (i == 0 && !"".equals(imageUrl[i])) {
							appUser.setImageUrl01(imageUrl[i]);
						} else if (i == 1 && !"".equals(imageUrl[i])) {
							appUser.setImageUrl02(imageUrl[i]);
						} else if (i == 2 && !"".equals(imageUrl[i])) {
							appUser.setImageUrl03(imageUrl[i]);
						}
					}
				}
				appUser.setModifyTime(new Date());
				appUserDao.updateObj(appUser);

				//更新微信用户信息
				WxUser wxuser = scWxuserDao.getScWxuserByUserId(appUser.getId());
				if (wxuser != null) {
					wxuser.setOrganizationId(appUser.getOrganizationId());
					wxuser.setIsBinding(Constants.BINDING);
					scWxuserDao.updateObj(wxuser);
				}

				assignSyncUser(appUser, ElementConstant.OPRATETYPE_UPD);

				//发送通知-给管理员进行审核
				sendWxTemplateMemberJoinVirtual(appUser.getVirtualArchId(), appUser.getUserName(), appUser.getUserMobile());
			}
		} catch (Exception e) {
			log.error("updateAppUser() occur error.{}" + LogExceptionStackUtil.LogExceptionStack(e));
			retCode = "error";
		}
		return retCode;
	}


	@Override
	public String updateAppUser(int userId, String status, String suggestion, String modifier, String actType) {
		try {
			AppUser appUser = appUserDao.get(userId);
			if (appUser != null) {
				CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
				if ("1".equals(actType)) {
					String[] paramsStr        = suggestion.split(";");
					String   suggestionRemark = "";
					if (paramsStr != null && paramsStr.length == 2) {
						suggestionRemark = paramsStr[0];
						String userName = paramsStr[1];
						appUser.setUserName(userName);
					} else {
						suggestionRemark = suggestion;
					}
					appUser.setSuggestion(suggestionRemark);
					appUser.setModifier(modifier);
					appUser.setModifyTime(new Date());

					String title  = "";
					String result = "";
					if (ElementConstant.USER_CERT_STATUSYES.equals(status)) {
						List<UserImageInfo> userImages = visitorInFoDao.getUserImageInfo(userId, "1");
						List<Integer>       pohto_ids  = new ArrayList<Integer>();
						if (userImages != null && userImages.size() > 0) {
							for (UserImageInfo userImageInfo : userImages) {
								if (userImageInfo.getImageFacePlusId() == null && cookieStore != null) {
									Map<String, Object> paramMap = new HashMap<String, Object>();
									paramMap.put("photo", Constants.IMAGE_ROOT + userImageInfo.getImageUrl());
									Integer imageId = FacePlusClient.photo(paramMap, cookieStore,null);
									if (imageId == null) {
										return "error";
									} else {
										userImageInfo.setImageFacePlusId(imageId);
									}
									visitorInFoDao.updateObj(userImageInfo);
								} else {
									visitorInFoDao.updateObj(userImageInfo);
								}
								pohto_ids.add(userImageInfo.getImageFacePlusId());
							}
						}

						boolean flag  =true;
						//boolean flag = assignOperateForFace(appUser, status, pohto_ids);
						if (flag) {
							appUser.setStatus(status);
							appUserDao.updateObj(appUser);
						} else {
							return "error";
						}
						title = "恭喜您，您的资料已企业认证通过，欢迎使用\\n";
						result = "通过";

					} else {//认证不通过
						boolean flag =true;
						//boolean flag = assignOperateForFace(appUser, status, null);
						if (flag) {
							appUser.setFacePlusUserId(null);
							appUser.setStatus(status);
							appUser.setRoleType("2");
							appUserDao.updateObj(appUser);
							visitorInFoDao.updateUserImageInfoByUserId(userId, "1");
						} else {
							return "error";
						}
						title = "非常抱歉，您的资料企业审核未通过，请修改资料重新提交\\n";
						result = "未通过";
					}

					//发送模板消息提醒
					List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType03, 0);
					if (!CollectionUtils.isEmpty(templateList)) {
						final WxUser wxUser = scWxuserDao.getScWxuserByUserId(userId);
						if (wxUser != null) {
							final String templateId  = (String) templateList.get(0).get("templateId");
							final String title_      = title;
							final String result_     = result;
							final String suggestion_ = suggestionRemark;
							asynchronousWorkService.store(new Executable() {
								@Override
								public Void execute() {
									log.info("assginMassnotification--");
									//获取消息模板ID
									Map<String, String> paramMap = new HashMap<String, String>();
									String              url      = webUrl + "/wechat/appUser/userInfo?userId=" + wxUser.getUserId() + "&developId=" + wxUser.getDevelopId() + "&openId=" + wxUser.getOpenId();
									paramMap.put("templateId", templateId);
									paramMap.put("title", title_);
									paramMap.put("openId", wxUser.getOpenId());
									paramMap.put("developId", wxUser.getDevelopId());
									paramMap.put("url", url);
									paramMap.put("type", "企业认证");
									paramMap.put("result", result_);
									paramMap.put("suggestion", suggestion_);
									paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
									String result = weChatApiManager.sendTemplateMsg02(paramMap);
									log.info("assginMassnotification result:" + result);
									return null;
								}
							});
						}
					}
					assignSyncUser(appUser, ElementConstant.OPRATETYPE_UPD);
				} else if ("2".equals(actType)) {
					//认证状态，进行解绑，重置为待审核
					if (ElementConstant.USER_CERT_STATUSYES.equals(appUser.getStatus()) && appUser.getFacePlusUserId() != null) {
						boolean flag = FacePlusClient.deleteSubject(appUser.getFacePlusUserId(), cookieStore);
						if (flag) {
							appUser.setFacePlusUserId(null);
							visitorInFoDao.updateUserImageInfoByUserId(userId, "1");
						} else {
							return "error";
						}
					}
//					appUser.setRoleType("2");
//					appUser.setStatus(status);
					appUser.setModifier(modifier);
					appUser.setModifyTime(new Date());
					appUserDao.updateObj(appUser);

					assignSyncUser(appUser, ElementConstant.OPRATETYPE_UPD);
				}
			}
			return "success";
		} catch (Exception e) {
			log.error("updateAppUser() occur error.{}" + LogExceptionStackUtil.LogExceptionStack(e));
			return "error";
		}
	}

	@Override
	public String updateAppUserMobile(int userId, String userMobile,
									  String authCode) {
		try {
			AppUser existAppUser = appUserDao.getAppUsersByPhone(userMobile);
			if (existAppUser == null) {
				SmsAuthCode smsAuthCode = smsAuthCodeDao.getSmsAuthCode(userMobile, authCode, "1", 15);
				if (smsAuthCode != null) {
					AppUser appUser = appUserDao.get(userId);
					if (appUser != null) {
						String oldUserMobile = appUser.getUserMobile();

						appUser.setUserMobile(userMobile);
						appUser.setModifyTime(new Date());
						appUserDao.updateObj(appUser);

						//修改电话号码（同步数据到欧法信商城）
//						if(OFXShopSysClient.changeTel(oldUserMobile, userMobile)){
//							log.info("OFXShopSysClient.changeTel success.");
//						}
//						else{
//							log.info("OFXShopSysClient.changeTel fail.");
//						}
					}
					return "success";
				} else {
					return "codeError";
				}
			} else {
				return "existError 手机号已存在";
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("updateAppUser() occur error.{}" + e.getMessage(), e.getCause());
			return "error";
		}
	}

	@Override
	public String exportUserModel(String fileFullPath, String organizationId) {
		String       retCode  = "";
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 创建工作表对象并命名
		XSSFSheet sheet = workbook.createSheet("USER");
		//标题样式定义
		XSSFCellStyle headStyle = workbook.createCellStyle();
		XSSFFont      headfont  = workbook.createFont();    //字体
		headfont.setFontHeightInPoints((short) 7);    //字体大小
		headfont.setColor(HSSFColor.BLACK.index);        //字体颜色
		headfont.setFontName("微软雅黑");                    //字体
		headStyle.setFont(headfont);

		headStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);  //填充单元格
		headStyle.setFillForegroundColor(HSSFColor.ORANGE.index);
		headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直布局：居中
		headStyle.setWrapText(true);

		headStyle.setBorderTop((short) 1);
		headStyle.setBorderLeft((short) 1);
		headStyle.setBorderBottom((short) 1);
		headStyle.setBorderRight((short) 1);
		headStyle.setTopBorderColor(HSSFColor.CORNFLOWER_BLUE.index);
		headStyle.setLeftBorderColor(HSSFColor.CORNFLOWER_BLUE.index);
		headStyle.setBottomBorderColor(HSSFColor.CORNFLOWER_BLUE.index);
		headStyle.setRightBorderColor(HSSFColor.CORNFLOWER_BLUE.index);

		XSSFCellStyle paramStyle = workbook.createCellStyle();
		XSSFFont      headfont1  = workbook.createFont();    //字体
		headfont1.setFontHeightInPoints((short) 7);    //字体大小
		headfont1.setColor(HSSFColor.BLACK.index);        //字体颜色
		headfont1.setFontName("微软雅黑");                    //字体
		paramStyle.setFont(headfont1);

		//创建行和单元格
		XSSFRow headRow = sheet.createRow(0);
		headRow.setHeight((short) (18 * 20));

		XSSFCell cell0 = headRow.createCell(0);
		cell0.setCellValue("职员代码（选填）");
		cell0.setCellStyle(headStyle);

		XSSFCell cell1 = headRow.createCell(1);
		cell1.setCellValue("姓名（必填）");
		cell1.setCellStyle(headStyle);

		XSSFCell cell2 = headRow.createCell(2);
		cell2.setCellValue("所属公司唯一编号（必填）");
		cell2.setCellStyle(headStyle);
		XSSFCell cell3 = headRow.createCell(3);
		cell3.setCellValue("所属部门唯一编号（必填）");
		cell3.setCellStyle(headStyle);
		XSSFCell cell4 = headRow.createCell(4);
		cell4.setCellValue("岗位名称（选填）");
		cell4.setCellStyle(headStyle);
		XSSFCell cell5 = headRow.createCell(5);
		cell5.setCellValue("入司时间（选填）");
		cell5.setCellStyle(headStyle);
		XSSFCell cell6 = headRow.createCell(6);
		cell6.setCellValue("移动电话（必填）");
		cell6.setCellStyle(headStyle);
		XSSFCell cell7 = headRow.createCell(7);
		cell7.setCellValue("所属项目唯一编号（必填）");
		cell7.setCellStyle(headStyle);
		sheet.setColumnWidth((short) 0, (short) 10 * 240); //调整第一列宽度
		sheet.setColumnWidth((short) 1, (short) 16 * 200);
		sheet.setColumnWidth((short) 2, (short) 16 * 260);
		sheet.setColumnWidth((short) 3, (short) 16 * 260);
		sheet.setColumnWidth((short) 4, (short) 16 * 230);
		sheet.setColumnWidth((short) 5, (short) 16 * 230);
		sheet.setColumnWidth((short) 6, (short) 16 * 230);
		sheet.setColumnWidth((short) 7, (short) 16 * 260);
		Row headerRowRegion = sheet.createRow(1);
		headRow.setHeight((short) (18 * 20));
		Cell headerCellRegion;
		headerCellRegion = headerRowRegion.createCell(0);
		headerCellRegion.setCellValue("示例");
		File             file = new File(fileFullPath);
		FileOutputStream fos  = null;
		try {
			fos = new FileOutputStream(file);
			workbook.write(fos);
		} catch (Exception e) {
			e.printStackTrace();
			retCode = "201";
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		retCode = "200";
		return retCode;
	}

	public boolean isMobileNO(String mobiles) {

		//Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147))\\d{8}$");
		Pattern p = Pattern.compile("[1][34578]\\d{9}");

		Matcher m = p.matcher(mobiles);

		return m.matches();
	}

	@Override
	public Map<String, Object> saveImportUserData(InputStream ins) {
		Map<String, Object> retMap   = new HashMap<String, Object>();
		List<AppUser>       list     = new ArrayList<AppUser>();
		int                 bugCount = 0;
		StringBuffer        bugStr   = new StringBuffer("");
		XSSFSheet           sheet    = null;
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(ins);
			sheet = workbook.getSheet("USER");
		} catch (Exception e) {
			bugStr.append("模板格式有问题，请下载最新的模板");
		}
		if (sheet == null) {
			bugStr.append("模板格式有问题，请下载最新的模板");
		} else {
			int rows = sheet.getLastRowNum();
			//如果大于2000行数据
			if (rows > 20000) {
				bugStr.append("数据量太大，不能大于2w行");
			} else if (rows < 1) {
				bugStr.append("数据为空，请录入账单信息");
			} else {
				for (int i = 4; i <= rows; i++) {
					if (sheet.getRow(i) == null) {
						continue;
					}
					if (sheet.getRow(i).getCell(6) != null) {
						sheet.getRow(i).getCell(6).setCellType(Cell.CELL_TYPE_STRING);
					} else {
						bugStr.append("第" + i + "行第7列数据有问题，请检查，问题：手机号码不能为空，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}

					String cell6 = sheet.getRow(i).getCell(6).getStringCellValue();//手机号码
					if (StringUtils.isBlank(cell6)) {
						bugStr.append("第" + i + "行第7列数据有问题，请检查，问题：手机号码不能为空，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					if (!isMobileNO(cell6)) {
						bugStr.append("第" + i + "行第7列数据有问题，请检查，问题：手机号码格式有问题，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					AppUser appUser = appUserDao.getAppUsersByPhone(cell6);
					if (appUser != null) {
						bugStr.append("第" + i + "行第7列数据有问题，请检查，问题：手机号码已注册，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					if (sheet.getRow(i).getCell(7) == null) {
						bugStr.append("第" + i + "行第8列数据有问题，请检查，问题：项目编号必填，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					sheet.getRow(i).getCell(7).setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isBlank(sheet.getRow(i).getCell(7).getStringCellValue())) {
						bugStr.append("第" + i + "行第8列数据有问题，请检查，问题：项目编号必填，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					String         cell7          = sheet.getRow(i).getCell(7).getStringCellValue();//项目唯一编码
					TbOrganization tbOrganization = propertyDao.getOrganization(cell7);
					if (tbOrganization == null) {
						bugStr.append("第" + i + "行第8列数据有问题，请检查，问题：项目编号不存在，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					if (sheet.getRow(i).getCell(2) == null) {
						bugStr.append("第" + i + "行第3列数据有问题，请检查，问题：公司编号必填，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					sheet.getRow(i).getCell(2).setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isBlank(sheet.getRow(i).getCell(2).getStringCellValue())) {
						bugStr.append("第" + i + "行第3列数据有问题，请检查，问题：公司编号必填，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					String              cell2               = sheet.getRow(i).getCell(2).getStringCellValue();//公司唯一编码
					VirtualArchitecture virtualArchitecture = propertyDao.getVirtualArchitecture(cell2);
					if (virtualArchitecture == null) {
						bugStr.append("第" + i + "行第3列数据有问题，请检查，问题：公司编号不存在，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}

					String cell3 = ""; //部门唯一编码
					if (sheet.getRow(i).getCell(3) != null) {
						sheet.getRow(i).getCell(3).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(sheet.getRow(i).getCell(3).getStringCellValue())) {
							cell3 = sheet.getRow(i).getCell(3).getStringCellValue().trim();
						}
					}
					VirtualArchitecture virtualArchitecture2 = null;
					if (StringUtils.isNotBlank(cell3)) {
						virtualArchitecture2 = propertyDao.getVirtualArchitecture(cell3);
					}

					appUser = new AppUser();
					if (sheet.getRow(i).getCell(0) != null) {
						sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
						appUser.setUserNumber(sheet.getRow(i).getCell(0).getStringCellValue());
					}
					if (sheet.getRow(i).getCell(1) == null) {
						bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：姓名必填，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					sheet.getRow(i).getCell(1).setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isBlank(sheet.getRow(i).getCell(1).getStringCellValue())) {
						bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：姓名必填，请导出系统模板匹配录入<br/>");
						bugCount++;
						continue;
					}
					appUser.setUserName(sheet.getRow(i).getCell(1).getStringCellValue());//用户名称
					appUser.setUserMobile(sheet.getRow(i).getCell(6).getStringCellValue());//用户号码
					appUser.setOrganizationId(tbOrganization.getId());//项目ID
					appUser.setOrganizationName(tbOrganization.getName());
					appUser.setVirtualArchId(virtualArchitecture.getId());//公司ID
					appUser.setVirtualArchName(virtualArchitecture.getName());
					if (virtualArchitecture2 != null) {
						appUser.setDepartmentId(virtualArchitecture2.getId());//部门ID
						appUser.setDepartmentName(virtualArchitecture2.getName());
					}
					if (sheet.getRow(i).getCell(4) != null) {
						appUser.setPositionName(sheet.getRow(i).getCell(4).getStringCellValue());//职位名称
					}
					if (sheet.getRow(i).getCell(5) != null) {
						appUser.setEnteringTime(sheet.getRow(i).getCell(5).getDateCellValue());//入司时间
					}
					appUser.setStatus("1");
					appUser.setCreateTime(new Date());
					appUser.setIsEnabled("1");
					list.add(appUser);
				}
			}
		}
		retMap.put("bugCount", bugCount);
		retMap.put("bugStr", bugStr.toString());
		retMap.put("data", list);
		retMap.put("okCount", list.size());
		return retMap;
	}

	@Override
	public String validateHeadStandard(String imageUrl, String virtualArchId) {
		CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + virtualArchId);
		if (cookieStore == null) {
			//cookieStore = FacePlusClient.authLogin(Constants.FACE_PLUS_USER, Constants.FACE_PLUS_PASSWORD);
		}
		String relativePath = FileUploadUtils.getBase64ImageUrl(imageUrl);
		if (StringUtils.isNotBlank(relativePath)) {
			boolean             checkFlag = false;
			Map<String, Object> paramMap  = new HashMap<String, Object>();
			paramMap.put("photo", Constants.IMAGE_ROOT + relativePath);
			try {
				Integer i = FacePlusClient.photo(paramMap, cookieStore,null);
				if (i != null) {
					checkFlag = true;
				}
			} catch (Exception e) {
				log.error("validateHeadStandard occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			}
			if (checkFlag) {
				return relativePath;
			} else {
				return "error";
			}
		} else {
			return "error";
		}
	}

	@Override
	public Map<String, Object> saveAppUser(List<AppUser> appuserList) throws Exception {
		/*Map<String,Object> resultMap=new HashMap<String, Object>();
		Map<String,Object> paramMap=new HashMap<String, Object>();
		List<Integer> userList=new ArrayList<Integer>();
		String desc="";
		boolean flag=true;
		try{
			if(!CollectionUtils.isEmpty(appuserList)){
				for(int i=0;i<appuserList.size();i++){
					AppUser appUser=appuserList.get(i);
					CookieStore cookieStore=Constants.FaceMap.get("vis_cookiestore_"+appUser.getVirtualArchId());
					paramMap=new HashMap<String, Object>();
					paramMap.put("subjectType",0);
					paramMap.put("obj",appUser);
					paramMap.put("photo_ids",new ArrayList<Integer>());
					Integer userId=FacePlusClient.subject(paramMap,cookieStore);
					if(userId==null){
						desc="上传图用户失败！";
						flag=false;
					}
					appUser.setFacePlusUserId(userId);
					userList.add(userId);
				}	
			}
			//保存用户信息
			if(flag){
				for(AppUser appUser:appuserList){
					appUserDao.save(appUser);
				}
			}
		}catch(Exception e){
			log.error("程序异常！执行回滚facePlus操作 异常信息:"+e.getMessage());
			desc="程序异常！";
			flag=false;
		}
		resultMap.put("desc", desc);
		resultMap.put("flag", flag);*/
		Map<String, Object> resultMap = new HashMap<String, Object>();
		for (AppUser appUser : appuserList) {
			appUserDao.save(appUser);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> updateAppUserInfo(AppUser appUser, String imageUrlids, String removeUrlids, String addimgUrls) throws Exception {
		UserImageInfo       adduserImageInfo  = null;
		Map<String, Object> paramMap          = new HashMap<String, Object>();
		List<Integer>       pohto_ids         = new ArrayList<Integer>();
		List<UserImageInfo> userImageInfoList = new ArrayList<UserImageInfo>();
		String              desc              = "保存成功！";
		boolean             flag              = true;
		try {
			//审核成功！或后台编辑
			//操作没有更改的
			CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
			if (StringUtils.isNotBlank(imageUrlids)) {
				String imageUrlId[] = getStr(imageUrlids);
				for (String str : imageUrlId) {
					if (StringUtils.isNotBlank(str)) {
						UserImageInfo userImageInfo = visitorInFoDao.getUserImageInfoById(Integer.parseInt(str));
						if (userImageInfo.getImageFacePlusId() != null) {
							pohto_ids.add(userImageInfo.getImageFacePlusId());
						} else {
							if (cookieStore != null) {
								paramMap.put("photo", Constants.IMAGE_ROOT + userImageInfo.getImageUrl());
								Integer faceImageId = FacePlusClient.photo(paramMap, cookieStore,null);
								if (faceImageId == null) {
									flag = false;
									desc = "上传图片失败！";
									break;
								}
								userImageInfo.setImageFacePlusId(faceImageId);
								pohto_ids.add(faceImageId);
							}
							visitorInFoDao.updateObj(userImageInfo);
						}
					}
				}
			}
			//新增图片操作
			if (StringUtils.isNotBlank(addimgUrls)) {
				String addImageUrl[] = getStr(addimgUrls);
				for (String str : addImageUrl) {
					adduserImageInfo = new UserImageInfo();
					if (StringUtils.isNotBlank(str)) {
						if (cookieStore != null) {
							paramMap.put("photo", Constants.IMAGE_ROOT + str);
							Integer faceImageId = FacePlusClient.photo(paramMap, cookieStore,null);
							if (faceImageId == null) {
								flag = false;
								desc = "上传图片失败！";
								break;
							}
							adduserImageInfo.setImageFacePlusId(faceImageId);
							pohto_ids.add(faceImageId);
						}
						adduserImageInfo.setImageUrl(str);
						userImageInfoList.add(adduserImageInfo);
					}
				}
			}

			//上传用户信息或更新用户信息
			if (pohto_ids.size() > 0) {
				//flag = assignOperateForFace(appUser, "1", pohto_ids);
			}

			//执行JDBC操作
			if (flag) {
				//删除图片操作
				if (StringUtils.isNotBlank(removeUrlids)) {
					String removeImagUrlId[] = getStr(removeUrlids);
					for (String str : removeImagUrlId) {
						if (StringUtils.isNotBlank(str)) {
							UserImageInfo userImageInfo = visitorInFoDao.getUserImageInfoById(Integer.parseInt(str));
							visitorInFoDao.remove(userImageInfo);
						}
					}
				}
				//保存用户信息
				if (appUser.getId() == null) {
//					appUser.setId(10021);
					appUser.setStatus("1");
					appUser.setModifier(appUser.getCreator());
					appUser.setModifyTime(new Date());
					visitorInFoDao.saveObj(appUser);
				} else {
					appUser.setStatus("1");
					//发送模板消息提醒
					List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType03, 0);
					if (!CollectionUtils.isEmpty(templateList)) {
						final WxUser wxUser = scWxuserDao.getScWxuserByUserId(appUser.getId());
						if (wxUser != null) {
							final String templateId  = (String) templateList.get(0).get("templateId");
							final String title_      = "恭喜您，您的资料已企业认证通过，欢迎使用\\n";
							final String result_     = "通过";
							final String suggestion_ = "信息正确，给予通过";
							asynchronousWorkService.store(new Executable() {
								@Override
								public Void execute() {
									//获取消息模板ID
									Map<String, String> paramMap = new HashMap<String, String>();
									String              url      = webUrl + "/wechat/appUser/userInfo?userId=" + wxUser.getUserId() + "&developId=" + wxUser.getDevelopId() + "&openId=" + wxUser.getOpenId();
									paramMap.put("templateId", templateId);
									paramMap.put("title", title_);
									paramMap.put("openId", wxUser.getOpenId());
									paramMap.put("developId", wxUser.getDevelopId());
									paramMap.put("url", url);
									paramMap.put("type", "企业认证");
									paramMap.put("result", result_);
									paramMap.put("suggestion", suggestion_);
									paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
									String result = weChatApiManager.sendTemplateMsg02(paramMap);
									log.info("assginMassnotification result:" + result);
									return null;
								}
							});
						}
					}

					WxUser wxUser = scWxuserDao.getScWxuserByUserId(appUser.getId());
					if (wxUser != null) {
						wxUser.setOrganizationId(appUser.getOrganizationId());
						visitorInFoDao.updateObj(wxUser);
					}
					visitorInFoDao.updateObj(appUser);

					//用户手机号码发生改变
					if (!appUser.getUserMobile().equals(appUser.getOrganizationName())) {
						//修改电话号码（同步数据到欧法信商城）
						if (OFXShopSysClient.changeTel(appUser.getOrganizationName(), appUser.getUserMobile())) {
							log.info("updateAppUserInfo OFXShopSysClient.changeTel success.");
						} else {
							log.info("updateAppUserInfo OFXShopSysClient.changeTel fail.");
						}
					}
				}
				//保存图片
				for (UserImageInfo userImageInfo : userImageInfoList) {
					userImageInfo.setImageType("1");
					userImageInfo.setUserId(appUser.getId());
					visitorInFoDao.save(userImageInfo);
				}

				List<ContractIinformationOrder> list = contractIinformationOrderDao.getBusinessRecordBuyUser(appUser.getId());
				if (!CollectionUtils.isEmpty(list)) {
					contractIinformationOrderManager.saveUpdateContart(appUser.getId().toString(), appUser.getOrganizationId().toString(), appUser.getVirtualArchId().toString(), "");
				} else {
					assignSyncUser(appUser, ElementConstant.OPRATETYPE_UPD);
				}
			} else {
				desc = "上传用户失败！";
			}
		} catch (Exception e) {
			log.error("更新保存员工信息异常！错误信息为:" + e.getMessage());
			flag = false;
			desc = "程序异常！";
		}
		paramMap.put("flag", flag);
		paramMap.put("desc", desc);
		return paramMap;
	}

	public String[] getStr(String str) {
		return str.substring(0, str.length() - 1).split(",");
	}

	/*@Override
	public boolean assignOperateForFace(AppUser appUser, String status, List<Integer> pohto_ids) throws Exception {
		boolean             flag     = true;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		//审核通过
		CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
		if (ElementConstant.USER_CERT_STATUSYES.equals(status)) {
			//上传用户信息或更新用户信息
			if (cookieStore != null) {
				if (appUser.getFacePlusUserId() != null) {
					String subject = FacePlusClient.getSubject(appUser.getFacePlusUserId(), cookieStore);
					if (subject == null) {
						paramMap.put("subjectType", 0);
						paramMap.put("obj", appUser);
						paramMap.put("photo_ids", pohto_ids);
						Integer userId = FacePlusClient.subject(paramMap, cookieStore);
						if (userId == null) {
							flag = false;
						} else {
							appUser.setFacePlusUserId(userId);
						}
					} else {
						FacePlusClient.updatesubject(appUser, pohto_ids, cookieStore);
					}
				} else {
					paramMap = new HashMap<String, Object>();
					paramMap.put("subjectType", 0);
					paramMap.put("obj", appUser);
					paramMap.put("photo_ids", pohto_ids);
					Integer userId = FacePlusClient.subject(paramMap, cookieStore);
					if (userId == null) {
						flag = false;
					} else {
						appUser.setFacePlusUserId(userId);
					}
				}
			}
		}
		//审核不通过
		else {
			if (appUser.getFacePlusUserId() != null && cookieStore != null) {
				flag = FacePlusClient.deleteSubject(appUser.getFacePlusUserId(), cookieStore);
			}
		}
		return flag;
	}*/

	@Override
	public boolean assignSyncUser(AppUser appuser, String operateType) {
		WxUser wxUser = scWxuserDao.getScWxuserByUserId(appuser.getId());
		if (wxUser != null) {
			StringBuffer strParams = new StringBuffer();
			strParams.append("userName=" + appuser.getUserName());
			strParams.append("&userMobile=" + appuser.getUserMobile());
			String signStatus = "0";
			if (appuser.getOrganizationId() != null) {
				TbOrganization organization = propertyDao.getTbOrganizationById(appuser.getOrganizationId());
				strParams.append("&organizationCode=" + organization.getCode());
				//企业认证用户
				if (appuser.getVirtualArchId() != null && "1".equals(appuser.getStatus())) {
					//获取企业是否签约
					ContractIinformation contractIinformation = contractIinformationOrderDao.getContractIinformation(appuser.getVirtualArchId());

					VirtualArchitecture virtual = propertyDao.getVirtualArchitectureById(appuser.getVirtualArchId());
					if (contractIinformation != null) {
						strParams.append("&customerNo=" + virtual.getCustomerNumber());
						signStatus = "1";
					}
					strParams.append("&address=" + virtual.getAddress());
				}
			}
			strParams.append("&signStatus=" + signStatus);
			strParams.append("&customerType=" + 2);
			strParams.append("&operateType=" + operateType);

			boolean result = true;
			//UserinformationSync.assignuser(strParams.toString());
			log.info("assignSyncUser----------");
			log.info("strParams:" + strParams);
			log.info("result:" + result);
			return result;
		} else {
			log.info("assignSyncUser----------");
			log.info("the user not register." + appuser.getId());
			return true;
		}
	}

	@Override
	public void initAppUserToOneKeyService() {
		List<WxUser> list = scWxuserDao.getResisterWxUserList();
		if (!CollectionUtils.isEmpty(list)) {
			for (WxUser wxUser : list) {
				try {
					AppUser appUser = appUserDao.get(wxUser.getUserId());
					assignSyncUser(appUser, ElementConstant.OPRATETYPE_ADD);
				} catch (Exception e) {
					log.error("initAppUserToOneKeyService occur error." + LogExceptionStackUtil.LogExceptionStack(e));
				}
			}
		}
	}

	@Override
	public Page queryAppUserList(int userId, int virtualId, int pageNo, int pageSize) {
		return appUserDao.queryAppUserList(userId, virtualId, pageNo, pageSize);
	}

	@Override
	public Map<String, String> assignReviewUser(int userId, int acceptUserId, String status) {
		Map<String, String> retMap  = new HashMap<String, String>();
		AppUser             appUser = appUserDao.get(userId);
		if (appUser != null && "1".equals(appUser.getRoleType()) && "1".equals(appUser.getStatus())) {
			String flag = updateAppUser(acceptUserId, status, "", "", "1");
			if ("success".equals(flag)) {
				retMap.put("flag", "success");
				retMap.put("resultDesc", "处理成功");
			} else {
				retMap.put("flag", "fail");
				retMap.put("resultDesc", "处理失败，请稍后再试或者联系系统管理员");
			}
		} else {
			retMap.put("flag", "fail");
			retMap.put("resultDesc", "处理失败，请核查操作权限");
		}
		return retMap;
	}

	@Override
	public Map<String, String> assignSetRoleAppUser(int userId, int acceptUserId) {
		Map<String, String> retMap  = new HashMap<String, String>();
		AppUser             appUser = appUserDao.get(userId);
		if (appUser != null && "1".equals(appUser.getRoleType())) {
			AppUser acceptUser = appUserDao.get(acceptUserId);
			acceptUser.setRoleType("1");    //设置为管理员
			acceptUser.setModifyTime(new Date());
			appUserDao.updateObj(acceptUser);
			retMap.put("flag", "success");
			retMap.put("resultDesc", "处理成功");

			//发送模板消息提醒
			List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType03, 0);
			if (!CollectionUtils.isEmpty(templateList)) {
				final WxUser wxUser = scWxuserDao.getScWxuserByUserId(acceptUserId);
				if (wxUser != null) {
					final String templateId  = (String) templateList.get(0).get("templateId");
					String       title       = "恭喜您，您的资料已企业认证通过，并设置为企业管理员，可以审核管理企业员工，欢迎使用\\n";
					String       result      = "通过";
					final String title_      = title;
					final String result_     = result;
					final String suggestion_ = "";
					asynchronousWorkService.store(new Executable() {
						@Override
						public Void execute() {
							log.info("assginMassnotification--");
							//获取消息模板ID
							Map<String, String> paramMap = new HashMap<String, String>();
							String              url      = webUrl + "/wechat/appUser/userInfo?userId=" + wxUser.getUserId() + "&developId=" + wxUser.getDevelopId() + "&openId=" + wxUser.getOpenId();
							paramMap.put("templateId", templateId);
							paramMap.put("title", title_);
							paramMap.put("openId", wxUser.getOpenId());
							paramMap.put("developId", wxUser.getDevelopId());
							paramMap.put("url", url);
							paramMap.put("type", "企业管理员");
							paramMap.put("result", result_);
							paramMap.put("suggestion", suggestion_);
							paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
							String result = weChatApiManager.sendTemplateMsg02(paramMap);
							log.info("assignSetRoleAppUser result:" + result);
							return null;
						}
					});
				}
			}
		} else {
			retMap.put("flag", "fail");
			retMap.put("resultDesc", "处理失败，请核查操作权限");
		}
		return retMap;
	}


	@Override
	public Integer getAppUserNonCheckedCount(String virtualArchId, String status) {
		return appUserDao.getAppUserNonCheckedCount(virtualArchId, status);
	}


	@Override
	@Transactional
	public Map<String, String> assignJoinVirtual(Map<String, String> paramsMap) {
		//返回的结果
		Map<String, String> retMap = new HashMap<String, String>();
		//业务处理结果
		boolean dealFlag = false;

		String              openId          = paramsMap.get("openId");
		String              developId       = paramsMap.get("developId");
		String              userId          = paramsMap.get("userId");
		String              zhengjianImage  = paramsMap.get("zhengjianImage");
		String              headRealtiveUrl = paramsMap.get("headRelativeUrl");
		String              dataUrl         = paramsMap.get("dataUrl");
		String              userName        = paramsMap.get("name");
		String              virtualId       = paramsMap.get("virtualId");
		VirtualArchitecture virtual         = propertyDao.getVirtualArchitectureById(Integer.parseInt(virtualId));
		if (StringUtils.isNotBlank(userId)) {
			AppUser appUser = appUserDao.get(Integer.parseInt(userId));
			appUser.setOrganizationId(virtual.getOrganizationId());
			appUser.setVirtualArchId(virtual.getId());
			appUser.setUserName(userName);
			appUser.setStatus("0");            //待审核
			appUser.setRoleType("2");        //普通员工
			String result = updateAppUser(appUser, zhengjianImage, headRealtiveUrl, developId, dataUrl);
			if ("success".equals(result)) {
				dealFlag = true;
				retMap.put("flag", "success");
			} else {
				retMap.put("flag", "fail");
				retMap.put("resultDesc", "提交失败，请检查网络或稍后再试.");
			}
		}
		//新注册用户
		else {
			String userMobile = paramsMap.get("userMobile");
			String authCode   = paramsMap.get("authCode");

			//新增用户
			Map<String, Object> resultMap = assignBindPhone(openId, developId, userMobile, authCode);
			String              flag      = resultMap.get("flag").toString();
			if ("success".equals(flag)) {
				//更新用户
				AppUser appUser = appUserDao.getAppUsersByPhone(userMobile);
				appUser.setOrganizationId(virtual.getOrganizationId());
				appUser.setVirtualArchId(virtual.getId());
				appUser.setUserName(userName);
				if (!"1".equals(appUser.getStatus())) {
					appUser.setStatus("0");            //待审核
					appUser.setRoleType("2");        //普通员工
				}
				String result = updateAppUser(appUser, zhengjianImage, headRealtiveUrl, developId, dataUrl);
				if ("success".equals(result)) {
					dealFlag = true;
					retMap.put("flag", "success");
				} else {
					retMap.put("flag", "fail");
					retMap.put("resultDesc", "提交失败，请检查网络或稍后再试.");
				}
			} else if ("codeError".equals(flag)) {
				retMap.put("flag", "fail");
				retMap.put("resultDesc", "验证码错误或失效");
			} else if ("error".equals(flag)) {
				retMap.put("flag", "fail");
				retMap.put("resultDesc", "提交失败，请检查网络或稍后再试.");
			} else {
				retMap.put("flag", "fail");
				retMap.put("resultDesc", "您的信息已提交，请等候审核.");
			}

			if (dealFlag) {
				sendWxTemplateMemberJoinVirtual(Integer.parseInt(virtualId), userName, userMobile);
			}
		}
		return retMap;
	}

	private void sendWxTemplateMemberJoinVirtual(int virtualId, String userName, String userMobile) {
		log.info("sendWxTemplateMemberJoinVirtual:");
		//推送微信消息模板-成员申请待审核通知
		List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType09, 0);
		if (!CollectionUtils.isEmpty(templateList)) {
			//只有管理并且开通接收消息设置，才可以推送消息给他
//			List<AppUser> appUsers=appUserDao.getAppUserByRoleType("1", virtualId);
			List<AppUser>      appUsers = new ArrayList<AppUser>();
			List<VirtUserInfo> virUserList;
			try {
				virUserList = virtUserDao.getVirUserByVirId(virtualId);
				if (virUserList != null && virUserList.size() > 0) {
					for (int i = 0; i < virUserList.size(); i++) {
						VirtUserInfo virUser = virUserList.get(i);
						if (appUserDao.exists(virUser.getUserId())) {
							AppUser appUser = appUserDao.get(virUser.getUserId());
							appUsers.add(appUser);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			String templateId = (String) templateList.get(0).get("templateId");
			for (AppUser appUser : appUsers) {
				log.info("appUser id:" + appUser.getId());
				if ("1".equals(appUser.getNoticePower()) && "1".equals(appUser.getStatus())) {
					WxUser wxUser = scWxuserDao.getScWxuserByUserId(appUser.getId());
					if (wxUser != null) {
						log.info("wxUser id:" + wxUser.getId());
						String title = userName + "申请加入您的企业，请审核\\n";
						//获取消息模板ID
						Map<String, String> paramMap = new HashMap<String, String>();
						String              url      = webUrl + "/wechat/memberManage/memberManageList?openId=" + wxUser.getOpenId() + "&developId=" + wxUser.getDevelopId() + "&userId=" + wxUser.getUserId();
						paramMap.put("templateId", templateId);
						paramMap.put("openId", wxUser.getOpenId());
						paramMap.put("developId", wxUser.getDevelopId());
						paramMap.put("url", url);
						paramMap.put("title", title);
						paramMap.put("type", "新成员申请");
						paramMap.put("content", userName + " " + userMobile);
						paramMap.put("time", DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
						paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
						weChatApiManager.sendTemplateMsg09(paramMap);
					}
				}
			}
		}
	}

	@Override
	@Transactional
	public AppResultDto updateTelByHisTel(String userMobile, String code, String developId, String openId) {
		AppResultDto dto         = AppResultUtil.createErrorDto("100", "传输参数异常");
		SmsAuthCode  smsAuthCode = smsAuthCodeDao.getSmsAuthCode(userMobile, code, "1", 15);
		if (smsAuthCode == null) {
			return AppResultUtil.createErrorDto("100", "验证码错误");
		}
		AppUser user = appUserDao.getAppUsersByPhone(userMobile);
		if (user != null) {
			return AppResultUtil.createErrorDto("100", "系统中已存在该用户");
		}
		WxUser  wxUser  = scWxuserDao.getScWxuserByOpenId(openId);
		AppUser appUser = appUserDao.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
		if (appUser != null) {
			String modifier = "";
			if (wxUser != null) {
				modifier = wxUser.getId().toString();
			}
			appUser.setUserMobile(userMobile);
			appUser.setModifyTime(new Date());
			appUser.setModifier(modifier);
			appUserDao.updateObj(appUser);
			dto = AppResultUtil.createSuccesDto();
		}
		return dto;
	}

	@Override
	public AppUserDto convertToAppDto(AppUser user) {
		AppUserDto dto = new AppUserDto(user.getId(), user.getUserName(), user.getUserMobile(), user.getUserPhotoUrl());
		dto.setDeviceType(user.getDeviceType());
		dto.setDeviceNo(user.getDeviceNo());
		dto.setOrganizationId(user.getOrganizationId());
		return dto;
	}

	@Override
	public boolean updateUserPwd(String telephone, String newPwd) {
		boolean retFlag = true;
		AppUser user    = appUserDao.getAppUsersByPhone(telephone);
		if (user == null) {
			retFlag = false;
		} else {
			user.setPassword(passwordEncoder.encodePassword(newPwd, null));
		}
		return retFlag;
	}

	@Override
	public List<AppUser> getAppUserByVirId(int virtualId) {
		return appUserDao.getAppUserByVirId(virtualId);
	}

	@Override
	public Page findList(Map<String, Object> paramets, int pageSize, int pageNo) {
		return appUserDao.findList(paramets, pageSize, pageNo);
	}

//	@Override
//	public AppUser getAUByOpenId(String orgId, String openId) {
//		return appUserDao.getAUByOpenId(orgId, openId);
//	}

	@Override
	public AppUser getAppUsersByPhoneAndOrg(String userMobile, Integer orgId) {
		return appUserDao.getAppUsersByPhoneAndOrg(userMobile, orgId);
	}

	@Override
	public AppUser getAppUserByWxUserAndOrg(Integer wxUserId, Integer orgId) {
		return appUserDao.getAppUserByWxUserAndOrg(wxUserId, orgId);
	}

	@Override
	public List<AppUser> getUserByOrgIdAndRoleType(String orgId,
												   String roleTypes) {
		return appUserDao.getUserByOrgIdAndRoleType(orgId, roleTypes);
	}

	@Override
	public AppUser getAppUsersByPhoneAndOrg(String userMobile, String orgId,
											String isEnabled) {
		return appUserDao.getAppUsersByPhoneAndOrg(userMobile, orgId, isEnabled);
	}

	@Override
	public void updateAppUser(Integer userId, Integer wxUserId, Integer orgId) {
		appUserDao.updateAppUser(userId, wxUserId, orgId);
	}

	@Override
	public List<AppUser> getWxUserByOrgIds(String orgIds) {
		return appUserDao.getWxUserByOrgIds(orgIds);
	}

	@Override
	public List<AppUser> getAppUserByOrgId(Integer orgId) {
		return appUserDao.getAppUserByOrgId(orgId);
	}

	@Override
	public int updateAppUserByUserIds(Map<String, String> map) {
		return appUserDao.updateAppUserByUserIds(map);
	}

	@Override
	public AppUser getAppUserByLingLingId(String lingLingId) {
		return appUserDao.getAppUserByLingLingId(lingLingId);
	}

	@Override
	public AppUser getUserByVicIdAndMobile(Integer virtualArchId, String mobile) {
		return appUserDao.getUserByVicIdAndMobile(virtualArchId, mobile);
	}

	@Override
	public List<Map<String, Object>> getWhiteUserByMobileAndOrg2(String mobile, String developId) {
		WxPublicno publicno = publicNoDao.getByDevelopId(developId);
		return appUserDao.getWhiteUserByMobileAndOrg2(mobile, publicno.getId());
	}

	@Override
	public List<Map<String, Object>> getWeiXiaoAppUsersByIds(String userIds, Integer orgId) {
		return appUserDao.getWeiXiaoAppUsersByIds(userIds, orgId);
	}

	@Override
	public AppResultDto syncEmployeeInfo(String userIds, Integer orgId, User user1) {

		JSONArray                 jsonArray = new JSONArray();
		List<Map<String, Object>> users     = appUserDao.getWeiXiaoAppUsersByIds(userIds, orgId);

		try {
			if (users != null && users.size() > 0) {
				for (Map<String, Object> map : users) {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("name", map.get("name"));
					jsonObject.put("telephone", map.get("telephone"));
					jsonObject.put("organization", map.get("organization"));
					if (map.get("gender") == null || StringUtils.isBlank(map.get("gender").toString())) {
						jsonObject.put("gender", "男");
					} else {
						jsonObject.put("gender", map.get("gender"));
					}
					if (map.get("identity_type") == null || StringUtils.isBlank(map.get("identity_type").toString())) {
						jsonObject.put("identity_type", "员工");
					} else {
						jsonObject.put("identity_type", map.get("identity_type"));
					}
					if (map.get("card_number") == null || StringUtils.isBlank(map.get("card_number").toString())) {
						// 用户编号为空(8位)
						String  userNum = String.format("%08d", appUserDao.getUserNumer());
						AppUser user    = appUserDao.get((Integer) map.get("userId"));
						user.setUserNumber(userNum);
						appUserDao.updateObj(user);
						jsonObject.put("card_number", userNum);
					} else {
						jsonObject.put("card_number", map.get("card_number"));
					}

					jsonArray.add(jsonObject);
				}
			}

			String str = jsonArray.toString();
			// 参数加密
			String enStr = AES.Encrypt(str, app_key, app_secret.substring(0, 16));
			// 构建参数
			JSONObject params = new JSONObject();
			params.put("raw_data", enStr);
			params.put("app_key", app_key);

			log.info("AppUserManagerImpl syncEmployeeInfo 同步参数:原始数据:" + str + ",加密后参数:" + params.toString() + ",--url:" + url_sync_info + "");

			String result = HttpKit.HttpClientPost(params.toString(), url_sync_info);
			log.info("result:" + result + "");
			JSONObject object = JSONObject.parseObject(result);
			if (0 == object.getInteger("errcode")) {
				// 同步成功,保存操作记录
				MethodLog methodLog = new MethodLog();
				methodLog.setOrgId(orgId);
				methodLog.setCreate_time(new Date());
				methodLog.setMethod_name("syncEmployeeInfo");
				methodLog.setCreator(user1.getId());
				propertyDao.saveObj(methodLog);
				return AppResultUtil.createSuccesDto();
			} else {
				// 同步失败
				throw new RuntimeException("同步用户数据异常:" + object.getString("errmsg"));
//				return AppResultUtil.createErrorDto("100", object.getString("errmsg"));
			}
		} catch (Exception e) {
			log.error("============= 同步用户数据异常:" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "同步数据异常");
		}
	}

	public Map<String, Object> hdRegister(String mobile, String openId) {
		try {
			SimpleDateFormat    dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String              hdUrl      = PropertiesKit.readPropertiesValue("hdUrl", "wechat.properties");
			String              url        = hdUrl + "/user/lyzc/queryUserInfo.htm";
			Map<String, String> map        = new HashMap<String, String>();

			map.put("date", dateFormat.format(new Date()));
			map.put("mobile", mobile);
			map.put("openId", openId);
			map.put("password", "123456");

			String sign = EncryptionUtils.getSign(map);
			log.info("WechatIndexController hdRegister====> 航电用户注册接口加密 sign:" + sign);
			map.put("sign", sign);

			HttpClientResult    httpClientResult = HttpClientUtils.doPost(url, map);
			Map<String, Object> result           = (Map<String, Object>) JSON.parse(httpClientResult.getContent());
			log.info("航电用户注册返回:{}" + JSONObject.toJSONString(result));
			boolean success = (Boolean) result.get("success");//是否成功
			if (!success) {
				throw new RuntimeException("航电用户注册异常");
			}
			return result;
		} catch (Exception e) {
			Map map = new HashMap();
			map.put("success", true);
			Map map2 = new HashMap();
			map2.put("userCode", "20000");
			map.put("data", map2);
			log.error("航电用户注册异常,返回默认userCode 20000:========>" + e.getMessage());
			return map;
		}
	}

	@Override
	public List<AppUser> getAppUserByIds(String userIds) {
		return appUserDao.getAppUserByIds(userIds);
	}

	@Override
	public List<AppUser> getWhiteUserByMobile(String mobile) {
		return appUserDao.getWhiteUserByMobile(mobile);
	}

	@Override
	public List<Map<String, Object>> getUserMobileAndDepName(Integer orgId) {
		return appUserDao.getUserMobileAndDepName(orgId);
	}

	@Override
	public Integer getUserNumer() {
		return appUserDao.getUserNumer();
	}

	@Override
	public List<AppUser> countOrgWhiteUser(String[] orgIds) {
		return appUserDao.countOrgWhiteUser(orgIds);
	}

	@Override
	public String getUserMealcard(String userMobile) {
		return appUserDao.getUserMealcard(userMobile);
	}

	@Override
	public User getByAccount(String account) {
		return appUserDao.getByAccount(account);
	}

	@Override
	public AppUser getWhiteUserByMobileAndVirt(Integer virId, String employeePhone) {
		return appUserDao.getWhiteUserByMobileAndVirt(virId, employeePhone);
	}
	
	@Override
	public AppUser getWhiteUserByMobileAndOrgId(Integer orgId, String employeePhone) {
		return appUserDao.getWhiteUserByMobileAndOrgId(orgId, employeePhone);
	}

	@Override
	public List<Map<String, Object>> getVirtDeptUser(Integer virtId, String name) {
		return appUserDao.getVirtDeptUser(virtId, name);
	}

	@Override
	public List<Map<String, Object>> getGroupUser(Integer groupId,
												  Integer orgId, String name) {
		return appUserDao.getGroupUser(groupId, orgId, name);
	}

	@Override
	public List<Map<String, Object>> getNotGroupUser(Integer groupId,
													 Integer orgId, String name) {
		return appUserDao.getNotGroupUser(groupId, orgId, name);
	}

	@Override
	public AppUser findUserByNewFramework(Integer userId,String database) {
		return appUserDao.findUserByNewFramework(userId, database);
	}

	@Override
	public List<Map<String, Object>> getAllUserByOrgIds(String orgIds,String userIds,String openIds) {
		return appUserDao.getAllUserByOrgIds(orgIds, userIds,openIds);
	}

	@Override
	public AppUser findLoginUserByOpenId(Integer orgId, String openId) {
		// TODO Auto-generated method stub
		return appUserDao.findLoginUserByOpenId(orgId, openId);
	}
}
