package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.output.UserDataByTokenDto;
import com.palmnest.dao.estateserve.NeigouOrderDao;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
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.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.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping("/wechat/supperapp/*")
public class SuperAppController {


	@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;


	public static String encrypt_key = "f10adc3949ba59abbe56e057e20f883d";

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

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


		//0：正常
		//1：网络错误
		//2：userid不存在
		//3：密码错误
		JSONObject returnMap = new JSONObject();


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

		try {
			String  userid   = request.getParameter("userid");//用手机号
			String  password = request.getParameter("password");//
			AppUser appuser  = appUserManager.getAppUsersByPhone(userid);
			if (null != appuser) {
				if (StringUtils.isNotEmpty(appuser.getPassword()) && appuser.getPassword().equals(password)) {

					Long   datatimeStr  = new Date().getTime();
					String sso_codeData = appuser.getId() + "|" + userid + "|" + datatimeStr;
					log.info("SuperAppController sso_codeData===" + sso_codeData);
					//String encrypt_key="f10adc3949ba59abbe56e057e20f883d";
					//String token=Java_AES_Cipher.encrypt(encrypt_key, sso_codeData);
					String token = GenPass.Encrypt(sso_codeData);
					log.info("SuperAppController token===" + token);

					returnMap.put("token", URLEncoder.encode(token, "UTF-8"));//0：正常
					returnMap.put("errorcode", "0");//0：正常
				} else {
					returnMap.put("errorcode", "3");//密码错误
				}
			} else {
				returnMap.put("errorcode", "2");//userid不存在
			}
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			returnMap.put("errorcode", "1");//网络错误
		}


		log.info("SuperAppController returnMap===" + returnMap.toJSONString());
		log.info("SuperAppController===== end do login method");
		return returnMap.toJSONString();
	}


	/**
	 * 异步注入分享接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fenxiang", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String fenxiang(HttpServletRequest request, HttpServletResponse response) {


		//青章银
		//2018-12-12 10:00~12:00
		//飞亚达9楼大会议举行
		//中航物业年度总结会议

		/*参会提醒：青章银邀请你参加2018-12-12 10:00~12:00在飞亚达9楼大会议举行的《中航物业年度总结会议》 ，点击查看会议详情*/
		/*会议主题为空的默认 企业名称+会议为会议主题*/

		//推送链接
		//http://superdesk.avic-s.com/super_service/wechat/virtual/getMeetingProUrl
		//openId
		//bookId

		try {
			//String developId=request.getParameter("developId");
			String openId = request.getParameter("openId");
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);

			String              url        = request.getParameter("url");//当前链接
//			String              jsapi_tike = Constants.CacheMap.get("jsapi_" + wxUser.getDevelopId());
			String              jsapi_tike = baseRedisService.get(Constants.JSAPI+wxUser.getDevelopId());
			WxPublicno          wxPublicno = publicNoManager.getByDevelopId(wxUser.getDevelopId());
			Map<String, String> wxMap      = WxConfigUtil.sign(jsapi_tike, url);
			wxMap.put("appid", wxPublicno.getAppId());

			//会议室分享链接 我要预定的链接
			List<ServiceTypeInfo> listServiceTypeInfo = serviceTypeInfoManager.getServiceTypeInfoByShkipAddress("wechat%2Fneigou%2FmeetingDo");
			if (null != listServiceTypeInfo && listServiceTypeInfo.size() >= 1) {
				String skipAddress = listServiceTypeInfo.get(0).getSkipAddress();

				WxPublicno pub = publicNoManager.getByDevelopId(wxUser.getDevelopId());
				skipAddress = getUrl(skipAddress, pub.getAppId(), pub.getId().toString());

				wxMap.put("meetingFenxiangUrl", skipAddress);
			} else {
				wxMap.put("meetingFenxiangUrl", "");
			}

			return net.sf.json.JSONObject.fromObject(wxMap).toString();
		} catch (Exception e) {
			log.error("分享信息错误:" + e.getMessage());
		}
		return null;

	}

	public String getUrl(String str1, String appid, String state) {
		String reUrl = "";
		if (StringUtils.isNotEmpty(str1)) {
			if (str1.indexOf("appid=") != -1) {
				reUrl = str1.substring(0, str1.indexOf("appid=") + 6) + appid + str1.substring(str1.indexOf("&", 1), str1.lastIndexOf("=") + 1) + state;
				if (reUrl.indexOf("realse") != -1) {
					reUrl += "&moduleCode=2";
				}
				if (reUrl.indexOf("emig") != -1) {
					reUrl += "&moduleCode=1";
				}
				reUrl += str1.substring(str1.lastIndexOf("#"));
			} else {
				reUrl = str1;
			}

		}
		return reUrl;
	}


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


		//0：正常
		//1：网络错误
		//2：userid不存在
		//3：密码错误
		//JSONObject returnMap=new JSONObject();
		UserDataByTokenDto dto = new UserDataByTokenDto();

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

		try {

			String token              = request.getParameter("token");//用手机号
			String tokenTypeParameter = request.getParameter("tokenType");//用手机号
			//-------------lmz--------------
			String orgId = request.getParameter("organizationId");

			//-------------lmz--------------
			String tokenType = "WeChat";//WeChat/APP
			/*			if(StringUtils.isNotEmpty(tokenTypeParameter)){
				tokenType=tokenTypeParameter;
			}*/
			String user_token = GenPass.Decrypt(URLDecoder.decode(token, "UTF-8"));
			if (StringUtils.isNotEmpty(user_token)) {
				tokenType = "WeChat";
			} else {
				tokenType = "APP";
			}

			dto.setTokenType(tokenType);
			if (tokenType.equals("WeChat")) {

				String token_openId = SupperAppUtils.getOpenIdByToken(user_token);
				String userId=SupperAppUtils.getUserIdByToken(user_token);

				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(token_openId);

				if (StringUtils.isEmpty(orgId)) {
					if (wxUser != null && wxUser.getOrganizationId() != null) {
						orgId = wxUser.getOrganizationId().toString();
					}
					if (StringUtils.isEmpty(orgId)) {
						dto.setErrorcode("1");
						dto.setErrorMsg("项目不允许为空");
						return dto;
					}
				}
				dto.setOrganizationId(orgId.toString());

				//后面动态获取
				TbOrganization org = organizationManager.getOrganizationById(Integer.parseInt(orgId));//-------------lmz--------------
				if (StringUtils.isNotEmpty(org.getMettingClient())) {
					dto.setMettingclient(org.getMettingClient());//尚美集团
				} else {
					dto.setErrorcode("1");
					dto.setErrorMsg("该项目会议室尚未完成初始化,请联系管理员");
					return dto;
				}

				dto.setOrganizationName(org.getName());
				dto.setOpenId(wxUser.getOpenId());
				dto.setUserId(token_openId);//只有用openid了 需要的话后面在改
				dto.setNewUserId(userId);
				String userName = "超级前台用户";
				if (StringUtils.isNotEmpty(wxUser.getNickName())) {
					userName = wxUser.getNickName();
				}/*else if(StringUtils.isNotEmpty(appUser.getUserName())){
					userName=appUser.getUserName();
				}*/
				//returnMap.put("userName",userName);
				//returnMap.put("mobile", appUser.getUserMobile());
				//returnMap.put("role", appUser.getRoleType());//1-管理员，2-普通用户	
				//returnMap.put("headimgUrl", wxUser.getHeadimgUrl());
				dto.setUserName(userName);

				AppUser appUer = null;
				if(StringUtils.isNotEmpty(userId)){
					appUer = appUserManager.get(Integer.parseInt(userId));
				}else{
					appUer = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), Integer.decode(orgId));
				}
				if (null != appUer && StringUtils.isNotEmpty(appUer.getUserMobile())) {
					dto.setMobile(appUer.getUserMobile());
				} else {
					dto.setMobile("");//暂时时无手机号
				}
				//如果白名单有值 取白名单
				if (null != appUer && StringUtils.isNotEmpty(appUer.getUserName())) {
					dto.setUserName(appUer.getUserName());
				}

				//dto.setRole("2");//1-管理员，2-普通用户 微信都为普通用户
//				dto.setRole("BIZMANG");//个人登录企业账号 角色为业务管理员
				dto.setRole("BOOKER");
				dto.setHeadimgUrl(wxUser.getHeadimgUrl());


				dto.setHostUrl(webUrl);

				Integer isCompanyHead = 0;//是否企业负责人 0否 1是
				//returnMap.put("companyId","");//企业Id
				dto.setCompanyId("");

				dto.setIsCompanyHead(0);
				dto.setIsBingCompany(0);//没有绑定公司时 微信在预定会议室时拦截 来登录企业账号 地址用 getBandUrl 方法返回
				/*List<UserAccountRecode> userList=userAccountService.getUserAccountRecode(orgId,token_openId);
				if(userList!=null&&userList.size()>0){
				
					UserAccountRecode userAcc=userList.get(0);
					if(userAcc!=null){
						VirtualAccount virAcc=virtualAccountManager.get(userAcc.getAccountId());
						dto.setCompanyId(String.valueOf(virAcc.getVirId()));//企业id
						dto.setVirAccountId(virAcc.getId().toString());
						if(virAcc.getVirId()!=0){
							dto.setIsBingCompany(1);							
							VirtualArchitecture virInfo=virtualArchManager.get(virAcc.getVirId());
							if(StringUtils.isNotEmpty(virInfo.getName())){
								dto.setCompanyName(virInfo.getName());//企业名称
							}							
						}
					}
					
				}*/


				if(null != appUer && null != appUer.getVirtualArchId() && null != appUer.getOrganizationId()){
					List<VirtualAccount> listAccount = virtualAccountManager.getVirAccByVirAndOrg(appUer.getVirtualArchId(), appUer.getOrganizationId());
					if (listAccount.size() >= 1) {
						VirtualAccount vacc = listAccount.get(0);
						dto.setCompanyId(String.valueOf(vacc.getVirId()));//企业id
						dto.setVirAccountId(vacc.getId().toString());
						VirtualArchitecture virInfo = virtualArchManager.get(vacc.getVirId());
						if (StringUtils.isNotEmpty(virInfo.getName())) {
							dto.setCompanyName(virInfo.getName());//企业名称
						}

					}
				}
				
				//是否登录判断
				dto.setVirLoginUrl(webUrl + "/wechat/appUser/virAccount");
				if (org.getAccountType() == 1) {//个人是绑定手机号
					if (appUer == null || appUer.getIsLogin() == 0) {
						dto.setVirLoginUrl(webUrl + "/wechat/appUser/userLoginPage");//没有登录正常登录
						dto.setIsBingCompany(0);
					} else if (appUer != null && appUer.getIsLogin() == 1 && appUer.getIsBinding() == 0) {
						dto.setVirLoginUrl(webUrl + "/wechat/appUser/changeAccountLogin");//低权限处理
						dto.setIsBingCompany(0);
					} else {
						dto.setIsBingCompany(1);
					}

				}

			} else if (tokenType.equals("APP")) {//需要获得app管理员管理的楼层信息
				String userName = baseRedisService.get(token);

				if (userName == null) {
					dto.setErrorcode("1");
					dto.setErrorMsg("token已过期");
					return dto;
				}

				dto = userManager.setUserData(userName);

			}
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			//returnMap.put("errorcode", "1");//网络错误
			dto.setErrorcode("1");
			dto.setErrorMsg("出错：" + e.getMessage());
		}

		log.info("getUserDataByToken returnMap===" +JSONObject.toJSONString(dto));
		log.info("getUserDataByToken===== end do login method");
		return dto;
	}

	@RequestMapping(value = "/SpaceHome", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public @ResponseBody
	String SpaceHome(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {/*
		
	  
		List<Map<String,Object>> listObs=neigouOrderDao.getCompanyAndSuperUser("前海超级前台（深圳）有限公司");
		
		if(listObs.size()>=1){
			  SpaceHomeUtil.SynchCompany((Map<String,Object>)listObs.get(0));
			
			  SpaceHomeUtil.SynchUser(listObs);
		}
		
		//AppUser user=appUserManager.getAppUserByOpenId("gh_bb8ab88fc77a", "o4L9Qty_oT8c4lWUQnkQ9ZAXgG_U");
		
		return JSONObject.toJSONString(listObs);
	*/

		return null;
	}

	/**
	 * 同步公司及超级管理员
	 */
	@RequestMapping(value = "/SynchCompany", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public @ResponseBody
	void SynchCompany(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {


		String companyId     = request.getParameter("companyId");
		String supperAdminId = request.getParameter("supperAdminId");

		log.info("SynchCompany--companyId=========" + companyId);
		log.info("SynchCompany--companyId=========" + supperAdminId);

		List<Map<String, Object>> listObs = neigouOrderDao.getCompanyAndSuperUser(companyId, supperAdminId);

		String returnStr = "";
		if (listObs.size() >= 1) {
			returnStr = SpaceHomeUtil.SynchCompany((Map<String, Object>) listObs.get(0));
		}

		//AppUser user=appUserManager.getAppUserByOpenId("gh_bb8ab88fc77a", "o4L9Qty_oT8c4lWUQnkQ9ZAXgG_U");

		JSONObject json = new JSONObject();
		json.put("returnStr", returnStr);
		StringUtil.charSet(json, request, response);
	}

	/**
	 * 同步子管理员
	 */
	@RequestMapping(value = "/SynchUser", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public @ResponseBody
	void SynchUser(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {


		String companyId     = request.getParameter("companyId");
		String supperUserIds = request.getParameter("supperUserIds");//2910,607 子管员ids

		log.info("SynchCompany--companyId=========" + companyId);
		log.info("SynchCompany--supperUserIds=========" + supperUserIds);

		List<Map<String, Object>> listObs = neigouOrderDao.getSuperUser(companyId, supperUserIds);

		String returnStr = "";
		if (listObs.size() >= 1) {
			returnStr = SpaceHomeUtil.SynchUser(listObs);
		}

		JSONObject json = new JSONObject();
		json.put("returnStr", returnStr);
		StringUtil.charSet(json, request, response);
	}

	/**
	 * sunmei 跳转
	 */
	@RequestMapping(value = "/sunmei")
	public ModelAndView sunmei(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();


			return new ModelAndView("admin/billPush/billPush", model.asMap());
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}

	}


	/**
	 * 会议室排行榜
	 */
	//@RequestMapping(value="/getMeetingRanking",method = {RequestMethod.GET,RequestMethod.POST }, produces = "application/json")
	//public @ResponseBody void getMeetingRanking(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
	@RequestMapping(value = "getMeetingRanking")
	@ResponseBody
	public AppResultDto getMeetingRanking(String orgId) {

		String monthStr   = "";
		List   returnList = new ArrayList();
		if (!StringUtil.isNotEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目不允许为空");
		}

		TbOrganization org           = organizationManager.getOrganizationById(Integer.parseInt(orgId));
		String         mettingClient = org.getMettingClient();
		if (!StringUtil.isNotEmpty(mettingClient)) {
			return AppResultUtil.createErrorDto("100", "当前项目没有开通会议室功能");
		}

		Date currentDate = new Date();
		monthStr = DateUtils.getPrevMonth(DateUtils.getDate(currentDate, "yyyy-MM-dd"), "yyyy-MM");

		//服务项放入缓存
		String serviceJson = baseRedisService.get(CodeConstants.ORG_MEETINGRANKING + orgId + "-" + monthStr);
		if (StringUtils.isNotEmpty(serviceJson)) {

			returnList = (List) JSONObject.parseObject(serviceJson, List.class);
			if (returnList != null) {
				return AppResultUtil.createSuccesDto(returnList);
			}
		} else {
			returnList = superAppService.getMeetingRanking(orgId);
			baseRedisService.set(CodeConstants.ORG_MEETINGRANKING + orgId + "-" + monthStr, JSONObject.toJSONString(returnList));
		}
		return AppResultUtil.createSuccesDto(returnList);
	}

	public static void main(String[] args) {

		String token1 = "2026D95792D4741D813386F0BFC03D0DBAF12555FB5D2DC21E1FFDAAC165E802B8890BDB7416856724B36C3614D6A2CA7EC814AB5036476A";

		String returnToken;
		Long   datatimeStr  = new Date().getTime();
		String sso_codeData = "13066855659" + "|" + "438" + "|" + datatimeStr;
		//String encrypt_key="f10adc3949ba59abbe56e057e20f883d";
		//String token=Java_AES_Cipher.encrypt(encrypt_key, sso_codeData);
		//String token=GenPass.Encrypt(sso_codeData);
		//System.out.println(token);

		String token2;
		try {
			token2 = GenPass.Decrypt(URLDecoder.decode(token1, "UTF-8"));
			System.out.println(token2);
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}


	}
	
	/*public static void main(String[] args) {
		
		Map<String, String> oauthLoginResponse = null;
		String retMsg="";
		JSONObject json=new JSONObject();
		json.put("client", "");
		String jsonMapStr=JSONObject.toJSONString(json);
		String token ="FD5A0AEC737CF9B850A8766CE0CFAF8FA12D9774BAA09447";
		retMsg=HttpKit.HttpClientPost(jsonMapStr,token,"http://119.23.39.237:8066"+"/web/comment/getCommentAmount");
		System.out.println("getMeetingRanking retMsg:"+retMsg);
		
		oauthLoginResponse = JSONObject.parseObject(retMsg, new TypeReference<Map<String, String>>(){});
		
		if(oauthLoginResponse.get("code").equals("200")){
			
			String dateStr=oauthLoginResponse.get("data");
			
			Map<String, Integer> dataOj=JSONObject.parseObject(dateStr,new TypeReference<Map<String, Integer>>(){});
			Integer commentAmount=dataOj.get("commentAmount");
			
		}
		
		
	}*/
}
