package com.palmnest.webapp.controller.lingling;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.core.util.LingLingUtil;
import com.palmnest.application.dto.input.LingLingVisitorMachineInputDto;
import com.palmnest.application.dto.output.lingling.GetCompanyVO;
import com.palmnest.application.dto.output.lingling.GetNewCompanyVO;
import com.palmnest.application.dto.output.lingling.LingLingResultDto;
import com.palmnest.application.dto.output.lingling.LingLingResultUtil;
import com.palmnest.application.dto.output.lingling.LoginWinVO;
import com.palmnest.application.dto.output.lingling.NewSelectVisitorVO;
import com.palmnest.application.dto.output.lingling.SelectVisitorVO;
import com.palmnest.model.AppUserOrgnizationRelation;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.lingling.manager.LingLingManager;


/**
 * @Author qzy
 * @Description 新版令令访客机控制器======>NEW
 * @Date 2021/01/20
 **/
@Slf4j
@Controller
@RequestMapping(value = "/lingling/VisitorPcPost")
public class LingLingVisitorPcPostMachineController {
	
	
	@Autowired
	private LingLingManager lingLingManager;
	@Autowired
	private UserManager     userManager;	
	@Autowired
	private AppUserManager     appUserManager;
	
	@Autowired
	private VirtualArchManager  virtualArchManager;
	
	
	/**
	 * 访客机接口参数解析
	 *
	 * @param request
	 * @return
	 */
	private JSONObject handleParam(HttpServletRequest request) {

		try {
			String message = request.getParameter("MESSAGE");

			JSONObject jsonObject   = JSONObject.parseObject(message);
			JSONObject requestParam = jsonObject.getJSONObject("requestParam");

            log.info("LingLingVisitorPcPostMachineController handleParam 令令回调参数处理========>params:{}",message);

			return requestParam;
		} catch (Exception e) {
			log.error("LingLingVisitorPcPostMachineController handleParam 令令回调参数处理异常=====>" + e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 客户机用户登录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/loginWin")
	@ResponseBody
	public LingLingResultDto loginWin(HttpServletRequest request) {

		
		//入参
		//account
		//password 
		//deviceCode ==>项目配置 ==>找配置
		
		//statusCode ==1 登陆成功
		//statusCode ==2 账号不存在
		//statusCode ==3 账号或密码错误
		//statusCode ==4 账号和绑定的设备不匹配
		//statusCode ==5 设备不存在			
		
		Map returnMap = new HashMap();
		returnMap.put("data", new HashMap());
		JSONObject requestParam = handleParam(request);

		if (Objects.isNull(requestParam)) {
			returnMap.put("msg", LingLingUtil.PARAM_ANALYSIS_ERROR);
			return LingLingResultUtil.createErrorDto("loginWin", returnMap);
		}

		String account  = requestParam.getString("account");
		String password = requestParam.getString("password");

		if (StringUtils.isAnyBlank(account, password)) {
			returnMap.put("msg", LingLingUtil.PARAM_EMPTY_ERROR);
			return LingLingResultUtil.createErrorDto(LingLingUtil.FAILURE, "loginWin", returnMap);
		}

		log.info("LingLingVisitorMachineController loginWin =====>account:{},password:{}", account, password);

		try {
			User user = userManager.getUser(account, password);
			if (Objects.isNull(user)) {
				returnMap.put("msg", LingLingUtil.ACCOUNT_PASSWORD_ERROR);
				return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_ERROR, "loginWin", returnMap);
			}

			String deviceCode = requestParam.getString("deviceCode");	
			LingLingVisitorMachineInputDto inputDto = lingLingManager.getVisitorMachineByDeviceCode(deviceCode);
			if (Objects.isNull(inputDto)) {
				log.info("loginWin error=======>{}", LingLingUtil.DEVICE_NOT_Exist);
				returnMap.put("msg", LingLingUtil.DEVICE_NOT_Exist);
				return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_DEVICE_NOT_Exist,"loginWin", returnMap);
			}	
			
			// 获取该账户对应项目的访客机设置信息
			List<AppUserOrgnizationRelation> list       = userManager.getUserOrgByUserId(user.getId());			
			if(!list.get(0).getOrgId().equals(inputDto.getOrgId())){
				log.info("loginWin error=======>{}", LingLingUtil.UN_INITIALIZE_MACHINE);
				returnMap.put("msg", LingLingUtil.STATUS_ACCOUNT_DEVICE_MISMATCHING);
				return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_ACCOUNT_DEVICE_MISMATCHING, "loginWin", returnMap);
			}	

			returnMap.put("msg", "登录成功");
			returnMap.put("data", inputDto);
			return LingLingResultUtil.createSuccesDto("loginWin", returnMap);
		} catch (Exception e) {
			log.error("loginWin error=======>", e.getMessage());
			returnMap.put("msg", LingLingUtil.SERVER_ERROR);
			return LingLingResultUtil.createErrorDto("loginWin", returnMap);
		}

	}
	
	
	
	/**
	 * 客户机用户登录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/initVisitorDevice")
	@ResponseBody
	public LingLingResultDto initVisitorDevice(HttpServletRequest request) {

		
		//入参
		//account
		//password 
		//deviceCode ==>项目配置 ==>找配置
		
		//statusCode ==1 登陆成功
		//statusCode ==2 账号不存在
		//statusCode ==3 账号或密码错误
		//statusCode ==4 账号和绑定的设备不匹配
		//statusCode ==5 设备不存在			
		
		Map returnMap = new HashMap();
		returnMap.put("data", new HashMap());
		JSONObject requestParam = handleParam(request);

		if (Objects.isNull(requestParam)) {
			returnMap.put("msg", LingLingUtil.PARAM_ANALYSIS_ERROR);
			return LingLingResultUtil.createErrorDto("initVisitorDevice", returnMap);
		}


		try {

			String deviceCode = requestParam.getString("deviceCode");	
			LingLingVisitorMachineInputDto inputDto = lingLingManager.getVisitorMachineByDeviceCode(deviceCode);
			if (Objects.isNull(inputDto)) {
				log.info("initVisitorDevice error=======>{}", LingLingUtil.UN_INITIALIZE_MACHINE);
				returnMap.put("msg", LingLingUtil.UN_INITIALIZE_MACHINE);
				return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_DEVICE_NOT_Exist,"initVisitorDevice", returnMap);
			}else{
				String machineJson = inputDto.getMachineJson(); 
				log.info("initVisitorDevice machineJson=======>{}", machineJson);
				net.sf.json.JSONObject machineJsonOb = net.sf.json.JSONObject.fromObject(machineJson);
				log.info("initVisitorDevice machineJsonOb=======>{}", machineJsonOb.toString());
				return LingLingResultUtil.createSuccesDto("initVisitorDevice", (Map)com.alibaba.fastjson.JSON.parse(machineJsonOb.toString()) );
			}
		
		} catch (Exception e) {
			log.error("initVisitorDevice error=======>", e.getMessage());
			returnMap.put("msg", LingLingUtil.SERVER_ERROR);
			return LingLingResultUtil.createErrorDto("initVisitorDevice", returnMap);
		}

	}
	
	/**
	 * 获取公司列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getOrganization")
	@ResponseBody
	public LingLingResultDto getOrganization(HttpServletRequest request) {

		
		//入参
		//account
		//password 
		//deviceCode ==>项目配置 ==>找配置
		
		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("getOrganization", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String deviceCode = requestParam.getString("deviceCode");
		//List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(Long.valueOf(userId));
		//if (CollectionUtils.isEmpty(list)) {
		//	return LingLingResultUtil.createErrorDto("getCompany", null);
		//}

		LingLingVisitorMachineInputDto inputDto = lingLingManager.getVisitorMachineByDeviceCode(deviceCode);
		
		if (Objects.isNull(inputDto)) {
			log.info("loginWin error=======>{}", LingLingUtil.UN_INITIALIZE_MACHINE);
			return LingLingResultUtil.createErrorDto("getOrganization", LingLingUtil.UN_INITIALIZE_MACHINE);
		}		
		
		Integer  orgId       = inputDto.getOrgId();
		List<GetNewCompanyVO> companyList = lingLingManager.getNewCompanyList(orgId);
		Map returnMap = new HashMap();
		returnMap.put("msg", "登录成功");
		returnMap.put("data", companyList);
		return LingLingResultUtil.createSuccesDto("getOrganization", returnMap);
	}
	
	/**
	 * 查询被访人信息-用于自动填充
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectInterviewee")
	@ResponseBody
	public LingLingResultDto selectInterviewee(HttpServletRequest request) {

		//参数
		//selectInterviewee send:MESSAGE={"requestParam":{"orgId":"","owner":"17620324486","deviceCode":"E00E0671DB593"}}
		
		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("selectInterviewee", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String employeeCompanyId  = requestParam.getString("orgId");
		String employeePhone = requestParam.getString("owner");
		
		String deviceCode = requestParam.getString("deviceCode");		
		LingLingVisitorMachineInputDto inputDto = lingLingManager.getVisitorMachineByDeviceCode(deviceCode);		
		if (Objects.isNull(inputDto)) {
			log.info("loginWin error=======>{}", LingLingUtil.UN_INITIALIZE_MACHINE);
			return LingLingResultUtil.createErrorDto("selectInterviewee", LingLingUtil.UN_INITIALIZE_MACHINE);
		}		
		
		Integer  orgId       = inputDto.getOrgId();
		
		
		if (StringUtils.isAllBlank(orgId.toString(), employeePhone)) {
			return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_10001, "selectInterviewee", LingLingUtil.PARAM_EMPTY_ERROR);
		}
		log.info("LingLingVisitorPcPostMachineController selectInterviewee =====>orgId:{},employeePhone:{}", orgId, employeePhone);

		try {
	/*		Integer employeeCompanyIdInt = null;
			if(StringUtils.isNotEmpty(employeeCompanyId)){
				employeeCompanyIdInt =  Integer.parseInt(employeeCompanyId);
			}*/
			AppUser appUser = appUserManager.getWhiteUserByMobileAndOrgId(orgId, employeePhone);
			
			Map returnMap = new HashMap();			
			if(null != appUser){
				
				returnMap.put("ownerId", appUser.getId());//被访人 ID
				
				VirtualArchitecture virtualArchitecture = virtualArchManager.get(appUser.getVirtualArchId());
				if(null!=virtualArchitecture && StringUtils.isNotEmpty(virtualArchitecture.getName())){
					returnMap.put("orgName", virtualArchitecture.getName());//组织机构名称
				}else{
					returnMap.put("orgName", "");//组织机构名称
				}				
				returnMap.put("ownerName", appUser.getUserName());//被访人姓名
				returnMap.put("ownerTelephone", appUser.getUserMobile());//被访人电话
			}		
			
			return LingLingResultUtil.createSuccesDto("selectInterviewee", returnMap);
		} catch (Exception e) {
			log.error("selectVisitor error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("selectInterviewee", LingLingUtil.SERVER_ERROR);
		}
	}
	
	
	
	/**
	 * 用于查询之前来访访客的信息-只取当天最近一条数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectVisitorInfo")
	@ResponseBody
	public LingLingResultDto selectVisitorInfo(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("selectVisitorInfo", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}
		String type  = requestParam.getString("type");
		String number  = requestParam.getString("number");
		String telephone  = "";
		String idenNumber = "";
		if("1".equals(type)){//类型，1 证件号，2 手机号，3 访客码
			idenNumber = number;
		}else if("2".equals(type)){
			telephone = number;
		}
		//String telephone  = requestParam.getString("telephone");
		//String idenNumber = requestParam.getString("idenNumber");

		if (StringUtils.isAllBlank(telephone, idenNumber)) {
			return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_10001, "selectVisitorInfo", LingLingUtil.PARAM_EMPTY_ERROR);
		}
		log.info("LingLingVisitorPcPostMachineController selectVisitorInfo =====>telephone:{},idenNumber:{}", telephone, idenNumber);

		try {
			NewSelectVisitorVO visitorVO  = lingLingManager.getNewVisitorInfo(telephone, idenNumber);
			List            resultList = new ArrayList();
			resultList.add(visitorVO);
			return LingLingResultUtil.createSuccesDto("selectVisitorInfo", resultList);
		} catch (Exception e) {
			log.error("selectVisitor error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("selectVisitorInfo", LingLingUtil.SERVER_ERROR);
		}
	}
	

}
