package com.palmnest.webapp.controller.api;

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.application.dto.output.WJXUserDataDto;
import com.palmnest.dao.estateserve.NeigouOrderDao;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
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.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping(value = "/api/userdata*")
public class ApiUserTokenController {


	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;
	@Autowired
	private UserTokenService       userTokenService;


	@ResponseBody
	@RequestMapping(value = "/getUserDataByToken", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public AppResultDto getUserDataByToken(HttpServletRequest request, HttpServletResponse response) {


		WJXUserDataDto dto = new WJXUserDataDto();

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

		try {

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

			log.info("getUserDataByToken token=++++++++++==" + token);

			if (StringUtils.isEmpty(token)) {
				return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "token不能为空");
			}

			String orgId     = "";
			String tokenType = client_weChat;

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

			} else {
				tokenType = client_app;
			}

			dto.setTokenType(tokenType);
			if (tokenType.equals(client_weChat)) {

				String token_openId = SupperAppUtils.getOpenIdByToken(user_token);
				log.info("getUserDataByToken openid -----:" + token_openId);
				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(token_openId);

				if (StringUtils.isEmpty(orgId)) {
					if (wxUser != null && wxUser.getOrganizationId() != null) {
						orgId = wxUser.getOrganizationId().toString();
					}
					if (StringUtils.isEmpty(orgId)) {
						return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "项目不允许为空");
					}
				}
				dto.setOrgId(Integer.decode(orgId));

				//后面动态获取
				TbOrganization org = organizationManager.getOrganizationById(Integer.parseInt(orgId));//-------------lmz-------------
				dto.setOrgName(org.getName());

				dto.setOpenId(wxUser.getOpenId());

				String userName = "";
//				if(StringUtils.isNotEmpty(wxUser.getNickName())){
//					userName=wxUser.getNickName();
//				}
				dto.setUserName(userName);


				AppUser appUer = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), Integer.decode(orgId));
				if (appUer != null) {
					dto.setUserId(appUer.getId());//只有用openid了 需要的话后面在改
					if (StringUtils.isNotEmpty(appUer.getUserName())) {
						dto.setUserName(appUer.getUserName().trim());    //如果白名单有值 取白名单
					}
					if (StringUtils.isNotEmpty(appUer.getUserMobile())) {
						dto.setMobile(appUer.getUserMobile());
					} else {
						dto.setMobile("");//暂时时无手机号
					}
					if (null != appUer.getVirtualArchId()) {
						dto.setEnterpriseId(appUer.getVirtualArchId());
						VirtualArchitecture vir = virtualArchManager.get(appUer.getVirtualArchId());
						dto.setEnterpriseName(vir.getName());
					}
				}

				//admin或系统管理员返回问卷星系统管理员
				//微信用户只能属于一个项目
				if (StringUtils.isNotEmpty(org.getWjxAccount())) {
					dto.setWjxAccount(org.getWjxAccount());
				}


			} else if (tokenType.equals(client_app) || tokenType.equals(client_pc)) {//需要获得app管理员管理的楼层信息


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

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

					dto.setTokenType(client_app);
					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
				}

				if (appUser != null) {


					List<OrgDto> organizationList = appUserService.getUserOrgs(appUser.getId());
					if (organizationList.size() == 1) {
						OrgDto orgDto = organizationList.get(0);
						dto.setOrgId(orgDto.getId());
						dto.setOrgName(orgDto.getName());

						TbOrganization org = organizationManager.getOrganizationById(orgDto.getId());//-------------lmz-------------
						dto.setWjxAccount(org.getWjxAccount());
					} else {
						dto.setWjxAccount("superdesk");
						dto.setRoleType("moreOrg");
					}


					dto.setOpenId("");
					dto.setUserId(appUser.getId().intValue());

					//获得问卷可能用的get 名称中间有空格会报错
					//dto.setUserName(appUser.getId().toString());
					dto.setUserName(appUser.getFullName().trim());
					dto.setMobile(appUser.getTelephone());//账号唯一值
				}


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

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

	//当前项目 请求有回复权限的人 List<User> 参数当前项目Id
	@ResponseBody
	@RequestMapping(value = "/getUsersHaveTsbyReplyByOrgId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public AppResultDto getUserHaveTsbyReplyByToken(HttpServletRequest request, HttpServletResponse response) {


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

		try {

			String token = request.getHeader("token");//用手机号
			String orgId = request.getParameter("orgId");
				
				/*String userName = baseRedisService.get(token);
				if(userName == null) {
					return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "token已过期");
				}*/

			//推送消息
			List<User> users   = userManager.findByFunction(Integer.parseInt(orgId), CodeConstants.TSBYAUDIT_PERMISSION);
			List       userIds = new ArrayList<String>();
			for (User u : users) {
				userIds.add(u.getId().toString());
			}
			returnMap.put("users", userIds);


		} 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);
	}

	//某人是否有投诉表扬回复权限 true/false
	@ResponseBody
	@RequestMapping(value = "/getUserIsHaveTsbyReplyByToken", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public AppResultDto getUserIsHaveTsbyReplyByToken(HttpServletRequest request, HttpServletResponse response) {

		return userTokenService.getUserIsHaveTsbyReplyByToken(request);

	}

	@ResponseBody
	@RequestMapping(value = "/getOrgsByToken", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public AppResultDto getOrgsByToken(HttpServletRequest request, HttpServletResponse response) {

		return userTokenService.getOrgsByToken(request);
	}
}
