package com.palmnest.webapp.controller.wechat;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.core.util.LingLingUtil;
import com.palmnest.application.core.util.PushMessageUtils;
import com.palmnest.application.dto.UserTokenDto;
import com.palmnest.application.dto.input.LingLingVisitorMachineInputDto;
import com.palmnest.application.dto.output.lingling.LingLingResultDto;
import com.palmnest.application.dto.output.lingling.LingLingResultUtil;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.VisitorOrder;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.lingling.manager.LingLingManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.redis.BaseRedisService;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 黄笑天
 * @Description 微信端令令接口
 * @Date 2018/12/10 18:32
 **/
@Slf4j
@Controller
@RequestMapping(value = "/wechat/lingling")
public class LingLingWechatController {


	@Autowired
	private ScWxuserManager scWxuserManager;
	@Autowired
	private AppUserManager  userManager;
	@Autowired
	private PropertyManager propertyManager;
	@Autowired
	private LingLingManager lingLingManager;
	@Autowired
	private BaseRedisService                baseRedisService;

	/**
	 * 生成员工二维码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/createQrCode")
	@ResponseBody
	public AppResultDto createQrCode(HttpServletRequest request) {
		long createTime=System.currentTimeMillis();
		log.info("LingLingWechatController-createQrCode-业主请求开始时间:"+createTime);
		String userToken = request.getParameter("userToken");
		String userIds = request.getParameter("userId");
		log.info("createQrCode-userToken:"+userToken);
		if (StringUtils.isBlank(userToken) && StringUtils.isBlank(userIds)) {
			return AppResultUtil.createErrorDto("500", "用户未登录,请重新登录");
		}
		Integer userId=null;
		if(StringUtils.isNotBlank(userToken)){
			long beginTime=System.currentTimeMillis();
			log.info("LingLingWechatController-createQrCode-业主userToken开始时间:"+beginTime);
			String url1=LingLingUtil.uset_token;
			log.info("createQrCode-url1:"+url1);
			userId=getUserIdByUserToken(userToken,url1);
			log.info("LingLingWechatController-createQrCode-业主userToken-userId1:"+userId);
			if(null == userId){
				String url2=LingLingUtil.uset_token;
				userId=getUserIdByUserToken(userToken,url2);
				log.info("LingLingWechatController-createQrCode-业主userToken-userId2:"+userId);
			}
			long endTime=System.currentTimeMillis();
			log.info("LingLingWechatController-createQrCode-业主userToken结束时间:"+endTime);
			log.info("LingLingWechatController-createQrCode-业主userToken计算时间:"+(endTime-beginTime));
		}else{
			userId=Integer.parseInt(userIds);
		}
		log.info("createQrCode-userId:"+userId);
		if(null == userId){
			return AppResultUtil.createErrorDto("500", "用户未登录,请重新登录");
		}
		// 根据用户查询用户所属权限组下的设备列表
		AppUser appUser = userManager.get(userId);
		Map<String, Object> userGroupMap=lingLingManager.getUserGroupInfo(appUser.getId());
		
		if (appUser == null || null==userGroupMap || (null != appUser && !"0".equals(appUser.getUserType())) ) {
			// 权限组为员工权限组
			return AppResultUtil.createErrorDto("100", "用户不存在或者用户权限组为空");
		}
		
		if (!userGroupMap.containsKey("groupId") || !userGroupMap.containsKey("groupType") ||null == userGroupMap.get("groupId")) {
			// 权限组为员工权限组
			return AppResultUtil.createErrorDto("100", "用户不存在或者用户权限组为空");
		}
		
		if(StringUtils.isBlank(userGroupMap.get("groupType").toString()) || 1 != Integer.parseInt(userGroupMap.get("groupType").toString())){
			return AppResultUtil.createErrorDto("100", "用户不存在或者用户权限组为空");
		}
		Long groupId=Long.parseLong(userGroupMap.get("groupId").toString());
		
		AppResultDto dto=lingLingManager.createQrCode(appUser,groupId);
		long createEndTime=System.currentTimeMillis();
		log.info("LingLingWechatController-createQrCode-业主请求结束时间:"+createEndTime);
		return dto;
	}
	
	private Integer getUserIdByUserToken(String userToken,String url){
		Integer userId=null;
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("userToken", userToken);
		String params=HttpKit.getParamString(map);
		try {
			String     result = HttpKit.HttpPost(params, url);
			if(StringUtils.isBlank(result)){
				return userId;
			}
			
			JSONObject jsonObj=JSONObject.parseObject(result);
			if(!jsonObj.containsKey("code") || 200 != jsonObj.getInteger("code") || !jsonObj.containsKey("data") || null == jsonObj.getObject("data", UserTokenDto.class)){
				return userId;
			}
			UserTokenDto dto=jsonObj.getObject("data", UserTokenDto.class);
			userId=dto.getUserId();
		} catch (Exception e) {
			e.printStackTrace();
			return userId;
		}
		return userId;
	}
	


	/**
	 * 首页获取员工二维码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/indexQrCode")
	public ModelAndView indexQrCode(HttpServletRequest request) {

		ModelAndView model  = new ModelAndView();
		String       openId = request.getParameter("openId");
		try{
			if (StringUtils.isNotBlank(openId)) {

				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
				if(null == wxUser || null == wxUser.getOrganizationId()){
					model.setViewName("wechat/indexQrCode");
					return model;
				}

				// 这个就是tb_user
				AppUser user = userManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());

				TbOrganization organization = propertyManager.getTbOrganizationById(wxUser.getOrganizationId());

				model.addObject("passType", organization.getPassType());

				// 该用户所属企业必须是令令二维码开门方式,并且该用户处于登录状态才可以获取
				// 1.企业通行方式必须为二维码通行
				// 2.用户必须登录
				// 3.用户类型必须为白名单用户
				if (organization != null && organization.getPassType().contains("2")
						&& user != null && user.getIsLogin() == 1 && "0".equals(user.getUserType())) {
					model.addObject("userId", user.getId());
				}
			}
			model.setViewName("wechat/indexQrCode");
			return model;
		}catch(Exception e){
			model.setViewName("wechat/indexQrCode");
			return model;
		}
	}
	
	/**
	 * 批量新增设置用户通行权限
	 * 指定权限组
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addUserPerm")
	@ResponseBody
	public AppResultDto addUserPerm(HttpServletRequest request) {

		String userIds = request.getParameter("userIds");
		String addUserId = request.getParameter("addUserId");
		if(StringUtils.isBlank(userIds)||StringUtils.isBlank(addUserId)){
			return AppResultUtil.createErrorDto("100", "未获取到用户id");
		}
		log.info("addUserPerm:userIds"+userIds);
		log.info("addUserPerm:addUserId"+addUserId);

		try {
			String str=lingLingManager.updateUserPermNextNew(userIds,Integer.parseInt(addUserId));
			log.info("addUserPerm:msg-"+str);
			if(StringUtils.isEmpty(str)){
				return AppResultUtil.createSuccesDto();
			}
			return AppResultUtil.createErrorDto("100", "设置失败:"+str);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("LingLingController setUserPerm===============>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "设置失败");
		}
	}
	
	
	@RequestMapping(value = "/findByOrgId")
	@ResponseBody
	public AppResultDto findByOrgId(HttpServletRequest request) {

		String orgId = request.getParameter("orgId");
		log.info("findByOrgId:orgId"+orgId);

		try {
			Integer orgIdInt=null;
			if(StringUtils.isNotBlank(orgId)){
				orgIdInt=Integer.parseInt(orgId);
			}
			return AppResultUtil.createSuccesDto(lingLingManager.findByOrgId(orgIdInt));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("LingLingController findByOrgId===============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "失败");
	}
	
	
	@RequestMapping(value = "/delDeveloper")
	@ResponseBody
	public AppResultDto delDeveloper(HttpServletRequest request) {

		String key = request.getParameter("key");
		log.info("delDeveloper:key"+key);
		try {
			if("ALL".equals(key)){
				baseRedisService.delKeyLike(CodeConstants.LINGLING_DEVELPER);
			}else{
				baseRedisService.dele(CodeConstants.LINGLING_DEVELPER+"_"+key);
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("LingLingController delDeveloper===============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "失败");
	}
	
	@RequestMapping(value = "/test")
	@ResponseBody
	public AppResultDto test(HttpServletRequest request) {
		//String deviceNo,String alertTitle, String alertBody
		String deviceNo = request.getParameter("deviceNo");
		String alertTitle = request.getParameter("alertTitle");
		String alertBody = request.getParameter("alertBody");
		try {
			PushMessageUtils.pushIosMsg(deviceNo, alertTitle, alertBody);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("LingLingController delDeveloper===============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "失败");
	}
}
