package com.palmnest.service.estateserve.release.impl;

import com.palmnest.application.Constants;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.LingLingUtil;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.VisitorInfo;
import com.palmnest.model.lingling.LingLingCurrentset;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.VisitorInFoManager;
import com.palmnest.service.estateserve.release.VisitorInFoService;
import com.palmnest.service.lingling.manager.LingLingCurrentsetManager;
import com.palmnest.service.lingling.manager.LingLingManager;

import com.palmnest.service.property.PropertyManager;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;

@Slf4j
@Service("visitorInFoService")
public class VisitorInFoServiceImpl implements VisitorInFoService {


	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private VisitorInFoManager visitorInFoManager;
	@Autowired
	private LingLingCurrentsetManager lingLingCurrentsetManager;

	@Autowired
	private PropertyManager propertyManager;


	@Override
	public Map<String, Object> saveVisitorUserInfo(HttpServletRequest request,
												   HttpServletResponse response) {

		Map<String, Object> resultMap = null;
		try {
			//选择到访日期
			String startDateTime = request.getParameter("startDateTime");
			//结束日期
			String endDateTime = request.getParameter("endDateTime");

			String leaveTime = request.getParameter("leaveTime");//预计离开时间

			//到访公司名称(访客公司名称)
			String companyName = request.getParameter("companyName");
			//获得需要添加的用户信息
			String arrarId = request.getParameter("arrarId");
			// 如果是员工填写或者员工分享出去的邀请,此openId为员工openId;
			// 如果是访客填写预约,此openId为该访客的openId;
			String openId = request.getParameter("openId");

			String orgId = request.getParameter("orgId");

			//String idenNumber=request.getParameter("idenNumber");		
			//String censusAddr=request.getParameter("censusAddr");		
			//String race=request.getParameter("race");		
			//String police=request.getParameter("police");		

			if(StringUtils.isEmpty(orgId)){
				resultMap = new HashMap<String, Object>();
				resultMap.put("flag", false);
				resultMap.put("desc", "项目参数必传");
				return resultMap;
			}

			String passType = "2";
			TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));
			if(null != organization && StringUtils.isNotEmpty(organization.getPassType())){
				passType = organization.getPassType();
			}
			LingLingCurrentset currentset = lingLingCurrentsetManager.getByOrgId(Integer.parseInt(orgId));
			if(null == currentset){
				currentset = new LingLingCurrentset();
				currentset.setIsLinglingAudit(0);
				currentset.setVisitCompType(1);
				currentset.setVisitedCompType(1);
				currentset.setVisitedMobileType(1);
				currentset.setVisitNameType(1);
			}

			//type 2-员工填写 1-员工分享由访客填写 3-访客自己发起/填写 5-pc访客登记
			String type = request.getParameter("type");


			int virtualArchId = 0;
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(request.getParameter("virtualArchId"))) {
				virtualArchId = Integer.valueOf(request.getParameter("virtualArchId"));//到访公司
			}


			// 欢迎语
			String visitorWelComing = request.getParameter("visitorWelComing");
			// 访客openId
			String visitorOpenId = request.getParameter("visitorOpenId");
			// 访客vistorIdentification
			String visitorIdentification = request.getParameter("visitorIdentification");

			// 被访员工公司
			String employeeCompanyId = request.getParameter("employeeCompanyId");
			// 被访员工手机号
			String employeePhone = request.getParameter("employeePhone");
			// 如果被访人信息是由访客自己填写的,则需要校验被访人信息的真实性

			if ("3".equals(type) && 1 == currentset.getVisitedCompType().intValue() && 1 == currentset.getVisitedMobileType().intValue()) {
				String flag = checkEmployee(employeeCompanyId, employeePhone);
				if (flag.equals(Constants.FAIL_FLAG)) {
					// 不存在该员工
					resultMap = new HashMap<String, Object>();
					resultMap.put("flag", false);
					resultMap.put("desc", "被访人公司或被访人手机号有误");
					//return net.sf.json.JSONObject.fromObject(resultMap).toString();
					return resultMap;
				}
			}

			//拆分ID
			if (StringUtils.isNotBlank(arrarId)) {
				String            strId[] = arrarId.split(",");
				List<VisitorInfo> list    = new ArrayList<VisitorInfo>();
				for (int i = 0; i < strId.length; i++) {
					String      visitorName     = request.getParameter("visitorName" + strId[i]);
					String      visitorPhone    = request.getParameter("visitorPhone" + strId[i]);
					String      imageUrl        = request.getParameter("imageUrl" + strId[i]);
					String      visitorType     = request.getParameter("visitorType" + strId[i]);
					String      showimageUrl    = request.getParameter("showimageUrl" + strId[i]);
					String      imageFacePlusId = request.getParameter("imageFacePlusId" + strId[i]);
					VisitorInfo visitorInfo     = new VisitorInfo();
					
					/*visitorInfo.setIdenNumber(idenNumber);
					visitorInfo.setCensusAddr(censusAddr);
					visitorInfo.setRace(race);
					visitorInfo.setPolice(police);*/

					visitorInfo.setImageUrL(imageUrl);
					visitorInfo.setVisitorName(visitorName);
					visitorInfo.setVisitorType(visitorType);
					visitorInfo.setVisitorPhone(visitorPhone);
					visitorInfo.setVisitorWelcoming(visitorWelComing);
					visitorInfo.setIds(strId[i]);
					if (StringUtils.isNotBlank(imageFacePlusId)) {
						visitorInfo.setImagePlusId(Integer.parseInt(imageFacePlusId));
					}
					visitorInfo.setShowimageUrl(showimageUrl);
					visitorInfo.setVisitorCompanyName(companyName); //type ==5 时 在取下后台的公司地址
					visitorInfo.setVisitorStartTime(DateUtils.StrToDate(startDateTime, "yyyy-MM-dd HH:mm"));
					visitorInfo.setLeaveTime(leaveTime);
					Date time = DateUtils.StrToDate(endDateTime, "yyyy-MM-dd HH:mm");
					visitorInfo.setVisitorEndTime(time);

					if (!"5".equals(type)) {
						visitorInfo.setNodeStr(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm") + "  " + visitorPhone + " 发起访客申请");
					} else {
						User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
						visitorInfo.setNodeStr(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm") + "  " + user.getFullName() + " 登记打印访客单");
					}
					list.add(visitorInfo);
				}
				//员工自己填写邀请的话不需要审核，直接通过
				if ("2".equals(type)) {// 员工自己填写的邀请预约
					resultMap = visitorInFoManager.saveVisitorInfo(list, openId);
					resultMap.put("openId", openId);
					resultMap.put("type", 2);
					resultMap.put("passType", passType);
					//return  net.sf.json.JSONObject.fromObject(resultMap).toString();
					return resultMap;
				}

				if ("5".equals(type)) {// PC访客登记
					resultMap = visitorInFoManager.savePCVisitorInfo(list, virtualArchId, request);
					resultMap.put("openId", openId);
					resultMap.put("type", 5);
					resultMap.put("passType", passType);
					//return  net.sf.json.JSONObject.fromObject(resultMap).toString();
					return resultMap;
				}

				if ("1".equals(type)) {// 员工分享出去的邀请预约
					if (list.size() > 0) {
						list.get(0).setVisitorOpenId(visitorOpenId);
						list.get(0).setVisitorIdentification(visitorIdentification);
					}
					resultMap = visitorInFoManager.saveWeiXinVisitorInfo(list, openId);
					resultMap.put("openId", openId);
					resultMap.put("type", 1);
					resultMap.put("passType", passType);
					//return  net.sf.json.JSONObject.fromObject(resultMap).toString();
					return resultMap;
				}
				if ("3".equals(type)) {// 访客自己在公众号发起的预约

					if (list.size() > 0) {
						list.get(0).setVisitorOpenId(openId);
						list.get(0).setVisitorIdentification(visitorIdentification);
					}
					AppUser appUser = null;
					if(StringUtils.isNotEmpty(employeeCompanyId) && StringUtils.isNotEmpty(employeePhone)){
						appUser = appUserManager.getUserByVicIdAndMobile(Integer.parseInt(employeeCompanyId), employeePhone);
					}

					resultMap = visitorInFoManager.saveVisInfo(list, openId, appUser,Integer.parseInt(orgId));
					resultMap.put("openId", openId);
					resultMap.put("type", 3);
					resultMap.put("passType", passType);
					//return  net.sf.json.JSONObject.fromObject(resultMap).toString();
					return resultMap;
				}
			}
		} catch (Exception e) {
			resultMap = new HashMap<String, Object>();
			resultMap.put("flag", false);
			resultMap.put("desc", "提交失败，请稍候在试！");
			System.out.println("提交失败 saveVisitorUserInfo=====>");
			e.printStackTrace();
			//log.error("redirectFacePlusInfo:" + e.getMessage());
		}
		//return net.sf.json.JSONObject.fromObject(resultMap).toString();
		return resultMap;

	}


	/**
	 * 校验该公司下是否有该用户
	 *
	 * @param employeeCompanyId
	 * @param employeePhone
	 * @return
	 */
	private String checkEmployee(String employeeCompanyId, String employeePhone) {
		if (org.apache.commons.lang3.StringUtils.isAnyBlank(employeeCompanyId, employeePhone)) {
			return Constants.FAIL_FLAG;
		}
		// 根据企业id和员工电话查询白名单用户
		AppUser appUser = appUserManager.getWhiteUserByMobileAndVirt(Integer.parseInt(employeeCompanyId), employeePhone);
		if (appUser != null) {
			return Constants.SUCCESS_FLAG;
		}
		return Constants.FAIL_FLAG;
	}
}
