package com.palmnest.service.dinner.service.impl;

import com.palmnest.application.AppConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.ExcelUtils;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.VirInfoDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.AppUserInputDto;
import com.palmnest.application.dto.input.ConsumerInputDto;
import com.palmnest.application.dto.output.AppUserDinDto;
import com.palmnest.application.dto.output.IntegralRecodeDto;
import com.palmnest.model.Element;
import com.palmnest.model.dinner.*;
import com.palmnest.model.enterprise.VirPermConfig;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.lingling.DevicePermGroup;
import com.palmnest.model.lingling.LingLingCard;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.dinner.manager.*;
import com.palmnest.service.dinner.service.ConsumerUserService;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.lingling.manager.LingLingManager;
import com.palmnest.service.outer.KafkaOuterService;
import com.palmnest.service.virtProject.manager.UserAccountManager;
import com.palmnest.service.virtProject.manager.VirtualAccountManager;
import com.palmnest.service.ws.FacePlusClient;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.CookieStore;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 订餐管理  新增账号  实现类
 *
 * @author leixiaoliang
 */
@Slf4j
@Service("consumerUserService")
public class ConsumerUserServiceImpl implements ConsumerUserService {


	public static final String CLIENTNO  = PropertiesKit.readPropertiesValue("clientNo", "wechat.properties");
	
	
	@Autowired
	private ConsumerManager             consumerManager;
	@Autowired
	private VirtualArchManager          virtualArchManager;
	@Autowired
	private IntegralRecodeInfoManager   integralRecodeInfoManager;
	@Autowired
	private AppUserManager              appUserManager;
	@Autowired
	private VisitorInFoManager          visitorInFoManager;
	@Autowired
	private UserAccountManager          userAccountManager;
	@Autowired
	private OrganizationManager         organizationManager;
	@Autowired
	private VirtualAccountManager       virtualAccountManager;
	@Autowired
	private ScWxuserManager             scWxuserManager;
	@Autowired
	private RechargeSetManager          rechargeSetManager;
	@Autowired
	private KafkaOuterService           kafkaOuterService;
	@Autowired
	private DeptManager                 deptManager;
	@Autowired
	private EnterprisePermissionManager enterprisePermissionManager;
	
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private LingLingManager lingLingManager;

	@Autowired
	private OrderDinnerSetManager orderDinnerSetManager;

	@Override
	public String saveUpdateUserInfo(AppUserInputDto appUserInputDto,
									 String userId, String addimgUrls, String imageUrlids, String removeUrlids) throws Exception {
		if (appUserInputDto.getIntegral() == null) {
			appUserInputDto.setIntegral(0);
		}
		if (appUserInputDto.getIntegral().intValue() < 0) {
			return "integral";
		}
		if (appUserInputDto.getUserType() == null || appUserInputDto.getUserType() == 0) {
			appUserInputDto.setUserType(2);
		}
		UserImageInfo       adduserImageInfo  = null;
		Map<String, Object> paramMap          = new HashMap<String, Object>();
		List<Integer>       pohto_ids         = new ArrayList<Integer>();
		List<UserImageInfo> userImageInfoList = new ArrayList<UserImageInfo>();
		boolean             flag              = true;

		AppUser user = new AppUser();

		if (appUserInputDto != null && StringUtils.isBlank(appUserInputDto.getId())) {
			// 新增操作
			// 新增时需要判断
			AppUser cons = appUserManager.getAppUsersByPhoneAndOrg(appUserInputDto.getMobilePhone(), String.valueOf(appUserInputDto.getOrgId()), "");

			// userType用户类型 -1-π平台用户 0-普通白名单用户 2-被禁用的白名单用户
			if (cons != null && !StringUtil.isEqual("-1", cons.getUserType())) {
				// 1.如果用户存在,并且用户不是低权限用户,即 userType为0或者2或者为空,则提示用户已经存在
				return "isExist";
			} else if (cons != null && StringUtil.isEqual("-1", cons.getUserType())) {
				// 2.如果用户存在,但是用户类型是低权限用户,即π平台登录注册的用户,即 userType 为-1,则只需要升级为白名单用户
				user = cons;
				// 修改userType
				user.setUserType("0");
				// 置空wxUserId
				user.setWxUserId(null);
			} else {
				// 3.不存在该用户,新建
				user = new AppUser();
			}

			if (StringUtils.isNotEmpty(appUserInputDto.getOrgId())) {
				user.setOrganizationId(Integer.parseInt(appUserInputDto.getOrgId()));
			}
			user.setRoleType(String.valueOf(appUserInputDto.getUserType()));
			if (StringUtils.isNotEmpty(appUserInputDto.getDeptid())) {
				user.setDepartmentId(Integer.parseInt(appUserInputDto.getDeptid()));
			}
			user.setVirtualArchId(appUserInputDto.getVirtualArchId());
			user.setIsEnabled("1");
			user.setAddress(appUserInputDto.getDinnerAddress());
			user.setCreator(userId);
			user.setDepartmentName(appUserInputDto.getDeptStr());
			user.setIntegral(appUserInputDto.getIntegral());
			user.setUserName(appUserInputDto.getUserName());
			String userNum = String.format("%08d", appUserManager.getUserNumer());
			user.setUserNumber(userNum);
			user.setUserSex(appUserInputDto.getUserSex());
			user.setEmail(appUserInputDto.getEmail());

			user.setUserMobile(appUserInputDto.getMobilePhone());
			user.setCreateTime(new Date());
			user.setIsBinding(0);
			user.setIsLogin(0);
			user.setUserType("0");
			user.setStatus("1");//后台添加默认已审核
			user.setVirPermId(appUserInputDto.getVirPermId());
			user.setIsPushState(appUserInputDto.getPushState());
		} else {
			// 修改操作
			user = appUserManager.get(Integer.parseInt(appUserInputDto.getId()));
			if (user != null) {

				//需要记录该积分流转（首先获取原有的积分，记录下来，然后再判断现在的积分和原有的积分是否有差异，有差异才进行修改记录）
				int inte = 0;
				if (null != user.getIntegral()) {
					inte = user.getIntegral();
				}
				if (appUserInputDto.getIntegral() != null && inte != appUserInputDto.getIntegral().intValue()) {
					String exchangeIntegral = String.valueOf(appUserInputDto.getIntegral() - user.getIntegral());
					IntegralRecodeInfo recode = new IntegralRecodeInfo(userId, 2, appUserInputDto.getUserName(), appUserInputDto.getMobilePhone()
							, user.getIntegral(), appUserInputDto.getIntegral(), new Date(), exchangeIntegral, appUserInputDto.getOrgId(), user.getId().toString());
					integralRecodeInfoManager.save(recode);
				}

				if (StringUtils.isNotEmpty(appUserInputDto.getOrgId())) {
					user.setOrganizationId(Integer.parseInt(appUserInputDto.getOrgId()));
				}
				user.setRoleType(String.valueOf(appUserInputDto.getUserType()));
				if (StringUtils.isNotEmpty(appUserInputDto.getDeptid())) {
					user.setDepartmentId(Integer.parseInt(appUserInputDto.getDeptid()));
				} else {
					user.setDepartmentId(null);
				}
				user.setVirtualArchId(appUserInputDto.getVirtualArchId());
				user.setAddress(appUserInputDto.getDinnerAddress());
				user.setDepartmentName(appUserInputDto.getDeptStr());
				user.setIntegral(appUserInputDto.getIntegral());
				user.setUserName(appUserInputDto.getUserName());
				user.setModifier(userId);
				user.setVirPermId(appUserInputDto.getVirPermId());

				if (!StringUtil.isNotEmpty(user.getUserNumber())) {
					String userNum = String.format("%08d", appUserManager.getUserNumer());
					user.setUserNumber(userNum);
				}
				user.setUserSex(appUserInputDto.getUserSex());
				user.setEmail(appUserInputDto.getEmail());

				// 如果手机号发生更改,则将用户状态置为下线状态
				if (!user.getUserMobile().trim().equalsIgnoreCase(appUserInputDto.getMobilePhone().trim())) {
					user.setIsLogin(0);
					user.setIsBinding(0);
				}
				user.setUserMobile(appUserInputDto.getMobilePhone());
				user.setIsPushState(appUserInputDto.getPushState());
			}
		}

		//人脸图片处理
		//新增图片操作
		CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + user.getVirtualArchId());

		if (StringUtils.isNotBlank(imageUrlids)) {
			String imageUrlId[] = getStr(imageUrlids);
			for (String str : imageUrlId) {
				if (StringUtils.isNotBlank(str)) {
					UserImageInfo userImageInfo = visitorInFoManager.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;
								log.info("ConsumerUserServiceImpl saveUserInfo imageUrlids ========>上传图片失败");
								break;
							}
							userImageInfo.setImageFacePlusId(faceImageId);
							pohto_ids.add(faceImageId);
						}
//						visitorInFoDao.updateObj(userImageInfo);
						visitorInFoManager.updateModel(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;
							log.info("ConsumerUserServiceImpl saveUserInfo addimgUrls ========>上传图片失败");
							break;
						}
						adduserImageInfo.setImageFacePlusId(faceImageId);
						pohto_ids.add(faceImageId);
					}
					adduserImageInfo.setImageUrl(str);
					userImageInfoList.add(adduserImageInfo);
				}
			}
		}
		//上传用户信息或更新用户信息(人脸)
		if (pohto_ids.size() > 0) {
			//flag = appUserManager.assignOperateForFace(user, "1", pohto_ids);
		}
		if (flag) {
			//删除人脸图片操作
			if (StringUtils.isNotBlank(removeUrlids)) {
				String removeImagUrlId[] = getStr(removeUrlids);
				for (String str : removeImagUrlId) {
					if (StringUtils.isNotBlank(str)) {
						UserImageInfo userImageInfo = visitorInFoManager.getUserImageInfoById(Integer.parseInt(str));
						visitorInFoManager.remove(userImageInfo);
					}
				}
			}
			if (appUserInputDto != null && StringUtils.isBlank(appUserInputDto.getId())) {
				// 新增操作
				Integer usId = appUserManager.saveOrUpdateAppUser(user);
//				setPushState(usId,appUserInputDto.getPushState());
				//需要记录该积分流转(充值记录)
				if (appUserInputDto.getIntegral() != null && appUserInputDto.getIntegral() >= 0) {
					if (appUserManager.exists(usId)) {
						user = appUserManager.get(usId);
						if (user != null) {
							String exchangeIntegral = String.valueOf(appUserInputDto.getIntegral());
							IntegralRecodeInfo recode = new IntegralRecodeInfo(userId, 1, appUserInputDto.getUserName(), appUserInputDto.getMobilePhone()
									, 0, appUserInputDto.getIntegral(), new Date(), exchangeIntegral, appUserInputDto.getOrgId(), user.getId().toString());
							integralRecodeInfoManager.save(recode);
						}
					}
				}
				//保存图片
				for (UserImageInfo userImageInfo : userImageInfoList) {
					userImageInfo.setImageType("1");
					userImageInfo.setUserId(user.getId());
					visitorInFoManager.save(userImageInfo);
				}

				//保存用户头像
				if (user != null) {
					//同步更新user到kafka（商城和超级前台）
					//发送到消息通道，同步到子系统
					kafkaOuterService.syncUser(user);
					return "success";
				} else {
					return "fail";
				}
			} else if (appUserInputDto != null && StringUtils.isNotBlank(appUserInputDto.getId())) {
				//修改操作
				if (user != null) {

					try {
						Integer usId = appUserManager.saveOrUpdateAppUser(user);

//						setPushState(usId,appUserInputDto.getPushState());
						//C端认证后 修改企业 修改绑定的企业账号
						if (null != user.getWxUserId()) {
							if (scWxuserManager.exists(user.getWxUserId())) {
								WxUser wxUser = scWxuserManager.get(user.getWxUserId());
								if (null != wxUser && StringUtils.isNotEmpty(wxUser.getOpenId())) {
									updateUserAccount(user.getOrganizationId().toString(), user.getVirtualArchId(), wxUser.getOpenId());
								}
							}
						}


						//保存图片
						for (UserImageInfo userImageInfo : userImageInfoList) {
							userImageInfo.setImageType("1");
							userImageInfo.setUserId(user.getId());
							visitorInFoManager.save(userImageInfo);
						}
						//同步更新user到kafka（商城和超级前台）
						//发送到消息通道，同步到子系统
						kafkaOuterService.syncUser(user);
						return "true";
					} catch (Exception e) {
						log.error(e.getMessage());
						e.printStackTrace();
						return "fail";
					}
				}
			}

		}
		return "fail";
	}

//	private void setPushState(Integer userId,String pushState){
//		if(null == userId){
//			return;
//		}
//		if(StringUtils.isEmpty(pushState)){
//			pushState = "1";
//		}
//		OrderDinnerSet set = orderDinnerSetManager.findByUserId(userId);
//		if(null == set){
//			set = new OrderDinnerSet();
//			set.setUserId(userId);
//			set.setStatus(pushState);
//			orderDinnerSetManager.saveModel(set);
//		}else{
//			set.setStatus(pushState);
//			orderDinnerSetManager.updateModel(set);
//		}
//	}

	@Override
	public String setFaceImage(AppUser user, String addimgUrls, String imageUrlids, String removeUrlids) {
		String              res               = "fail";
		UserImageInfo       adduserImageInfo  = null;
		Map<String, Object> paramMap          = new HashMap<String, Object>();
		List<Integer>       pohto_ids         = new ArrayList<Integer>();
		List<UserImageInfo> userImageInfoList = new ArrayList<UserImageInfo>();
		boolean             flag              = true;

		try {
			//人脸图片处理
			//新增图片操作
			CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + user.getVirtualArchId());
			//保存人脸图片到本地数据库中
			if (StringUtils.isNotBlank(imageUrlids)) {
				String imageUrlId[] = getStr(imageUrlids);
				for (String str : imageUrlId) {
					if (StringUtils.isNotBlank(str)) {
						UserImageInfo userImageInfo = visitorInFoManager.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;
									log.info("ConsumerUserServiceImpl saveUserInfo imageUrlids ========>上传图片失败");
									break;
								}
								userImageInfo.setImageFacePlusId(faceImageId);
								pohto_ids.add(faceImageId);
							}
							visitorInFoManager.updateModel(userImageInfo);
						}
					}
				}
			}
			//将人脸图片同步到face++方
			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;
								log.info("ConsumerUserServiceImpl saveUserInfo addimgUrls ========>上传图片失败");
								break;
							}
							adduserImageInfo.setImageFacePlusId(faceImageId);
							pohto_ids.add(faceImageId);
						}
						adduserImageInfo.setImageUrl(str);
						userImageInfoList.add(adduserImageInfo);
					}
				}
			}

			//上传用户信息或更新用户信息(人脸)
			if (pohto_ids.size() > 0) {
				//flag = appUserManager.assignOperateForFace(user, "1", pohto_ids);
			}
			if (flag) {
				//删除人脸图片操作
				if (StringUtils.isNotBlank(removeUrlids)) {
					String removeImagUrlId[] = getStr(removeUrlids);
					for (String str : removeImagUrlId) {
						if (StringUtils.isNotBlank(str)) {
							UserImageInfo userImageInfo = visitorInFoManager.getUserImageInfoById(Integer.parseInt(str));
							visitorInFoManager.remove(userImageInfo);
						}
					}
				}
				//修改操作
				if (user != null) {

					Integer usId = appUserManager.saveOrUpdateAppUser(user);
					//C端认证后 修改企业 修改绑定的企业账号
					if (null != user.getWxUserId()) {
						if (scWxuserManager.exists(user.getWxUserId())) {
							WxUser wxUser = scWxuserManager.get(user.getWxUserId());
							if (null != wxUser && StringUtils.isNotEmpty(wxUser.getOpenId())) {
								updateUserAccount(user.getOrganizationId().toString(), user.getVirtualArchId(), wxUser.getOpenId());
							}
						}
					}

					//保存图片
					for (UserImageInfo userImageInfo : userImageInfoList) {
						userImageInfo.setImageType("1");
						userImageInfo.setUserId(user.getId());
						visitorInFoManager.save(userImageInfo);
					}
				}
			}
			res = "success";
		} catch (Exception e) {
			log.error("修改用户人脸识别信息失败:" + e.getMessage());
			e.printStackTrace();
			res = "fail";
		}
		return res;
	}


	/**
	 * 个人时 同步且绑定企业账号
	 *
	 * @param orgId
	 * @param openId
	 * @throws Exception
	 */
	private void updateUserAccount(String orgId, Integer virtualArchId, String openId) throws Exception {

		String         virtualId = "";
		Long           accId     = null;
		TbOrganization org       = organizationManager.getOrganizationById(Integer.parseInt(orgId));
		if (null != org && org.getAccountType() == 1) {

			VirtualArchitecture vir = virtualArchManager.get(virtualArchId);
			if (null != vir) {
				List<VirtualAccount> listAS = virtualAccountManager.getVirAccountByVirId(vir.getId());
				if (listAS.size() >= 1) {
					VirtualAccount va = listAS.get(0);
					virtualId = va.getId().toString();
					accId = va.getId();
				}
			}
		}

		//先删除 旧登录记录
		List<UserAccountRecode> atRecodeList = userAccountManager.getUserAccountRecode(orgId, openId);
		for (UserAccountRecode recode : atRecodeList) {
			userAccountManager.remove(recode.getId());
		}

		//在重新保存
		if (StringUtils.isNotEmpty(virtualId) && null != accId) {
			List<UserAccountRecode> userAccList = userAccountManager.getUserAccountByAccount(orgId, virtualId, openId);
			if (userAccList != null && userAccList.size() > 0) {//如果有记录修改记录
				UserAccountRecode userAcc = userAccList.get(0);
				userAcc.setModifier(openId);
				userAcc.setModifyTime(new Date());
				userAcc.setIsOnline("2");
				userAcc.setOrgId(orgId);
				userAccountManager.updateModel(userAcc);

			} else {//如果没记录需要新增记录
				UserAccountRecode userAcc = new UserAccountRecode();
				userAcc.setAccountId(accId);
				userAcc.setIsOnline("2");
				userAcc.setOpenId(openId);
				userAcc.setUserId("");
				userAcc.setOrgId(orgId);
				userAcc.setCreateTime(new Date());
				userAcc.setCreator(openId);
				userAcc = userAccountManager.save(userAcc);

			}
		}
	}

	@Override
	public boolean updateUserInfo(AppUserInputDto appUserInputDto, String userId) throws Exception {

		boolean isExist = appUserManager.exists(Integer.parseInt(appUserInputDto.getId()));
		if (!isExist) return false;
		AppUser user = appUserManager.get(Integer.parseInt(appUserInputDto.getId()));
		if (user != null) {
			if (StringUtils.isNotEmpty(appUserInputDto.getOrgId())) {
				user.setOrganizationId(Integer.parseInt(appUserInputDto.getOrgId()));
			}
			user.setRoleType(String.valueOf(appUserInputDto.getUserType()));
			if (StringUtils.isNotEmpty(appUserInputDto.getDeptid())) {
				user.setDepartmentId(Integer.parseInt(appUserInputDto.getDeptid()));
			}
			user.setAddress(appUserInputDto.getDinnerAddress());
			user.setDepartmentName(appUserInputDto.getDeptStr());
			user.setIntegral(appUserInputDto.getIntegral());
			user.setUserName(appUserInputDto.getUserName());
			user.setModifier(userId);
			user.setUserMobile(appUserInputDto.getMobilePhone());
			//需要记录该积分流转（首先获取原有的积分，记录下来，然后再判断现在的积分和原有的积分是否有差异，有差异才进行修改记录）
			if (appUserInputDto.getIntegral() != null && user.getIntegral() != appUserInputDto.getIntegral()) {
				String exchangeIntegral = String.valueOf(appUserInputDto.getIntegral() - user.getIntegral());
				IntegralRecodeInfo recode = new IntegralRecodeInfo(userId, 2, appUserInputDto.getUserName(), appUserInputDto.getMobilePhone()
						, user.getIntegral(), appUserInputDto.getIntegral(), new Date(), exchangeIntegral, appUserInputDto.getOrgId(), userId);
				integralRecodeInfoManager.save(recode);
			}
			try {
				appUserManager.saveOrUpdateAppUser(user);
				return true;
			} catch (Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	@Override
	public AppResultDto importUserInfo(String orgId, String virId, InputStream ins, String userId)
			throws Exception {
		Map<String, Object> map      = consumerManager.importConsumer(ins, orgId, virId);
		int                 bugCount = Integer.parseInt(map.get("bugCount").toString());
		if (bugCount > 0) {//如果bug数量大于0，说明有异常，直接返回异常即可
			return AppResultUtil.createErrorDto("100", map.get("bugStr").toString());
		} else {//否则的话就将用户信息保存到数据库表中
			if (map.containsKey("userList") && map.containsKey("usersList")) {
				List<AppUser> list      = (List<AppUser>) map.get("userList");
				List<AppUser> usersList = (List<AppUser>) map.get("usersList");
				try {
					if (list != null && list.size() > 0) {
						String res = consumerManager.saveImportUser(list, userId);//保存用户信息
						if ("SUCCESS".equals(res)) {
							//同步更新user到kafka（商城和超级前台）
							//发送到消息通道，同步到子系统
							for (AppUser user : list) {
								kafkaOuterService.syncUser(user);
							}
							return AppResultUtil.createSuccesDto(map.get("countStr").toString(), null);
						} else {
							return AppResultUtil.createErrorDto("100", "保存导入用户数据失败：(DinnerUserServiceImpl/importUserInfo)" + res);
						}
					}
					if (usersList != null && usersList.size() > 0) {
						return AppResultUtil.createSuccesDto(map.get("countStr").toString(), null);
					}
					return AppResultUtil.createErrorDto("100", "导入的模板有误");
				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
					return AppResultUtil.createErrorDto("100", "导入用户数据失败：DinnerUserServiceImpl/importUserInfo：" + e.getMessage());
				}
			} else {
				return AppResultUtil.createErrorDto("100", "导入用户数据失败：获取不到userList");
			}
		}
	}

	/**
	 * 根据openId获取用户
	 *
	 * @param orgId
	 * @param openId
	 * @return
	 */
	@Override
	public Consumer getConsumerByOpenId(String orgId, String openId) {
		return consumerManager.getConsumerByOpenId(orgId, openId);
	}

	/**
	 * 登录
	 *
	 * @param openId
	 * @param orgId
	 * @return
	 */
	@Override
	public AppResultDto login(String mobile, String code, String openId,
							  String orgId) {
		Map<String, Object> map  = new HashMap<String, Object>();
		Consumer            cust = consumerManager.getConsumerByMobile(orgId, mobile);
		if (cust == null) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "账号不存在，请联系管理员开通订餐账号");
		} else {
			if ("1".equals(cust.getIsEnabled())) {
				cust.setModifier(openId);
				cust.setModifyTime(new Date());
				cust.setOpenId(openId);
				consumerManager.updateModel(cust);
				map.put("consumer", cust);
			} else {
				return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "账号不存在，请联系管理员开通订餐账号");
			}
		}
		if (StringUtils.isEmpty(cust.getUserName())) {
			map.put("isFirstLogin", 1);
		} else {
			map.put("isFirstLogin", 0);
		}
		return AppResultUtil.createSuccesDto(map);
	}

	/**
	 * 退出登录
	 */
	@Override
	public String exitLogin(String openId, String orgId) {
		String   res  = "FAIL";
		Consumer cust = getConsumerByOpenId(orgId, openId);
		if (cust != null) {
			cust.setModifier(openId);
			cust.setModifyTime(new Date());
			cust.setOpenId("");
			consumerManager.updateModel(cust);
			res = "SUCCESS";
		}
		return res;
	}

	/**
	 * 修改用户信息
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public String updateConsumer(ConsumerInputDto dto) {
		String res = "FAIL";
		if (StringUtils.isNotEmpty(dto.getId())) {
			Long id = Long.parseLong(dto.getId());
			if (consumerManager.exists(id)) {
				Consumer cust = consumerManager.get(id);
				cust.setUserName(dto.getUserName());
				cust.setDept(dto.getDept());
				cust.setMobile(dto.getMobile());
				cust.setAddress(dto.getAddress());
				cust.setModifier(dto.getOpenId());
				cust.setModifyTime(new Date());
				consumerManager.updateModel(cust);
				res = "SUCCESS";
			}
		}
		return res;
	}

	/**
	 * 修改密码
	 *
	 * @param id
	 * @param openId
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@Transactional
	public String updatePassword(String id, String openId, String oldPassword,
								 String newPassword) {
		String res = "";
		if (StringUtils.isNotEmpty(id)) {
			Long custId = Long.parseLong(id);
			if (consumerManager.exists(custId)) {
				Consumer cust = consumerManager.get(custId);
			} else {
				res = "找不到该用户";
			}
		} else {
			res = "id为空";
		}
		return res;
	}

	/**
	 * 判断是否有权限再添加订单
	 */
	@Override
	public AppResultDto isConsPower(String orgId, String openId) {
		Consumer cons = consumerManager.getConsumerByOpenId(orgId, openId);
		if (cons == null) {
			return AppResultUtil.createErrorDto("100", "找不到该用户信息");
		}
		int power = consumerManager.isConsPower(cons, 2);
		if (power == 1) {
			return AppResultUtil.createSuccesDto(power);
		} else {
			return AppResultUtil.createErrorDto("100", "每人只能订一份哦！");
		}
	}

	/**
	 * @return
	 */
	@Override
	public Page findList(Map<String, Object> paramets, int pageSize, int pageNo) {
		Page                      page  = consumerManager.findList(paramets, pageSize, pageNo);
		List<Map<String, Object>> items = page.getItems();

		if (!CollectionUtils.isEmpty(items)) {
			for (Map<String, Object> map : items) {
				
				Long virPermId = (Long) map.get("virPermId");
				if (Objects.isNull(virPermId)) {
					map.put("funcListStr", "");// 权限字符串的拼接
				} else {
					String relationStr = enterprisePermissionManager.getVirPermServiceRelationStr(virPermId);
					map.put("funcListStr", relationStr);
				}

			}
		}
		page.setItems(items);
		return page;
	}

	@Override
	public Page findEmployeeList(Map<String, Object> paramets, int pageSize, int pageNo) {
		Page                      page  = consumerManager.findEmployeeList(paramets, pageSize, pageNo);
		List<Map<String, Object>> items = page.getItems();
//		if (items != null && items.size() > 0) {
//			for (Map<String, Object> map : items) {
//				Integer userId  = (Integer) map.get("id");
//				AppUser appUser = appUserManager.get(userId);
//				DevicePermGroup group=lingLingDao.getGroupByUserId(userId);
//				if (null!=group) {
//					map.put("groupName", group.getGroupName());
//				} else {
//					map.put("groupName", null);
//				}
//				if (appUser.getCard() != null) {
//					map.put("cardId", appUser.getCard().getId());
//					map.put("cardCode", appUser.getCard().getCardCode());
//					map.put("cardCreateTime", DateHelper.formatDateToStr(appUser.getCard().getCreateTime()));
//				} else {
//					map.put("cardId", null);
//					map.put("cardCode", null);
//					map.put("cardCreateTime", null);
//				}
//			}
//		}

		page.setItems(items);
		return page;
	}

	/**
	 * 获取用户详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public AppResultDto findById(Integer id) {
		if (appUserManager.exists(id)) {
			AppUser cons = appUserManager.get(id);
			if (cons != null) {
				AppUserDinDto dto = new AppUserDinDto();
				dto.setAddress(StringUtils.isNotBlank(cons.getAddress()) ? cons.getAddress() : "");
				
				DevicePermGroup group=lingLingManager.getGroupByUserId(id);
				if (null != group) {
					dto.setGroupName(group.getGroupName());
				} else {
					dto.setGroupName("");
				}				
				//南昌项目 地址有误的情况下 需要正常发卡
				/*if (StringUtils.isNotBlank(cons.getAddress())){
					String address = cons.getAddress();
					OrgElement OrgEl=elementGroupManager.getOrgElementId(Long.valueOf(address));
					if(OrgEl!=null){
						dto.setAddressStr(OrgEl.getItemname());
					}else{
						Element byItemCode = elementGroupManager.getElementId(Long.valueOf(address));
						if(byItemCode!=null){
							dto.setAddressStr(byItemCode.getItemname());
						}
					}
					
				}*/				
				
				dto.setDept(cons.getDepartmentId() == null ? null : cons.getDepartmentId().toString());
				if (cons.getDepartmentId() != null && StringUtil.isNotEmpty(cons.getDepartmentId().toString()) && deptManager.exists(Long.parseLong(cons.getDepartmentId().toString()))) {
					Department dept = deptManager.get(Long.parseLong(cons.getDepartmentId().toString()));
					if (dept != null) {
						dto.setDeptStr(dept.getName());
					}
				}


				dto.setUserNumber(cons.getUserNumber());
				dto.setUserSex(cons.getUserSex());
				dto.setEmail(cons.getEmail());
				
				dto.setFacePlusImageId(cons.getFacePlusImageId());
				dto.setImageUrl01(cons.getImageUrl01());
				
				
				LingLingCard card=lingLingManager.getCardByUserId(id);
				if (null != card) {
					dto.setCardCreateTime(DateHelper.formatDateToStr(card.getCreateTime()));
					dto.setCardCode(card.getCardCode());
				}				

				dto.setIntegrale(cons.getIntegral());
				dto.setMobile(cons.getUserMobile());
				dto.setRoleType(cons.getRoleType());
				dto.setUserName(cons.getUserName());
				dto.setOrgId(cons.getOrganizationId() == null ? "" : cons.getOrganizationId().toString());
				if (cons.getOrganizationId() != null && StringUtil.isNotEmpty(cons.getOrganizationId().toString())) {
					TbOrganization org = organizationManager.getOrganizationById(cons.getOrganizationId());
					if (org != null) {
						dto.setOrgName(org.getName());
						//0无1face++2令令开门
						dto.setPassType(org.getPassType());
					}
				}
				dto.setVirtualArchId(cons.getVirtualArchId());
				if (cons.getVirtualArchId() != null && StringUtil.isNotEmpty(cons.getVirtualArchId().toString()) && virtualArchManager.exists(cons.getVirtualArchId())) {
					VirtualArchitecture virInfo = virtualArchManager.get(cons.getVirtualArchId());
					if (virInfo != null) {
						dto.setVirName(virInfo.getName());
					}
				}
				//增加充值记录
				List<IntegralRecodeDto> recodeList = integralRecodeInfoManager.getRecodeInfo(cons.getUserMobile(), cons.getOrganizationId() == null ? "" : cons.getOrganizationId().toString());
				dto.setRecodeList(recodeList);
				dto.setServeImgUrl(FileUploadUtils.getVisitPrefix());
				// 查询该员工人脸照片信息
				List<UserImageInfo> list = visitorInFoManager.getUserImageInfo(id, "1");
				if (list != null && list.size() > 0) {
					//为图片拼接前缀
					for (UserImageInfo userImageInfo : list) {
						userImageInfo.setImageUrl(userImageInfo.getImageUrl());
					}
				}
				dto.setFacePicList(list);

				if (!Objects.isNull(cons.getVirPermId())) {
					String relationStr = enterprisePermissionManager.getVirPermServiceRelationStr(cons.getVirPermId());
					dto.setFuncListStr(relationStr);
					VirPermConfig config = enterprisePermissionManager.get(cons.getVirPermId());
					dto.setPermName(config.getName());
					dto.setPermId(config.getId());
				}
//				OrderDinnerSet set = orderDinnerSetManager.findByUserId(id);
//				if(null != set && "0".equals(set.getStatus())){
//					dto.setPushState("0");
//				}else{
//					dto.setPushState("1");
//				}
				dto.setPushState(cons.getIsPushState());
				return AppResultUtil.createSuccesDto(dto);
			}
		}
		return AppResultUtil.createErrorDto("100", "账号不存在");
	}

	/**
	 * 1禁用、2启用、3删除
	 *
	 * @param id
	 * @param type
	 * @return
	 */
	@Override
	public AppResultDto updateConsumer(Integer id, int type, String userId) {
		if (appUserManager.exists(id)) {
			AppUser cons = appUserManager.get(id);
			if (cons != null) {
				cons.setModifier(userId);
				cons.setModifyTime(new Date());
				if (type == 1) {//禁用
					cons.setIsEnabled("0");
					cons.setIsBinding(0);
					cons.setIsLogin(0);
					cons.setUserType("2");// 用户类型 -1-π平台用户 0-普通白名单用户 2-被禁用的白名单用户
					cons.setWxUserId(null);
					appUserManager.saveOrUpdateAppUser(cons);
					// 禁用用户 同时删除其对应的照片信息
					visitorInFoManager.deleteUserImageInfoByUserId(id, "1");
				} else if (type == 2) {//启用
					cons.setUserType("0");// 用户类型 -1-π平台用户 0-普通白名单用户 2-被禁用的白名单用户
					cons.setIsEnabled("1");
					cons.setIsLogin(0);
					cons.setWxUserId(null);
					cons.setIsBinding(0);
					appUserManager.saveOrUpdateAppUser(cons);
				} else if (type == 3) {//删除
					//删除用户需要判断用户是否有存在订单，如果存在不允许删除
				}
				kafkaOuterService.syncUser(cons);
				return AppResultUtil.createSuccesDto();
			}
		}
		return AppResultUtil.createErrorDto("100", "用户不存在");
	}

	/**
	 * 获取所有有效的企业
	 */
	@Override
	public AppResultDto getVirInfo(String orgId) {
		try {
			List<VirInfoDto> list = virtualArchManager.getVirInfoDtoByOrgId(orgId, null);
			return AppResultUtil.createSuccesDto(list);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取企业数据失败:" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业数据失败");
		}
	}

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

	}

	@Override
	public AppResultDto getRechargeSet(String orgId) {
		RechargeSet reSet = rechargeSetManager.findByOrgId(orgId);
		return null;
	}


	@Override
	public AppResultDto getUserNumber(String id) {
		String number = "";
		try {
			//修改时
			if (StringUtil.isNotEmpty(id) && appUserManager.exists(Integer.parseInt(id))) {
				AppUser user = appUserManager.get(Integer.parseInt(id));
				if (user != null && !StringUtil.isNotEmpty(user.getUserNumber())) {
					number = String.format("%08d", appUserManager.getUserNumer());
				}
			} else {//新增时
				number = String.format("%08d", appUserManager.getUserNumer());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("生成工号失败:" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "生成工号失败");
		}
		return AppResultUtil.createSuccesDto(number);
	}

	@Override
	public List<Map<String, Object>> findListForReport(
			Map<String, Object> paramets) {
		
		return consumerManager.findListForReport(paramets);
	}
	
	
	@Override
	public List<IntegralRecodeDto> getAllIntegralRecodeList(
			Map<String, Object> paramets) {
		
		return integralRecodeInfoManager.getRecodeInfoExcelList(paramets);
	}

	@Override
	public WebPageResultDto findListReportExcel(List<Map<String, Object>> list) throws IOException {
		
		String   sheetName = "";
		if (list != null && list.size() > 0) {
			sheetName = "订餐人员账户余额";
			String[] titles     = {"姓名","手机号","企业", "部门","送餐地址","积分余额"};
			String[] fieldNames = {"userName", "mobile","virName", "deptStr", "address", "integral"};
			String   path       = exportExcelData(list, sheetName, titles, fieldNames);
			return new WebPageResultDto("200", "成功", path);
		} else {
			return new WebPageResultDto("100", "数据为空，无法导出", null);
		}
		
	}
	
	@Override
	public WebPageResultDto getAllIntegralRecodeListExcel(List<Map<String, Object>> list) throws IOException {
		
		String   sheetName = "";
		if (list != null && list.size() > 0) {
			sheetName = "订餐人员账户余额";
			String[] titles     = {"时间","类型","积分", "操作人","最新余额"};
			String[] fieldNames = {"createTime", "opTypeStr","exchangeIntegral", "creatorName", "newIntgrale"};
			String   path       = exportExcelDataRecodeExcel(list, sheetName, titles, fieldNames);
			return new WebPageResultDto("200", "成功", path);
		} else {
			return new WebPageResultDto("100", "数据为空，无法导出", null);
		}
		
	}
	
	public String exportExcelDataRecodeExcel(List<Map<String, Object>> list, String sheetName, String[] titles, String[] fieldNames) throws IOException {
		HSSFWorkbook wb   = new HSSFWorkbook();
		String       path = setPath("upload/Integral.xls");
		File         file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);

		ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames);
		return path;
	}
	
	
	public String exportExcelData(List<Map<String, Object>> list, String sheetName, String[] titles, String[] fieldNames) throws IOException {
		HSSFWorkbook wb   = new HSSFWorkbook();
		String       path = setPath("upload/Recode.xls");
		File         file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);

		ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames);
		return path;
	}
	
	
	@Override
	public String setPath(String fileName) {
		String classpath = getClass().getResource("/").getPath();
		log.info("begin exportExcel  classpath:" + classpath);
		if (StringUtils.isNotEmpty(classpath)) {
			log.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
			if ("dev".equals(CLIENTNO)) {
				String str = classpath.substring(0, 1);
				if ("/".equals(str)) {
					classpath = classpath.replaceFirst("/", "");
				}
			}
		}
		log.info("path:" + classpath);
		String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
		log.info("path:" + webappRoot);
		//"upload/OrderExcel.xls"
		String path = webappRoot + fileName;
		if (StringUtils.isNotEmpty(path)) {
			path = path.replace("//", "/");
		}

		log.info("path:" + path);
		return path;
	}

	@Override
	public AppResultDto importUserAddress(String orgId, InputStream ins, String userId){
		Map<String, Object> map      = consumerManager.importUserAddress(ins, orgId);
		int                 bugCount = Integer.parseInt(map.get("bugCount").toString());
		if (bugCount > 0) {//如果bug数量大于0，说明有异常，直接返回异常即可
			return AppResultUtil.createErrorDto("100", map.get("bugStr").toString());
		} else {//否则的话就将用户信息保存到数据库表中
			if (map.containsKey("userList")) {
				List<AppUser> list      = (List<AppUser>) map.get("userList");
				try {
					if (list != null && list.size() > 0) {
						for(AppUser user : list){
							if(null == user.getId()){
								continue;
							}
							appUserManager.saveOrUpdateAppUser(user);
						}
					}
					return AppResultUtil.createErrorDto("100", "导入的模板有误");
				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
					return AppResultUtil.createErrorDto("100", "导入用户数据失败：DinnerUserServiceImpl/importUserAddress：" + e.getMessage());
				}
			} else {
				return AppResultUtil.createErrorDto("100", "导入用户数据失败：获取不到userList");
			}
		}
	}
	
}
