package com.apobates.forum.trident.controller.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.trident.exception.ResourceNotFoundException;
import com.apobates.forum.trident.vo.MemberActionBean;
import com.apobates.forum.trident.controller.form.MemberLeaderForm;
import com.apobates.forum.trident.controller.form.MemberPassportForm;
import com.apobates.forum.core.api.service.TopicActionCollectionService;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.event.elderly.MemberActionDescriptor;
import com.apobates.forum.member.MemberBaseProfile;
import com.apobates.forum.member.MemberProfileBean;
import com.apobates.forum.member.api.service.MemberActiveRecordsService;
import com.apobates.forum.member.api.service.MemberContactService;
import com.apobates.forum.member.api.service.MemberOnlineService;
import com.apobates.forum.member.api.service.MemberRealAuthenticationService;
import com.apobates.forum.member.api.service.MemberService;
import com.apobates.forum.member.api.service.MemberSocialInfoService;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberActiveRecords;
import com.apobates.forum.member.entity.MemberContact;
import com.apobates.forum.member.entity.MemberGroupEnum;
import com.apobates.forum.member.entity.MemberOnline;
import com.apobates.forum.member.entity.MemberRealAuthentication;
import com.apobates.forum.member.entity.MemberRoleEnum;
import com.apobates.forum.member.entity.MemberSocialInfo;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.utils.CommonBean;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.lang.EnumArchitecture;
/**
 * 会员控制器
 * 
 * @author xiaofanku@live.cn
 * @since 20190321
 */
@Controller
@RequestMapping(value = "/admin/member")
public class AdminMemberController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private MemberContactService memberContactService;
	@Autowired
	private MemberRealAuthenticationService memberRealAuthenticationService;
	@Autowired
	private MemberSocialInfoService memberSocialInfoService;
	@Autowired
	private TopicActionCollectionService topicActionCollectionService;
	@Autowired
	private MemberActiveRecordsService memberActiveRecordsService;
	@Autowired
	private MemberOnlineService memberOnlineService;
    @Value("${site.pageSize}")
    private int pageSize;
    
	// 最近注册的会员
	@GetMapping(path="/")
	public String listPage(HttpServletRequest request, Model model) {
		model.addAttribute("rs", memberService.getRecent(pageSize).collect(Collectors.toList()));
		return "admin/member/index";
	}
	
	// 会员首页
	@GetMapping(path="/{id}.xhtml")
	public String homePage(@PathVariable("id") long memberId, HttpServletRequest request, Model model) {
		Member m = memberService.get(memberId).orElseThrow(()->new ResourceNotFoundException("指定的会员不存在或暂时无法访问"));
		model.addAttribute("member", m);
		//
		EnumMap<ForumActionEnum, Long> actionStats = topicActionCollectionService.groupMemberTopicAction(memberId); 
		MemberProfileBean memberProfile = memberService.getMemberProfileBean(memberId, actionStats).orElse(MemberProfileBean.empty(memberId, m.getNames(), m.getMgroup().getTitle(), m.getMrole().getTitle(), MemberBaseProfile.getStyle(m.getMgroup(), m.getMrole()), m.getSignature()));
		Map<String, String> profile = memberProfile.toMap();
		//
		Optional<MemberOnline> mo = memberOnlineService.get(memberId);
		if(mo.isPresent()){
			try{
				profile.put("activeDateTime", DateTimeUtils.formatClock(mo.get().getActiveDateTime()));
			}catch(Exception e){
				profile.put("activeDateTime", "-");
			}
		}
		model.addAttribute("profile", profile);
		return "admin/member/view";
	}
	
	// 联系方式
	@GetMapping(path="/contact")
	public String contactPage(
			@RequestParam("member") long memberId, 
			HttpServletRequest request, 
			Model model) {
		MemberContact rs = memberContactService.getByMember(memberId).orElseThrow(()->new ResourceNotFoundException("指定会员的联系方式不存在或暂时无法访问"));
		model.addAttribute("contact", rs);
		return "admin/member_contact/index";
	}
	
	// 实名认证
	@GetMapping(path="/realauth")
	public String realauthPage(
			@RequestParam("member") long memberId, 
			HttpServletRequest request, 
			Model model) {
		MemberRealAuthentication rs = memberRealAuthenticationService.getByMember(memberId).orElseThrow(()->new ResourceNotFoundException("指定会员的实名认证不存在或暂时无法访问"));
		model.addAttribute("realauth", rs);
		return "admin/member_realauth/index";
	}
	
	// 社交信息
	@GetMapping(path="/social")
	public String socialPage(
			@RequestParam("member") long memberId, 
			HttpServletRequest request, 
			Model model) {
		MemberSocialInfo rs = memberSocialInfoService.getByMember(memberId).orElseThrow(()-> new ResourceNotFoundException("指定会员的社交信息不存在或暂时无法访问"));
		model.addAttribute("social", rs);
		return "admin/member_social/index";
	}
	
	// 整体:根据登录帐号查看会员
	@GetMapping(path="/search", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Long,String> lookMember(@RequestParam("names")String names, HttpServletRequest request, Model model){
		//是否以@开头
		if(!Commons.isNotBlank(names) || !names.startsWith("@")) {
			return Collections.emptyMap();
		}
		String memberNames = names.substring(1);
		Long memberId = memberService.existMemberNames(memberNames);
		Map<Long,String> data = new HashMap<>();
		data.put(memberId, memberNames);
		return data;
	}
	
	// 任命版主时根据登录帐号
	@GetMapping(path="/suggest", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<CommonBean> suggestMember(@RequestParam("names")String names, HttpServletRequest request, Model model) {
		return memberService.searchByNames(names, pageSize).map(mb -> new CommonBean(mb.getId(), mb.getNames())).collect(Collectors.toList());
	}
	//校验uid时的
	@GetMapping(path = "/detection/uid")
	@ResponseBody
	public TipMessage checkMemberUID(
			@RequestParam("value")String uidString, 
			MemberSessionBean mbean, 
			HttpServletRequest request, 
			Model model){
		long memberId = 0L;
		try{
			memberId = Long.valueOf(uidString.substring(1));
		}catch(Exception e){
			return TipMessage.ofError("非法的会员");
		}
		if(memberId <= 0){
			return TipMessage.ofError("会员不接受消息");
		}
		Member m = memberService.get(memberId).orElse(null);
		if(null == m || mbean.getMid() == m.getId()){
			return TipMessage.ofError("会员不存在");
		}
		return TipMessage.ofSuccess(m.getNickname());
	}
	//编辑密码
	@GetMapping(path="/passport")
	public String editForm(@RequestParam("id")long id, HttpServletRequest request, Model model) {
		MemberPassportForm form = new MemberPassportForm();
		form.setRecord(id);
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/member/passport";
	}
	@PostMapping(path="/passport")
	public String editAction(
			@ModelAttribute("form")MemberPassportForm form, 
			MemberSessionBean mbean, 
			HttpServletRequest request, 
			Model model) {
		Optional<Boolean> symbol = memberService.resetPswd(form.getLongRecord(), form.getNewpswd(), MemberActionDescriptor.getInstance(request, form.getToken()));
		if(symbol.orElse(false)){
			return "redirect:/admin/member/";
		}
		model.addAttribute("errors", "修改会员密码操作失败");
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/member/passport";
	}
	
	//新社区经理
	@GetMapping(path="/create")
	public String createTopicForm(
			HttpServletRequest request, 
			Model model){
		MemberLeaderForm form = new MemberLeaderForm();
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/member/create";
	}
	@PostMapping(path="/create")
	public String createTopicAction(
			@ModelAttribute("form")MemberLeaderForm form, 
			MemberSessionBean mbean, 
			HttpServletRequest request, 
			Model model){
		String errMsg="新增社区经理操作失败";
		try{
			long symbol = memberService.create(
				form.getNames(), 
				form.getPswd(), 
				Commons.optional(form.getNickname(), form.getNames()),
				form.getEnumRole(),
				MemberActionDescriptor.getInstance(request, form.getToken()));
			if(symbol>0){
				return "redirect:/admin/member/";
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		model.addAttribute("errors", errMsg);
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/member/create";
	}
	//会员角色
	@GetMapping(path="/role/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Integer,String> getAllRoles(HttpServletRequest request, Model model){
		return EnumArchitecture.getInstance(MemberRoleEnum.class);
	}
	//会员组
	@GetMapping(path="/group/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Integer,String> getAllGroup(HttpServletRequest request, Model model){
		//滤掉0,-1,-2
		return EnumArchitecture.getInstance(MemberGroupEnum.class);
	}
	//指定会员的操作记录
	@GetMapping(path="/action/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<MemberActionBean> getMemberOperateAction(
			@RequestParam("id")long memberId, 
			@RequestParam("names")String names, 
			HttpServletRequest request, 
			Model model){
		List<MemberActiveRecords> rs = memberActiveRecordsService.getByMember(memberId, names, pageSize).collect(Collectors.toList());
		List<MemberActionBean> data = new ArrayList<>();
		for(MemberActiveRecords ar : rs){
			data.add(new MemberActionBean(ar.getAction().getTitle(), DateTimeUtils.getRFC3339(ar.getActiveDateTime()), ar.getIpAddr(), ar.isSucceed()?"成功":"失败"));
		}
		return data;
	}
}
