package com.palmnest.webapp.controller.backstage;

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.DateUtils;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.dto.OutRetMsg;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.UserImageInfo;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.MemberManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.VisitorInFoManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 会员信息管理前端控制器
 *
 * @author yubing
 * @since 2017-2-15
 */
@Slf4j
@Controller
@RequestMapping(value = "/member/*")
public class MemberController extends BaseFormController {


	@Autowired
	private MemberManager    memberManager;	
	@Autowired
	private ScWxuserManager    scWxuserManager;
	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private PropertyManager    propertyManager;
	@Autowired
	private VisitorInFoManager visitorInFoManager;

	@RequestMapping(value = "/list")
	public ModelAndView handleRequest(HttpServletRequest request,
									  HttpServletResponse response) throws Exception {
		initFunctionOperate(request); // 初始化功能操作权限
		Model  model          = new ExtendedModelMap();
		String pageNo         = request.getParameter("pageNo");
		String keyWord        = request.getParameter("keyWord");
		String organizationId = request.getParameter("organizationId");
		String virtualId      = request.getParameter("virtualId");
		String bgTime         = request.getParameter("bgTime");
		String endTime        = request.getParameter("endTime");
		String status         = request.getParameter("status");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}

		model.addAttribute("keyWord", keyWord);
		model.addAttribute("organizationId", organizationId);
		model.addAttribute("virtualId", virtualId);
		model.addAttribute("bgTime", bgTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("status", status);
		//管理项目的范围权限集合
		List<TbOrganization> organizationList = getUserRelationOrgList(request);

		Page page = scWxuserManager.getMemberPage(Integer.parseInt(pageNo),
				keyWord, organizationId, virtualId, bgTime, endTime,
				getUserRelationOrganizationStr(organizationList), status);
		model.addAttribute("page", page);
		model.addAttribute("organizationList", organizationList);
		return new ModelAndView("admin/member/memberList", model.asMap());
	}

	@RequestMapping(value = "/userlist")
	public ModelAndView userlist(HttpServletRequest request,
								 HttpServletResponse response) throws Exception {
//		initFunctionOperate(request); // 初始化功能操作权限   旧版权限
		Model  model          = new ExtendedModelMap();
		String pageNo         = request.getParameter("pageNo");
		String keyWord        = request.getParameter("keyWord");
		String organizationId = request.getParameter("organizationId");
		String virtualId      = request.getParameter("virtualId");
		String bgTime         = request.getParameter("bgTime");
		String endTime        = request.getParameter("endTime");
		String status         = request.getParameter("status");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}

		model.addAttribute("keyWord", keyWord);
		model.addAttribute("organizationId", organizationId);
		model.addAttribute("virtualId", virtualId);
		model.addAttribute("bgTime", bgTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("status", status);
		//管理项目的范围权限集合
		List<TbOrganization> organizationList = getUserRelationOrgList(request);

		Page page = scWxuserManager.getUserPage(Integer.parseInt(pageNo),
				keyWord, organizationId, virtualId, bgTime, endTime,
				getUserRelationOrganizationStr(organizationList), status);
		model.addAttribute("page", page);
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
		return new ModelAndView("admin/member/memberList", model.asMap());
	}

	@RequestMapping(value = "/unselectedItemuserlist")
	public ModelAndView unselectedItemuserlist(HttpServletRequest request,
											   HttpServletResponse response) throws Exception {
		initFunctionOperate(request); // 初始化功能操作权限
		Model  model   = new ExtendedModelMap();
		String pageNo  = request.getParameter("pageNo");
		String keyWord = request.getParameter("keyWord");
		String bgTime  = request.getParameter("bgTime");
		String endTime = request.getParameter("endTime");
		String status  = request.getParameter("status");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		model.addAttribute("keyWord", keyWord);
		model.addAttribute("bgTime", bgTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("status", status);
		Page page = scWxuserManager.getUnselectdUserPage(Integer.parseInt(pageNo),
				keyWord, bgTime, endTime, status);
		model.addAttribute("page", page);
		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
		return new ModelAndView("admin/member/unselectedItemuserlist", model.asMap());
	}

	@RequestMapping(value = "/info")
	public ModelAndView info(HttpServletRequest request,
							 HttpServletResponse response) throws Exception {
		Model   model   = new ExtendedModelMap();
		String  userId  = request.getParameter("userId");
		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		if (appUser.getOrganizationId() != null) {
			model.addAttribute("organizationName", propertyManager.getTbOrganizationById(appUser.getOrganizationId()).getName());
		}
		if (appUser.getVirtualArchId() != null) {
			model.addAttribute("virtualName", propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId()).getName());
		}
		model.addAttribute("model", appUser);
		model.addAttribute("funcId", request.getParameter("funcId"));

		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
		return new ModelAndView("admin/member/memberInfo", model.asMap());
	}

	@RequestMapping(value = "/form")
	public ModelAndView form(@ModelAttribute("appUser") AppUser appUser, HttpServletRequest request,
							 HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		// 管理项目的范围权限集合
		String  userId         = request.getParameter("userId");
		String  saveType       = request.getParameter("saveType");
		Integer organizationId = 0;
		AppUser au             = new AppUser();
		// 编辑用户信息,先查询出用户信息
		if ((appUser != null && appUser.getId() != null)) {
			au = appUserManager.get(appUser.getId());
		} else if (StringUtils.isNotEmpty(userId)) {
			au = appUserManager.get(Integer.parseInt(userId));
		}

		if (au != null && au.getId() != null) {
			appUser.setIsResponsible(au.getIsResponsible());
		}
		if (StringUtils.isNotBlank(userId)) {
			AppUser aUser = appUserManager.get(Integer.parseInt(userId));
			organizationId = aUser.getOrganizationId();
			if (aUser.getOrganizationId() != null) {
				List<VirtualArchitecture> virtualList = propertyManager
						.getVirtualArchitectureList(aUser.getOrganizationId(), "1");
				model.addAttribute("virtualList", virtualList);
			}
			if (aUser.getVirtualArchId() != null) {
				List<VirtualArchitecture> dempentList = propertyManager
						.getVirtualArchitectureList(aUser.getVirtualArchId() + "");
				model.addAttribute("dempentList", dempentList);
			}
			model.addAttribute("appUser", aUser);

			// 查询该员工人脸照片信息
			List<UserImageInfo> list = visitorInFoManager.getUserImageInfo(
					aUser.getId(), "1");
			// 如果查询结果为空则往list中塞入三个空对象;
			// 如果不为空且个数小于3,则将查询出的对象塞入list,并用空对象补齐三个,然后返回页面???
			if (list != null && list.size() > 0) {
				Integer sum = 3 - list.size();
				for (int i = 0; i < sum; i++) {
					list.add(new UserImageInfo());
				}
			} else {
				list = new ArrayList<UserImageInfo>();
				for (int i = 0; i < 3; i++) {
					list.add(new UserImageInfo());
				}
			}
			model.addAttribute("list", list);

		} else if (StringUtils.isBlank(saveType)) {
			List<UserImageInfo> list = new ArrayList<UserImageInfo>();
			for (int i = 0; i < 3; i++) {
				list.add(new UserImageInfo());
			}
			model.addAttribute("list", list);
		}

		if ("save".equals(saveType)) {
			String              userMobile   = appUser.getUserMobile();
			AppUser             appUser2     = appUserManager.getAppUsersByPhone(userMobile);
			String              imageUrlids  = request.getParameter("imageUrlids");// tb_userimageinfo表中该用户对应的图片id串
			String              removeUrlids = request.getParameter("removeUrlids");
			String              addimgUrls   = request.getParameter("addimgUrls");
			List<UserImageInfo> list         = new ArrayList<UserImageInfo>();
			// 获取用户企业信息
			List<VirtualArchitecture> virtualList = propertyManager
					.getVirtualArchitectureList(appUser.getOrganizationId(),
							"1");
			// 获取用户部门信息
			List<VirtualArchitecture> dempentList = propertyManager
					.getVirtualArchitectureList(appUser.getVirtualArchId() + "");
			model.addAttribute("virtualList", virtualList);
			model.addAttribute("dempentList", dempentList);

			if (StringUtils.isNotBlank(imageUrlids)) {
				for (String str : getStr(imageUrlids)) {
					UserImageInfo userImageInfo = visitorInFoManager
							.getUserImageInfoById(Integer.parseInt(str));
					list.add(userImageInfo);
				}
			}

			if (StringUtils.isNotBlank(addimgUrls)) {
				for (String str : getStr(addimgUrls)) {
					UserImageInfo userImageInfo = new UserImageInfo();
					userImageInfo.setImageUrl(str);
					list.add(userImageInfo);
				}
			}

			if (list.size() > 0) {
				Integer sum = 3 - list.size();
				for (int i = 0; i < sum; i++) {
					list.add(new UserImageInfo());
				}
			} else {
				list = new ArrayList<UserImageInfo>();
				for (int i = 0; i < 3; i++) {
					list.add(new UserImageInfo());
				}
			}
			model.addAttribute("list", list);
			model.addAttribute("imageUrlids", imageUrlids);
			model.addAttribute("removeUrlids", removeUrlids);
			model.addAttribute("addimgUrls", addimgUrls);
			if (appUser2 != null && !appUser2.getId().equals(appUser.getId())) {
				model.addAttribute("code", "error");
				model.addAttribute("errormsg", "手机号码已存在！");
				return new ModelAndView("admin/member/memberForm",
						model.asMap());
			}
			appUser.setIsEnabled("1");
			//管理员，默认开通接收通知
			if ("1".equals(appUser.getRoleType())) {
				appUser.setNoticePower("1");
			} else {
				appUser.setNoticePower("0");
			}

			if (appUser.getId() != null) {
				// 编辑修改用户信息
				//appUser.setStatus("1");
				String oldUserMobile = request.getParameter("oldUserMobile");
				appUser.setOrganizationName(oldUserMobile);  //临时用organizationName存储旧手机号码

				Map<String, Object> resultMap = appUserManager
						.updateAppUserInfo(appUser, imageUrlids, removeUrlids,
								addimgUrls);
				model.addAttribute("imageServer",
						FileUploadUtils.getVisitPrefix());
				if ((Boolean) resultMap.get("flag")) {
					model.addAttribute("code", "success");
					model.addAttribute("errormsg", resultMap.get("desc") + "");
				} else {
					model.addAttribute("code", "error");
					model.addAttribute("errormsg", resultMap.get("desc") + "");
				}
			} else {
				// 新增用户信息
				appUser.setIsEnabled("1");
				//appUser.setStatus("1");
				appUser.setCreateTime(new Date());
				Map<String, Object> resultMap = appUserManager
						.updateAppUserInfo(appUser, imageUrlids, removeUrlids,
								addimgUrls);
				if ((Boolean) resultMap.get("flag")) {
					model.addAttribute("code", "success");
					model.addAttribute("errormsg", resultMap.get("desc") + "");
				} else {
					model.addAttribute("code", "error");
					model.addAttribute("errormsg", resultMap.get("desc") + "");
				}
			}
		}
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		model.addAttribute("organizationList", organizationList);
		for (TbOrganization t : organizationList) {
			if (t.getId().equals(organizationId)) {
				model.addAttribute("organizationName", t.getName());
				break;
			}
		}
		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
		model.addAttribute("personRoleGroup", this.getElementGroupManager().getElementsByGroupName("personRoleGroup"));
		return new ModelAndView("admin/member/memberForm", model.asMap());
	}

	@RequestMapping(value = "/reviewOperate")
	public @ResponseBody
	String reviewOperate(HttpServletRequest request,
						 HttpServletResponse response) throws Exception {
		String userId     = request.getParameter("userId");
		String status     = request.getParameter("status");
		String suggestion = request.getParameter("suggestion");
		String userName   = request.getParameter("userName");

		suggestion = suggestion + ";" + userName;

		return appUserManager.updateAppUser(Integer.parseInt(userId), status, suggestion, request.getRemoteUser(), "1");
	}

	/**
	 * 下载員工导入的模板
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "exportUserModel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
	public @ResponseBody
	OutRetMsg exportBillModel(HttpServletRequest request, HttpServletResponse response) {
		String organizationId = request.getParameter("organizationId");
		String path           = request.getRealPath(File.separator + "upload");
		String datastr        = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
		String fileName       = "UserTemplate" + datastr + ".xlsx";
		String fileFullPath   = path + File.separator + fileName;
		String retFlag        = appUserManager.exportUserModel(fileFullPath, organizationId);
		String absolutePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		OutRetMsg retMsg = new OutRetMsg();
		retMsg.setErrcode(retFlag);
		retMsg.setErrmsg(absolutePath + "/upload/" + fileName);
		return retMsg;
	}

	@RequestMapping(value = "/importUserModel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public ModelAndView importUserModel(@RequestParam("excelFile") MultipartFile excelFile,
										HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model               model  = new ExtendedModelMap();
		Map<String, Object> retMap = null;
		try {
			retMap = appUserManager.saveImportUserData(excelFile.getInputStream());
			model.addAllAttributes(retMap);
			String dataSessionUid = UUID.randomUUID().toString();
			request.getSession().setAttribute(dataSessionUid, retMap.get("data"));
			model.addAttribute("dataSessionUid", dataSessionUid);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		model.addAttribute("excelFileName", excelFile.getOriginalFilename());
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/member/memberListResult", model.asMap());
	}

	@RequestMapping(value = "/importUserModelList", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public ModelAndView importUserModelList(HttpServletRequest request, HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/member/memberListImport", model.asMap());
	}

	/**
	 * 确认导入处理
	 *
	 * @throws Exception
	 */
	@RequestMapping(value = "/confirmImportUser", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public ModelAndView confirmImportBill(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model         model          = new ExtendedModelMap();
		String        dataSessionUid = request.getParameter("dataSessionUid");
		List<AppUser> list           = (List<AppUser>) request.getSession().getAttribute(dataSessionUid);
		if (list != null) {
			request.getSession().removeAttribute(dataSessionUid);
			Map<String, Object> map = appUserManager.saveAppUser(list);
			model.addAttribute("map", map);
		}
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("redirect:/member/userlist", model.asMap());
	}

	/**
	 * 企业员工信息添加人脸图片识别上传
	 * 微信端访客邀约人脸识别校验
	 *
	 * @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
	 * @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
	 */
	@RequestMapping(value = "/updateKoalaImg")
	@ResponseBody
	public AppResultDto updateAppUser(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 = "/deleteUserInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String deleteUserInfo(HttpServletRequest request) throws IOException, ParseException, JSONException {
		try {
			String userId = request.getParameter("userId");
			if (StringUtils.isNotBlank(userId)) {

			}
		} catch (Exception e) {
			log.error("删除用户信息:" + e.getMessage());
		}
		return "error";
	}


	public String[] getStr(String str) {
		return str.substring(0, str.length() - 1).split(",");
	}


}
