package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.DeptAddressDto;
import com.palmnest.model.Role;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.UserAccountRecode;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.dinner.service.ConsumerUserService;
import com.palmnest.service.dinner.service.DeptService;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.MemberManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.virtProject.UserAccountService;
import com.palmnest.service.virtProject.VirtualAccountService;
import com.palmnest.service.virtProject.VirtualArchService;
import com.palmnest.service.ws.FacePlusClient;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.json.JSONException;
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.ModelAttribute;
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.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping(value = "/wechat/appUser*")
public class AppWechatUserController {


	@Autowired
	private MemberManager    memberManager;	
	
	@Autowired
	private ScWxuserManager       scWxuserManager;
	@Autowired
	private UserAccountService    userAccountService;
	@Autowired
	private VirtualAccountService virtualAccountService;
	@Autowired
	private VirtualArchService    virtualArchService;
	@Autowired
	private AppUserManager        appUserManager;
	@Autowired
	private DeptService           deptService;
	@Autowired
	private OrganizationManager   organizationManager;
	@Autowired
	private ConsumerUserService   consumerUserService;

	public static String host      = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	public static String wechatUrl = PropertiesKit.readPropertiesValue("wechatUrl", "wechat.properties");

	@RequestMapping(value = "/virAccount")
	public ModelAndView virAccount() {
		Model model = new ExtendedModelMap();
		model.addAttribute("wechatUrl", host + wechatUrl);
		return new ModelAndView("wechat/virAccount", model.asMap());
	}

	@RequestMapping(value = "/newmine")
	public ModelAndView newmine() {
		Model model = new ExtendedModelMap();

		return new ModelAndView("wechat/newmine", model.asMap());
	}

	@RequestMapping(value = "/errorTip")
	public ModelAndView errorTip() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/errorTip", model.asMap());
	}

	@RequestMapping(value = "/understandProject")
	public ModelAndView understandProject() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/understandProject", model.asMap());
	}

	@RequestMapping(value = "/virChangePsd")
	public ModelAndView virChangePsd() {
		Model model = new ExtendedModelMap();

		return new ModelAndView("wechat/virChangePsd", model.asMap());
	}

	@RequestMapping(value = "/accountExplain")
	public ModelAndView accountExplain() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/accountExplain", model.asMap());
	}

	@RequestMapping(value = "/selectProject")
	public ModelAndView selectProject() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/selectProject", model.asMap());
	}

	/**
	 * 微信端 我的-设置页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/mySetUp")
	public ModelAndView mySetUp() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/mySetUp", model.asMap());
	}

	/**
	 * 微信端 我的-修改个人信息页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/modifyInfo")
	public ModelAndView modifyInfo() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/modifyInfo", model.asMap());
	}

	/**
	 * 微信端 我的-修改手机号页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/modifyPhone")
	public ModelAndView modifyPhone() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/modifyPhone", model.asMap());
	}

	/**
	 * 去个人账号登录页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/userLoginPage")
	public ModelAndView bindPhone() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/bindPhone", model.asMap());
	}

	/**
	 * 去更换账号页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/changeAccountLogin")
	public ModelAndView changeAccountLogin() {
		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/changeAccountLogin", model.asMap());
	}

	/**
	 * 企业账号登录
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/accountLogin")
	@ResponseBody
	public AppResultDto accountLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String account  = request.getParameter("account");
		String password = request.getParameter("password");
		String openId   = request.getParameter("openId");
		String orgId    = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
			if (user != null && user.getOrganizationId() != null) {
				orgId = user.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "登录用户不存在");
		}
		try {
			return virtualArchService.accLogin(orgId, openId, account, password);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "登录失败：" + e.getMessage());
		}
	}

	/**
	 * 退出登录
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/exitLogin")
	@ResponseBody
	public AppResultDto exitLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String openId    = request.getParameter("openId");
		String accountId = request.getParameter("accountId");
		String orgId     = request.getParameter("orgId");
		try {
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			List<UserAccountRecode> list = userAccountService.getUserAccountByAccount(orgId, accountId, openId);
			if (list != null && list.size() == 1) {
				UserAccountRecode recode = list.get(0);
				recode.setModifier(openId);
				recode.setModifyTime(new Date());
				recode.setIsOnline("1");
				userAccountService.updateUserAccount(recode);
				return AppResultUtil.createSuccesDto();
			} else {
				return AppResultUtil.createErrorDto("100", "账号记录出现异常");
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "退出：" + e.getMessage());
		}
	}

	/**
	 * 获取用户信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserInfo")
	@ResponseBody
	public AppResultDto getUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String openId = request.getParameter("openId");
		String orgId  = request.getParameter("organizationId");
		String userId = request.getParameter("userId");

		try {
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			AppResultDto dto = virtualArchService.getUserInfo(openId, orgId, userId);
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取用户信息失败：" + e.getMessage());
		}
	}

	/**
	 * 获取部门的接口
	 *
	 * @param orgId
	 * @param virId
	 * @return
	 */
	@RequestMapping(value = "getDept")
	@ResponseBody
	public AppResultDto getDept(String orgId, String virId) {
		List<DeptAddressDto> dtoList = deptService.getAllDept(orgId, virId, "");
		return AppResultUtil.createSuccesDto(dtoList);
	}

	/**
	 * 修改企业帐号的密码
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updatePassword")
	@ResponseBody
	public AppResultDto updatePassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String account     = request.getParameter("account");
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String openId      = request.getParameter("openId");
		String orgId       = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
			if (user != null && user.getOrganizationId() != null) {
				orgId = user.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		if (StringUtils.isEmpty(account) || StringUtils.isEmpty(oldPassword)) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "登录用户不存在");
		}
		if (StringUtils.isEmpty(newPassword)) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "新密码不能为空");
		}
		try {
			AppResultDto dto = virtualAccountService.updateVirAccount(orgId, account, oldPassword, newPassword, openId);
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取用户信息失败：" + e.getMessage());
		}
	}

	/**
	 * 尚美-会议室后台 同步企业信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/synchroCompanyData")
	@ResponseBody
	public AppResultDto synchroCompanyData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//根据上次查询的时间节点，查询到本时间内的企业信息
		String startTime = request.getParameter("lastUpdateTime");
		try {
			AppResultDto dto = virtualArchService.synchroCompanyData(startTime);
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "返回信息：" + e.getMessage());
		}
	}

	/**
	 * 同步会议室审核角色
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/synchroMeetingRole")
	@ResponseBody
	public AppResultDto synchroMeetingRole(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String         orgId    = "0";
		String         clientNo = request.getParameter("clientNo");
		TbOrganization org      = organizationManager.getByMettingClient(clientNo);
		if (null != org) {
			orgId = org.getId().toString();
		}
		try {
			AppResultDto dto = virtualArchService.synchroMeetingRole(orgId);
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "返回信息：" + e.getMessage());
		}
	}

	/**
	 * 尚美-会议室后台 同步楼层房间信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/synchroFloorData")
	@ResponseBody
	public AppResultDto synchroFloorData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//根据上次查询的时间节点，查询到本时间内的企业信息
		String startTime = request.getParameter("lastUpdateTime");
		try {
			AppResultDto dto = virtualArchService.synchroFloorData(startTime);
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "返回信息：" + e.getMessage());
		}
	}
	
	
	
	
	@RequestMapping(value = "/updateKoalaImg")
	@ResponseBody
	public AppResultDto updateKoalaImg(HttpServletRequest request) {
		
		String userId = request.getParameter("userId");
		String imgId   = request.getParameter("imgId");
		String imgUrl   = request.getParameter("imgUrl");

		if (StringUtils.isEmpty(userId)) {
			return AppResultUtil.createErrorDto("100", "userId参数为空");
		}
		/*if (StringUtils.isEmpty(imgId)) {
			return AppResultUtil.createErrorDto("100", "imgId参数为空");
		}
		if (StringUtils.isEmpty(imgUrl)) {
			return AppResultUtil.createErrorDto("100", "imgUr参数为空");
		}*/
		
		return memberManager.updateKoalaImg(Integer.valueOf(userId),imgId,imgUrl);

	}
	
	
	@RequestMapping(value = "/setKoalaInfo", method = RequestMethod.GET)
	public AppResultDto setKoalaInfo(HttpServletRequest request) {
		
		return AppResultUtil.createSuccesDto("成功");
	}
	
	

	/**
	 * 微信端 我的-修改个人信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/modifyUserInfo")
	@ResponseBody
	public AppResultDto modifyUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String userId   = request.getParameter("userId");
		String userName = request.getParameter("userName");
//		String addressId = request.getParameter("addressId");
		String deptId   = request.getParameter("deptId");
		String deptName = request.getParameter("deptName");

		String addimgUrls   = request.getParameter("addimgUrls");
		String imageUrlids  = request.getParameter("imageUrlids");
		String removeUrlids = request.getParameter("removeUrlids");

		if (StringUtils.isBlank(userId)) {
			return AppResultUtil.createErrorDto("100", "用户id不能为空");
		}

		try {
			AppUser user = appUserManager.get(Integer.parseInt(userId));
			if (user != null) {
				user.setDepartmentName(deptName);
				user.setUserName(userName);
				if (StringUtil.isNotEmpty(deptId)) {
					user.setDepartmentId(Integer.parseInt(deptId));
				}
				appUserManager.saveOrUpdateAppUser(user);
			}
			if (StringUtil.isNotEmpty(addimgUrls) || StringUtil.isNotEmpty(imageUrlids) || StringUtil.isNotEmpty(removeUrlids)) {
				consumerUserService.setFaceImage(user, addimgUrls, imageUrlids, removeUrlids);
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "返回信息：" + e.getMessage());
		}
	}
	
	
	
	/**
	 * 企业员工信息添加人脸图片识别上传
	 * 微信端访客邀约人脸识别校验
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	@RequestMapping(value = "/uploadKoalaPhoto", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String uploadKoalaPhoto(HttpServletRequest request) throws IOException, ParseException, JSONException {	
		
		return memberManager.uploadKoalaPhoto(request);	
		
	}
	

	/**
	 * 企业员工信息添加人脸图片识别上传
	 * 微信端访客邀约人脸识别校验
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	/*@RequestMapping(value = "/validateImage", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String validateImage(HttpServletRequest request) throws IOException, ParseException, JSONException {
		String     imageUrl      = request.getParameter("imageUrl");
		String     virtualArchId = request.getParameter("virtualArchId");
		JSONObject jsonObject    = new JSONObject();
		String     relativePath  = "";
		try {
			relativePath = FileUploadUtils.getBase64ImageUrl(imageUrl);
			if (StringUtils.isNotBlank(relativePath) && StringUtils.isNotBlank(virtualArchId)) {
				// 从缓存中取face++账号信息
				CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + virtualArchId);
				if (cookieStore != null) {
					// 如果有相关账号信息 则直接进行图片上传 同步face++
					Map<String, Object> map = FacePlusClient.photos(Constants.IMAGE_ROOT + relativePath, cookieStore);
					if (map == null) {
						FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
						jsonObject.put("desc", "没有检测到人脸！");
						jsonObject.put("flag", false);
					} else {
						jsonObject.put("imageUrl", relativePath);
						jsonObject.put("url", map.get("url") + "");
						jsonObject.put("id", map.get("id"));
						jsonObject.put("flag", true);
					}
				} else {
					// 如果缓存中没有相关face++ 企业账号信息;则去配置文件读取账号信息,并登陆face++,然后进行图片上传
					Map<String, Object> map = FacePlusClient.photos(Constants.IMAGE_ROOT + relativePath,
							FacePlusClient.authLogin(Constants.FACE_PLUS_USER, Constants.FACE_PLUS_PASSWORD));
					if (map == null) {
						FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
						jsonObject.put("desc", "没有检测到人脸！");
						jsonObject.put("flag", false);
					} else {
						jsonObject.put("imageUrl", relativePath);
						jsonObject.put("flag", true);
						jsonObject.put("url", map.get("url") + "");
						jsonObject.put("id", map.get("id"));
					}
				}
			} else {
				jsonObject.put("flag", false);
				jsonObject.put("desc", "没有检测到图片！");
			}
		} catch (Exception e) {
			FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
			log.error("检测图片接口错误:" + e.getMessage());
			jsonObject.put("flag", false);
			jsonObject.put("desc", "网络超时！");
		}
		return jsonObject.toString();
	}*/


	/**
	 * 微信端 我的-修改个人信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/exitPersonLogin")
	@ResponseBody
	public AppResultDto exitPersonLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String userId = request.getParameter("userId");

		String openId    = request.getParameter("openId");
		String accountId = request.getParameter("accountId");
		String orgId     = request.getParameter("orgId");

		if (StringUtils.isBlank(userId)) {
			return AppResultUtil.createErrorDto("100", "用户id不能为空");
		}

		try {
			AppUser user = appUserManager.get(Integer.parseInt(userId));
			if (user != null) {
				user.setIsLogin(0);
				user.setIsBinding(0);
//				user.setWxUserId(null);// 退出时解绑微信用户的绑定
				appUserManager.saveOrUpdateAppUser(user);
			}


			// 退出个人登录时,企业内购相关登录记录也清除(根据当前openid清除)
//			try {
//				neigouManager.quitNeigouLogin(openId);
//			}catch (Exception e){
//				log.error("企业内购退出登录异常 ===>:" + e.getMessage(),e);
//			}

			//退出个人时 企业相关信息也要退出 qzy
			if (StringUtils.isEmpty(orgId)) {
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			if (StringUtil.isNotEmpty(orgId) && StringUtil.isNotEmpty(accountId) && StringUtil.isNotEmpty(openId)) {

				List<UserAccountRecode> list = userAccountService.getUserAccountByAccount(orgId, accountId, openId);
				if (list != null && list.size() == 1) {
					UserAccountRecode recode = list.get(0);
					recode.setModifier(openId);
					recode.setModifyTime(new Date());
					recode.setIsOnline("1");
					userAccountService.updateUserAccount(recode);
					return AppResultUtil.createSuccesDto();
				} else {
					return AppResultUtil.createErrorDto("100", "账号记录出现异常");
				}
				//退出个人时 企业相关信息也要退出 qzy
			}

			return AppResultUtil.createSuccesDto();

		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "返回信息：" + e.getMessage());
		}
	}
}
