package com.palmnest.service.usertoken.impl;

import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.dao.estateserve.NeigouOrderDao;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.estateserve.airconditioner.SuperAppService;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.usertoken.UserTokenService;
import com.palmnest.service.virtProject.UserAccountService;
import com.palmnest.service.virtProject.manager.VirtualAccountManager;
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 java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("userTokenService")
public class UserTokenServiceImpl implements UserTokenService {


	public static String webUrl = PropertiesKit.readPropertiesValue("webUrl", "wechat.properties");

	public static String client_weChat = "weChat";
	public static String client_app    = "app";
	public static String client_pc     = "pc";

	@Autowired
	private AppUserManager         appUserManager;
	@Autowired
	private ScWxuserManager        scWxuserManager;
	@Autowired
	private NeigouOrderDao         neigouOrderDao;
	@Autowired
	private BaseRedisService       baseRedisService;
	@Autowired
	private UserManager            userManager;
	@Autowired
	private VirtualArchManager     virtualArchManager;
	@Autowired
	private UserAccountService     userAccountService;
	@Autowired
	private VirtualAccountManager  virtualAccountManager;
	@Autowired
	private OrganizationManager    organizationManager;
	@Autowired
	private PublicNoManager        publicNoManager;
	@Autowired
	private ServiceTypeInfoManager serviceTypeInfoManager;
	@Autowired
	private SuperAppService        superAppService;
	@Autowired
	private AppUserService         appUserService;

	@Override
	public AppResultDto getUserIsHaveTsbyReplyByToken(HttpServletRequest request) {

		log.info("getUserHaveTsbyReplyByToken=====start do login method");
		Map returnMap = new HashMap<String, String>();

		try {

			//微信 Pc token
			String token = request.getHeader("token");//用手机号

			String tokenType = client_weChat;

			String user_token = GenPass.Decrypt(URLDecoder.decode(token, "UTF-8"));
			if (StringUtils.isNotEmpty(user_token)) {
				String tokenTypeQuery = SupperAppUtils.getToKenTypeByToken(user_token);

				tokenType = tokenTypeQuery;
			} else {
				tokenType = client_app;
			}


			User appUser = null;
			if (tokenType.equals(client_app)) {
				String userName = baseRedisService.get(token);

				if (userName == null) {
					return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "token已过期");
				}

				appUser = userManager.getUserByUsername2(userName);//tb_app_user
			} else if (tokenType.equals(client_pc)) {
				String pcUserName = SupperAppUtils.getOpenIdByToken(user_token);

				//PCtoken校验
				/*String pcToken=(String)request.getSession().getAttribute("PcToken");
				if(StringUtils.isNotEmpty(pcToken) || user_token.equals(pcToken)){
					appUser = userManager.getUserByUsername2(pcUserName);//tb_app_user
				}else{
					return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "token已过期");
				}*/

				appUser = userManager.getUserByUsername2(pcUserName);//tb_app_user
			}


			User userTsbyaudit = userManager.findByFunctionAndUser(CodeConstants.TSBYAUDIT_PERMISSION, appUser.getId());
			if (null != userTsbyaudit) {
				returnMap.put("haveTsbyReplyPermission", "1");
			} else {
				returnMap.put("haveTsbyReplyPermission", "0");
			}

		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "出错：" + e.getMessage());
		}

		log.info("getUserHaveTsbyReplyByToken===== end do login method");
		return AppResultUtil.createSuccesDto("获得数据成功", returnMap);
	}

	@Override
	public AppResultDto getOrgsByToken(HttpServletRequest request) {


		log.info("getOrgsByToken=====start do login method");

		List<OrgDto> orgDtoList = new ArrayList<OrgDto>();
		try {

			String tokenType = "";
			String token     = request.getHeader("token");//用手机号
			if (StringUtils.isEmpty(token)) {
				return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "token不能为空");
			}

			String user_token = GenPass.Decrypt(URLDecoder.decode(token, "UTF-8"));
			if (StringUtils.isNotEmpty(user_token)) {
				String tokenTypeQuery = SupperAppUtils.getToKenTypeByToken(user_token);

				tokenType = tokenTypeQuery;
			} else {
				tokenType = client_app;
			}

			User appUser = null;
			if (tokenType.equals(client_app)) {
				String userName = baseRedisService.get(token);

				if (userName == null) {
					return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "token已过期");
				}

				appUser = userManager.getUserByUsername2(userName);//tb_app_user
			} else if (tokenType.equals(client_pc)) {
				String pcUserName = SupperAppUtils.getOpenIdByToken(user_token);
				appUser = userManager.getUserByUsername2(pcUserName);//tb_app_user
				//PCtoken校验
				/*String pcToken=(String)request.getSession().getAttribute("PcToken");
				if(StringUtils.isNotEmpty(pcToken) || user_token.equals(pcToken)){
					appUser = userManager.getUserByUsername2(pcUserName);//tb_app_user
				}else{
					return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "token已过期");
				}*/

			}

			if (appUser != null) {

				orgDtoList = appUserService.getUserOrgs(appUser.getId());
			}


		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "出错：" + e.getMessage());
		}

		log.info("getOrgsByToken===== end do login method");
		return AppResultUtil.createSuccesDto("获得数据成功", orgDtoList);
	}

}
