package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
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.dto.CommonDto;
import com.palmnest.application.dto.output.WechatUserInfoDto;
import com.palmnest.model.VirtUserInfo;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.UserImageInfo;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.property.PropertyManager;
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.util.*;

/**
 * 人员信息管理
 *
 * @author yubing
 * @since 2017-07-07
 */
@Slf4j
@Controller
@RequestMapping(value = "/wechat/memberManage*")
public class MemberManageController {


	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private ScWxuserManager    scWxuserManager;
	@Autowired
	private PropertyManager    propertyManager;
	@Autowired
	private VisitorInFoManager visitorInFoManager;
	@Autowired
	private VirtUserManager    virtUserManager;
	@Autowired
	private EmigrationManager  emigrationManager;

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

	/**
	 * 进入企业人员信息管理页面
	 */
	@RequestMapping(value = "/memberManageList")
	public ModelAndView memberManageList(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Model model = new ExtendedModelMap();

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

		AppUser             appUser = appUserManager.get(Integer.parseInt(userId));
		VirtualArchitecture virtual = propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId());

		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("appUser", appUser);
		model.addAttribute("wxUser", scWxuserManager.getScWxuserByOpenId(openId));

		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);

		if (wxUser != null) {
			List<CommonDto> listDto = emigrationManager.getVirListByReman(wxUser.getUserId());
			model.addAttribute("virList", listDto);
		}

		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
		model.addAttribute("webUrl", webUrl);
		model.addAttribute("virtualName", virtual.getName());

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

	@RequestMapping(value = "/getAppUserByVirId")
	@ResponseBody
	public AppResultDto getAppUserByVirId(int virtId) {
		List<WechatUserInfoDto> userDtoList = new ArrayList<WechatUserInfoDto>();
		try {
			List<AppUser> userList = appUserManager.getAppUserByVirId(virtId);//获取企业普通用户
			if (userList != null && userList.size() > 0) {
				for (int i = 0; i < userList.size(); i++) {
					AppUser           user     = userList.get(i);
					WechatUserInfoDto userInfo = new WechatUserInfoDto();
					userInfo.setId(user.getId());
					userInfo.setStatus(user.getStatus());
					userInfo.setTelephone(user.getUserMobile());
					userInfo.setUserName(user.getUserName());
					userInfo.setIsManager(0);
					userInfo.setPhoto(user.getUserPhotoUrl());
					userDtoList.add(userInfo);
				}
			}
			List<VirtUserInfo> virUserList = virtUserManager.getVirtUserByVirtId(virtId);//获取企业负责人
			if (virUserList != null && virUserList.size() > 0) {
				for (int i = 0; i < virUserList.size(); i++) {
					VirtUserInfo      virUser  = virUserList.get(i);
					AppUser           user     = appUserManager.get(virUser.getUserId());
					WechatUserInfoDto userInfo = new WechatUserInfoDto();
					userInfo.setId(user.getId());
					userInfo.setStatus(user.getStatus());
					userInfo.setTelephone(user.getUserMobile());
					userInfo.setUserName(user.getUserName());
					userInfo.setPhoto(user.getUserPhotoUrl());
					userInfo.setIsManager(0);
					for (int j = 0; j < userDtoList.size(); j++) {
						WechatUserInfoDto dto = userDtoList.get(j);
						if (userInfo.getId().equals(dto.getId())) {
							userDtoList.remove(dto);
						}
					}
					userInfo.setIsManager(1);
					userDtoList.add(userInfo);
				}
			}

			Collections.sort(userDtoList, new Comparator<WechatUserInfoDto>() {
				public int compare(WechatUserInfoDto o1, WechatUserInfoDto o2) {
					// 按照认证状态进行排序
					int o1Status = Integer.parseInt(o1.getStatus());
					int o2Status = Integer.parseInt(o2.getStatus());
					if (o1Status > o2Status) {
						return 1;
					}
					if (o1Status == o2Status) {
						return 0;
					}
					return -1;
				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}


		return AppResultUtil.createSuccesDto(userDtoList);
	}

	/**
	 * 获取管理的用户列表信息
	 */
	@RequestMapping(value = "/getMemberList", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	Page getMemberList(HttpServletRequest request, HttpServletResponse response) {
		String userId    = request.getParameter("userId");
		String virtualId = request.getParameter("virtualId");
		String pageNo    = request.getParameter("pageNo");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		Page page = appUserManager.queryAppUserList(Integer.parseInt(userId), Integer.parseInt(virtualId), Integer.parseInt(pageNo), 10);
		return page;
	}

	/**
	 * 设置接收通知的开关处理
	 */
	@RequestMapping(value = "/updateNoticePower", method = {RequestMethod.POST})
	public @ResponseBody
	String updateNoticePower(HttpServletRequest request, HttpServletResponse response) {
		String  userId      = request.getParameter("userId");
		String  noticePower = request.getParameter("noticePower");
		AppUser appUser     = appUserManager.get(Integer.parseInt(userId));
		appUser.setNoticePower(noticePower);
		appUserManager.updateModel(appUser);
		return "success";
	}

	/**
	 * 管理员审核用户
	 */
	@RequestMapping(value = "/reviewAppUser", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	Map<String, String> reviewAppUser(HttpServletRequest request, HttpServletResponse response) {
		String userId       = request.getParameter("userId");
		String acceptUserId = request.getParameter("acceptUserId"); //接收处理的用户ID
		String status       = request.getParameter("status");
		return appUserManager.assignReviewUser(Integer.parseInt(userId), Integer.parseInt(acceptUserId), status);
	}

	/**
	 * 设置用户为管理员
	 */
	@RequestMapping(value = "/setRoleAppUser", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	Map<String, String> setRoleAppUser(HttpServletRequest request, HttpServletResponse response) {
		String userId       = request.getParameter("userId");
		String acceptUserId = request.getParameter("acceptUserId"); //接收处理的用户ID
		return appUserManager.assignSetRoleAppUser(Integer.parseInt(userId), Integer.parseInt(acceptUserId));
	}

	/**
	 * 分享链接
	 * 邀请用户加入企业业务处理
	 */
	@RequestMapping(value = "/joinCompanyPage")
	public ModelAndView joinCompanyPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model        = new ExtendedModelMap();
		String openId       = request.getParameter("openId");
		String developId    = request.getParameter("developId");
		String userId       = request.getParameter("userId");
		String manageUserId = request.getParameter("manageUserId");

		AppUser manageUser = appUserManager.get(Integer.parseInt(manageUserId));

		if (StringUtils.isNotBlank(userId)) {
			AppUser appUser = appUserManager.get(Integer.parseInt(userId));
			//如果用户认证通过，并且与邀请者用户所在企业相同，则进入个人信息主页
			if ("1".equals(appUser.getStatus()) &&
					appUser.getVirtualArchId().intValue() == manageUser.getVirtualArchId().intValue()) {
				//进入个信息页面
				model.addAttribute("openId", openId);
				model.addAttribute("developId", developId);
				model.addAttribute("userId", userId);
				return new ModelAndView("redirect:/wechat/appUser/userInfo", model.asMap());
			} else {
				List<UserImageInfo> list = visitorInFoManager.getUserImageInfo(Integer.parseInt(userId), "1");
				model.addAttribute("list", list);
				if (appUser.getVirtualArchId() != null) {
					model.addAttribute("appUserVname", propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId()).getName());
				}
				model.addAttribute("appUser", appUser);
			}
		}
		//进入邀请加入企业信息页面
		VirtualArchitecture virtual = propertyManager.getVirtualArchitectureById(manageUser.getVirtualArchId());
		model.addAttribute("manageUser", manageUser);
		model.addAttribute("virtual", virtual);
		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		return new ModelAndView("wechat/joinCompayPage", model.asMap());
	}

	/**
	 * 邀请用户加入企业
	 */
	@RequestMapping(value = "/assignJoinCompay", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	Map<String, String> assignJoinCompay(HttpServletRequest request, HttpServletResponse response) {
		log.info("----assignJoinCompay----");
		Map<String, String> paramsMap = new HashMap<String, String>();
		String              openId    = request.getParameter("openId");
		String              developId = request.getParameter("developId");

		String manageUserId    = request.getParameter("manageUserId");
		String userId          = request.getParameter("userId");
		String virtualId       = request.getParameter("virtualId");
		String name            = request.getParameter("name");
		String zhengjianImage  = request.getParameter("zhengjianImage");        //证件照片集合
		String headRelativeUrl = request.getParameter("headRelativeUrl");        //头像
		String dataUrl         = request.getParameter("dataUrl");
		if (StringUtils.isBlank(userId)) {
			String userMobile = request.getParameter("userMobile");
			String authCode   = request.getParameter("authCode");
			paramsMap.put("userMobile", userMobile);
			paramsMap.put("authCode", authCode);
		}
		paramsMap.put("openId", openId);
		paramsMap.put("developId", developId);
		paramsMap.put("manageUserId", manageUserId);
		paramsMap.put("userId", userId);
		paramsMap.put("virtualId", virtualId);
		paramsMap.put("name", name);
		paramsMap.put("zhengjianImage", zhengjianImage);
		paramsMap.put("headRelativeUrl", headRelativeUrl);
		paramsMap.put("dataUrl", dataUrl);

		return appUserManager.assignJoinVirtual(paramsMap);
	}
}
