package com.zzwtec.third.action.community;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zzwtec.third.common.*;
import com.zzwtec.third.config.redis.RedisService;
import com.zzwtec.third.model.SysuserCache;
import com.zzwtec.third.model.basedata.dto.CommunityDTO;
import com.zzwtec.third.model.permission.dto.LoginDTO;
import com.zzwtec.third.model.permission.dto.ObjRelationDTO;
import com.zzwtec.third.services.LoginServiceImpl;
import com.zzwtec.third.utils.BizException;
import com.zzwtec.third.utils.ErrorCode;
import com.zzwtec.third.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 物业管理员
 */
@Controller
public class AdmAdminController {

	private static final Logger logger = LoggerFactory.getLogger(AdmAdminController.class);

	@Autowired
	@Qualifier("stringRedisTemplate")
	private RedisTemplate<String, String> stringRedisTemplate;
	@Autowired
	private RedisService redisService;
	@Autowired
	private VerifyCodeComponent verifyCodeComponent;
	@Autowired
	private HttpServletResponse response;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	LoginServiceImpl loginService;

	/**
	 * 进入登录页面
	 */
	@RequestMapping(UrlContents.URL_ADM_LOGIN_UI)
	public String loginUI() {
		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(request);
		if (StringUtil.notEmpty(tokenId)) {
			this.request.getSession(true).removeAttribute(tokenId);
		}
		CookieIdGenerator gen = CookieIdGenerator.build();
		tokenId = WebPrefixAndConstant.SESSION_PREFIX_PROPERTY + gen.genaeratorSessionId();
		TokenServiceSupport.setWebTokenIdToCookie(this.request, this.response, tokenId);
		return "/community/view/login.html";
	}

	/**
	 * 物业管理登录请求
	 */
	@RequestMapping(value = UrlContents.URL_ADM_LOGIN, method = RequestMethod.POST)
	@ResponseBody
	public JSONObject login() {

		JSONObject result = new JSONObject()
				.fluentPut("url", UrlContents.URL_ADM)
				.fluentPut("error", 0);

		String username=request.getParameter("username");
		String password=request.getParameter("password");
		LoginDTO loginDTO=new LoginDTO(username,password);

		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
		String verifyCode = request.getParameter("verifyCode");
		String key = verifyCodeComponent.getVerifyCodeRedisKey(tokenId);
		String code = stringRedisTemplate.opsForValue().get(key);
		stringRedisTemplate.delete(key);

		if (StringUtils.isEmpty(code)) {
			result = new JSONObject()
					.fluentPut("error", ErrorCode.ERROR_313.getCode())
					.fluentPut("errormsg", ErrorCode.ERROR_313.getMessage())
					.fluentPut("url", UrlContents.URL_ADM_LOGIN_UI);
			return result;
		}
		if ( !StringUtils.isEmpty(verifyCode) && !StringUtils.isEmpty(code) ) {
			if( !code.equals(verifyCode)) {
				result = new JSONObject()
						.fluentPut("error", ErrorCode.ERROR_312.getCode())
						.fluentPut("errormsg", ErrorCode.ERROR_312.getMessage())
						.fluentPut("url", UrlContents.URL_ADM_LOGIN_UI);
				return result;
			}
		}

		try {
			SysuserCache sysuserCache = loginService.login(loginDTO);
			// 把登录过后的 tokenId 覆盖未登录时的 cookie 中的 tokenId
			// 并 缓存登录信息 30 分钟
			String newTokenId = sysuserCache.getTokenId();

			saveWechatUserCache(sysuserCache);
			redisService.saveEntityToJson(
					newTokenId,
					sysuserCache,
					RedisPrefixAndConstant.CACHE_LOGIN_TIME,
					TimeUnit.MINUTES
			);
		} catch (BizException e) {
			logger.warn(e.getMessage(), e);
			result = new JSONObject()
					.fluentPut("error", e.getCode())
					.fluentPut("errormsg", e.getMessage())
					.fluentPut("url", UrlContents.URL_ADM_LOGIN_UI);
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e.getCause());
			result = new JSONObject()
					.fluentPut("error", ErrorCode.ERROR_A_NEGATIVE.getCode())
					.fluentPut("errormsg", ErrorCode.ERROR_A_NEGATIVE.getMessage())
					.fluentPut("url", UrlContents.URL_ADM_LOGIN_UI);
			return result;
		}

		return result;
	}

	/**
	 * 物业登出
	 */
	@RequestMapping(
			value = UrlContents.URL_ADM_LOGIN_OUT,
			method = { RequestMethod.POST, RequestMethod.GET}
	)
	@ResponseBody
	public DataObject loginOut() {
		DataObject dataObject = new DataObject(
				ErrorCode.ERROR_0.getCode(),
				ErrorCode.ERROR_0.getMessage(),
				UrlContents.URL_ADM_LOGIN_UI
		);

		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(request);

		try {
			loginService.loginOut(tokenId);
			redisService.delete(tokenId);
		} catch (BizException e) {
			dataObject = new DataObject(e.getCode(), e.getMessage());
		} catch (Exception e) {
			dataObject = new DataObject(
					ErrorCode.ERROR_A_NEGATIVE.getCode(),
					ErrorCode.ERROR_A_NEGATIVE.getMessage()
			);
		}

		return dataObject;
	}

	/**
	 * 获取验证码
	 */
	@RequestMapping(
			value = UrlContents.URL_ADM_LOGFIN_VERIFY_CODE + "/{param}",
			method = {RequestMethod.GET, RequestMethod.POST}
	)
	public String getVerifyCode(@PathVariable("param") String param) {
		long t = 0;
		long s_at = 0;
		String[] ary = param.split("-");
		if (StringUtil.notEmpty(ary[0])) {
			t = Long.parseLong(ary[0]);
		}
		if (ary.length == 2) {
			if (StringUtil.notEmpty(ary[1])) {
				s_at = Long.parseLong(ary[1]);
			}
		}

		boolean isOK = false;
		if (s_at > 600 && t > 30) {
			isOK = true;
		} else if (s_at == 0 && t > 30) {
			isOK = true;
		}
		if (isOK) {
			String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(request);
			if (StringUtil.notEmpty(tokenId)) {
				String verifyCode = verifyCodeComponent.buildVerifyCode(tokenId);
				new MyCaptchaResult(verifyCode).render(response);
				return null;
			} else {
				return "redirect:" + UrlContents.URL_ADM_LOGIN_UI;
			}
		} else {
			return "redirect:" + UrlContents.URL_ADM_LOGIN_UI;
		}
	}

	/**
	 * 登录成功后的跳转主页
	 */
	@RequestMapping(UrlContents.URL_ADM)
	public String index() {
		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
		SysuserCache sysuserCache = redisService.getEntity(tokenId, new TypeReference<SysuserCache>(){});
		request.setAttribute("loginName", sysuserCache.getName());
		request.setAttribute("userName", sysuserCache.getName());
		List<String> permissionList = sysuserCache.getPermissionList();
		request.setAttribute("permissionList", permissionList);
		String currentManageCommunityId="";
		String currentManageCommunityName="";

		//查询登录管理员管理的小区集合
		List<CommunityDTO> manageCommunityList=sysuserCache.getManageCommunityList();
		CommunityDTO currentManageCommunity=sysuserCache.getCurrentManageCommunity();
		if(currentManageCommunity==null){
			if(manageCommunityList!=null && manageCommunityList.size()==1){//数据权限只有一个小区 默认为当前管理小区
				currentManageCommunity=manageCommunityList.get(0);
				sysuserCache.setCurrentManageCommunity(currentManageCommunity);
				redisService.saveEntityToJson(tokenId, sysuserCache, 30, TimeUnit.MINUTES);
			}
		}else{
			currentManageCommunityId=currentManageCommunity.getId();
			currentManageCommunityName=currentManageCommunity.getName();
		}
		request.setAttribute("currentManageCommunityId", currentManageCommunityId);
		request.setAttribute("currentManageCommunityName", currentManageCommunityName);
		String appkey = "555daeaa27302bb315893697";
		request.setAttribute("communityId", currentManageCommunityId);
		request.setAttribute("feedbackTopic", "s_feedback");
		//初始化yunba
		request.setAttribute("sessionId", tokenId);
		request.setAttribute("appkey", appkey);
		request.setAttribute("feedbackAlias", sysuserCache.getName());

		return "/community/view/index.html";
	}


	//由于微信那边需要token验证
	private void saveWechatUserCache(SysuserCache sysuserCache ){
		String adminTokenId="";
		String communityIds="";
		if(sysuserCache!=null){
			adminTokenId=sysuserCache.getTokenId();

			List<ObjRelationDTO> dataAuthList = sysuserCache.getDataAuthList();
			for(int i=0;i<dataAuthList.size();i++){
				if(i>=1) communityIds+=",";
				communityIds+= dataAuthList.get(i).getObjId();
			}
			stringRedisTemplate.opsForValue().set("adminTokenId", adminTokenId);
			stringRedisTemplate.expire("adminTokenId", 30, TimeUnit.MINUTES);
			stringRedisTemplate.opsForValue().set("adminCommunityIds", communityIds);
			stringRedisTemplate.expire("adminCommunityIds", 30, TimeUnit.MINUTES);
			TokenServiceSupport.setWebTokenIdToCookie(this.request, this.response, adminTokenId);
		}


	}



}