package com.iamberry.wechat.handles.admin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.Page;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Integral;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.IntegralService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.face.relationship.WdRelationService;
import com.iamberry.wechat.tools.PropertiesUtils;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * 后台会员管理 description:
 * 
 * @author: 张应真
 * @createDate: 2016年4月29日
 */
@Controller
@RequestMapping("/admin/member")
public class AdminMemberHandler {
	@Autowired
	private MemberService memberService;
	// 将后台数据传输到前端
	// private Map<String, Object> maps = new HashMap<String, Object>();

	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private IntegralService integralService;
	
	@Autowired
	private WdRelationService wdRelationService;
	
	@Autowired
	private DealerRelationService dealerRelationService;
	
	@Autowired
	private PlaceInfoService placeInfoService;

	/**
	 * 加载所有会员列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/listUI", method = RequestMethod.POST)
	public ModelAndView showMemberList(
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize,
			HttpServletRequest request) throws Exception {

		Page page = new Page();
		page.setPageNo((pageNO - 1) * pageSize);
		int count = memberService.getCount();
		int pageCount = count % pageSize == 0 ? count / pageSize : count
				/ pageSize + 1;
		page.setPageSize(pageSize);
		List<Member> memberList = memberService.getMemberByPage(page);
		ModelAndView mv = new ModelAndView();
		mv.addObject("memberList", memberList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("pageSize", pageCount);
		mv.addObject("url", "/admin/member/listUI?pageSize=" + pageSize
				+ "&pageNO=");
		mv.setViewName("/admin/member/list");
		return mv;
	}

	/**
	 * 跳转到会员详细信息页面
	 * 
	 * @param userId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/showMenberInfo/{userId}")
	public ModelAndView showMemberInfo(@PathVariable int userId)
			throws UnsupportedEncodingException {
		Member member = new Member();
		member = memberService.getMemberByUserId(userId);
		member.setUserNickname(URLDecoder.decode(
				member.getUserNickname() == null ? "无昵称" : member
						.getUserNickname(), "UTF-8")); // 设置昵称
		ModelAndView mv = new ModelAndView("/admin/member/memberinfo");
		String parentName = "";
		if (member == null) {
			return mv;
		}
		if (member.getUserResType() == 2) {
			//父级是微代理层
			WdRelation wdRelation = wdRelationService.getWdRelationByOpenid(member.getUserOpenid());
			Member parentMember = memberService.getMemberByUserId(wdRelation.getWdFirst());
			parentName = URLDecoder.decode(parentMember.getUserNickname(),"UTF-8");
		} else if (member.getUserResType() == 3) {
			//父级是商户层
			DealerRelation dealerRelation = dealerRelationService.getDealerRelationById(member.getUserDealers());
			if (dealerRelation == null) {
				mv.addObject("member", member);
				mv.addObject("parentName", parentName);
				return mv;
			}
			int dealerId = 0;
			if (dealerRelation.getDealerSixth() != null) {
				dealerId = dealerRelation.getDealerSixth();
			} else if (dealerRelation.getDealerFifth() != null) {
				dealerId = dealerRelation.getDealerFifth();
			} else if (dealerRelation.getDealerFourth() != null) {
				dealerId = dealerRelation.getDealerFourth();
			} else if (dealerRelation.getDealerThird() != null) {
				dealerId = dealerRelation.getDealerThird();
			} else if (dealerRelation.getDealerSecond() != null) {
				dealerId = dealerRelation.getDealerSecond();
			} else if (dealerRelation.getDealerFirst() != null) {
				dealerId = dealerRelation.getDealerFirst();
			}
			PlaceInfo placeInfo = new PlaceInfo();
			placeInfo.setId(dealerId);
			placeInfo = placeInfoService.getOnePlaceInfoByInitcode(placeInfo);
			parentName = placeInfo.getName();
		}
		mv.addObject("member", member);
		mv.addObject("parentName", parentName);
		return mv;

	}

	/**
	 * 返回当前用户所有积分信息列表
	 * 
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showIntegralLogs/{userOpenid}", method = RequestMethod.GET)
	public ModelAndView getIntegralByOpenId(
			HttpServletRequest request,
			@PathVariable String userOpenid,
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize)
			throws Exception {

		Member member = new Member();
		Page page = new Page();
		page.setPageNo((pageNO - 1) * pageSize);
		page.setPageSize(pageSize);
		member.setPage(page);
		member.setUserOpenid(userOpenid);
		List<Integral> integrals = integralService
				.getIntegralListByOpenId(member);
		ModelAndView mv = new ModelAndView();
		mv.addObject("integrals", integrals);
		mv.setViewName("/admin/member/Integrallogs");
		return mv;

	}

	/**
	 * 查找会员列表
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/listUI", method = RequestMethod.GET)
	public ModelAndView findMemberList(
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize,
			HttpServletRequest request, String beginDate, String endDate,
			String userInput) throws Exception {
		// 获取请求页面时的URL
		Page page = new Page();
		// 写入参数
		Map params = new HashMap<String, Object>();
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		params.put("userInput", userInput);
		page.setPageSize(0);
		page.setPageNo(0);
		page.setParams(params);
		List<Member> memberListSize = memberService.getMemberByPage(page);// 查询第一次，确定总数
		int count = memberListSize.size();

		int pageCount = count % pageSize == 0 ? count / pageSize : count
				/ pageSize + 1;
		page.setPageNo((pageNO - 1) * pageSize);//
		page.setPageSize(pageSize);

		List<Member> memberList = memberService.getMemberByPage(page);
		for (Member member : memberList) {
			member.setUserNickname(URLDecoder.decode(
					member.getUserNickname() == null ? "无昵称" : member
							.getUserNickname(), "UTF-8")); // 设置昵称
		}
		ModelAndView mv = new ModelAndView();
		// 写入页面需要参数
		mv.addObject("userInput", userInput);
		mv.addObject("beginDate", beginDate);
		mv.addObject("endDate", endDate);

		mv.addObject("memberList", memberList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("pageSize", pageCount);
		StringBuffer url = new StringBuffer("/admin/member/listUI?");
		url.append("pageSize=" + pageSize);
		if (userInput != null) {
			url.append("&userInput=" + userInput);
		}
		if (userInput != null) {
			url.append("&beginDate=" + beginDate);
		}
		if (userInput != null) {
			url.append("&endDate=" + endDate);
		}
		url.append("&pageNO=");
		mv.addObject("url", url.toString());
		mv.setViewName("/admin/member/list");
		return mv;
	}
	/**
	 * 活动信息显示
	 * @return
	 * @throws FileNotFoundException
	 */
	@RequestMapping("/activity")
	public ModelAndView showActivityInfo() throws FileNotFoundException {
		String filePath = "resource" + File.separator + "ResultInfo.properties";
		//获取ResultInfo.properties路径
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
        ServletContext servletContext = webApplicationContext.getServletContext(); 
        InputStream in=servletContext.getResourceAsStream("/WEB-INF/classes/ResultInfo.properties");
		
        Map<String,String>map=PropertiesUtils.readProperties(in);
             
 //     System.out.println("map:"+map);
        String cartDesc=map.get("CARTDESC");
        String isShow = map.get("ISSHOW");
        String cartUrl=map.get("CART_URL");
		ModelAndView mv = new ModelAndView();
		List<String> list = new ArrayList<String>();
		list.add(cartDesc);
		list.add(isShow);
		list.add(cartUrl);
//System.out.println("============="+list);
		mv.addObject("cartDesc", cartDesc);
		mv.addObject("isShow", isShow);
		mv.addObject("cartUrl", cartUrl);
		mv.setViewName("/admin/activity/cartActivity");
		return mv;

	}
	/**
	 * 跳转到修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateInfo")
	public ModelAndView updateInfo(HttpServletRequest request){

		try {
			ModelAndView mv=new ModelAndView();
			mv.addObject("isShow",new  String(request.getParameter("isShow").getBytes("ISO8859-1"),"UTF-8"));
			mv.addObject("cartDesc",new  String(request.getParameter("cartDesc").getBytes("ISO8859-1"),"UTF-8"));
			mv.addObject("cartUrl",new  String(request.getParameter("cartUrl").getBytes("ISO8859-1"),"UTF-8"));
			
			mv.setViewName("/admin/activity/editActivity");
			return mv;
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	/**
	 * 保存修改信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveActivity")
	public String saveActivity(HttpServletRequest request){
		String isShow = "";
		String cartUrl = "";
		String cartDesc = "";
		try {
//System.out.println(request.getParameter("cartUrl")+"-------------");
			WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
			ServletContext servletContext = webApplicationContext.getServletContext(); 
			
			String path= servletContext.getRealPath("/WEB-INF/classes/ResultInfo.properties");
//System.out.println("=====路径==="+path);
			 isShow = request.getParameter("isShow");//new  String(request.getParameter("isShow").getBytes("ISO8859-1"),"UTF-8");
			 cartUrl = request.getParameter("cartUrl");//new  String(request.getParameter("cartUrl").getBytes("ISO8859-1"),"UTF-8");
			 cartDesc = request.getParameter("cartDesc");//new  String(request.getParameter("cartDesc").getBytes("ISO8859-1"),"UTF-8");
			
			PropertiesUtils.writeProperties(path, "ISSHOW",isShow );
			PropertiesUtils.writeProperties(path, "CART_URL", cartUrl);
			PropertiesUtils.writeProperties(path, "CARTDESC", cartDesc);
//System.out.println("更新完成~~");
			return "{\"status\":\"修改成功!\"}" ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "{\"status\":\"修改异常!\"}" ;
		}
	}

	/**
	 * 通过openid查询userid
	 * @param request
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectUserIdByOpenId")
	public ResultMsg selectUserIdByOpenId(HttpServletRequest request,
			@RequestParam(value = "openId", defaultValue = "", required = false) String openId) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		if (openId == null || "".equals(openId)) {
			resultMsg.setData("");
			resultMsg.setMessage(ResultInfo.ERRORINFO);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setStatus(false);
			return resultMsg;
		}
		Member member = memberService.getMemberByUserOpenId(openId);
		if (member == null) {
			resultMsg.setData("");
			resultMsg.setMessage(ResultInfo.ERRORINFO);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setStatus(false);
			return resultMsg;
		} else {
			resultMsg.setData(member.getUserId());
			resultMsg.setMessage(ResultInfo.SUCCESSINFO);
			resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
			resultMsg.setStatus(true);
			return resultMsg;
		}
	}
}
