package com.iamberry.wechat.handles.drp;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.drp.ApplyPlaceLogs;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.statictics.MarketInfo;
import com.iamberry.wechat.core.entity.statictics.SalesmanInfo;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.giftCard.AgentService;
import com.iamberry.wechat.face.statistics.AdminStatisticsService;
import com.iamberry.wechat.face.statistics.StatisticsRelationService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidatorUtil;


/**
 * @description 分销链接 跳转
 * @date  2016-4-26
 */
@Controller
@RequestMapping("/wechat/drp")
public class DrpWeChatHandler {
	
	@Autowired
	private PlaceInfoService placeInfoService;
	@Autowired
	private AdminUtils adminUtils;
	@Autowired
	private ValidatorUtil validatorUtil;
	@Autowired
	private SystemService systemService;
	@Autowired
	private AdminStatisticsService adminStatisticsService;
	@Autowired
	private StatisticsRelationService statisticsRelationService;
	@Autowired
	private AgentService agentService;

	/**
	 * 转发地址跳转
	 * @param response
	 * @param requestion
	 * @param url
	 */
	public void dispatcherLink(HttpServletResponse response,HttpServletRequest requestion,String url){
		url="/WEB-INF/views/wechat/"+url+".html";
		try {
			requestion.getRequestDispatcher(url).forward(requestion,response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 分销首页的跳转
	 * 1.判断是否有商户，有则跳转
	 * 2.没有商户则判断是否有业务员角色，有则跳转
	 * 3.没有商户，没有业务员，则判断是否有付费代理商支付记录;
	 * 		3.1.有支付记录，判断支付状态，已支付则跳转付费代理中心
	 * 		3.1.有支付记录，判断支付状态，待支付则跳转支付页面
	 * 4.没有商户，没有业务员，没有付费代理商支付记录，则进入商城首页
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping("/indexPage")
	public void  index(HttpServletRequest request ,HttpServletResponse response){
		String openid="";
		openid = WechatUtils.getUserBySession(request).getUserOpenid();
		PlaceInfo placeInfo = placeInfoService.getPlaceInfoByOpenId(openid);
		if(placeInfo == null){//没有商户
			SalesmanInfo salesInfo = statisticsRelationService.getRelationByOpenID(openid);
			boolean flag = forwardSalesStatistics(salesInfo, request, response);
			if(!flag){	//没有转发业务员页面 
				dispatcherLink(response,request,"index");
			}
		}else{//有商户
			// 查询发展金牌会员的placeID
    		//int goldPlaceId = systemService.selectOneShopRuleById(206).getRuleNum().intValue();
			
			ApplyPlaceLogs logs = placeInfoService.selectApplyLogsByOpenID(openid);
			if(logs == null || (logs.getApplyStatus() != null && logs.getApplyStatus().intValue() == 3 )){
				//若（未申请过 或被驳回申请）且代理商未完善个人信息  则跳转到完善个人信息页面
				dispatcherLink(response,request,"add_information");
			}else {//进入分销中心
				if(placeInfo.getRoleId() == 51){	//VIP会员
					dispatcherLink(response,request,"fenxiao_center2");
				}else{
					dispatcherLink(response,request,"fenxiao_center");
				}
			}
		}
	}
	
	//提交订单后跳转页面
	@RequestMapping("/playOrderPage")
    public void payOrder(HttpServletResponse response,HttpServletRequest requestion){
		 String productId=requestion.getParameter("productId");
		 if(productId==null || productId.equals("")){
			 productId="12";
		 }
		 dispatcherLink(response,requestion,"fenxiao_clearing");

    }
	
	//支付成功
	@RequestMapping("/PaySuccessPage")
	public void dealOrder(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_pay_win");
    }
	
	/**
	 * 提现申请页面
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/withdrawalsPage")
	 public void getWithdrawals(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_tixian_apply");
    }
	
	/**
	 * 提现申请后跳转页面
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/withdrawalssubmitSuccess")
	 public void submitSuccess(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_apply_submitSuccess");
    }
	
	/**
	 * 分销规则
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/rulePage")
	 public void ruleInfo(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_guize");
    }
	
	/**
	 * 分销未入账订单列表
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/UnIncomeOrderList")
	 public void UnIncomeOrderList(HttpServletResponse response,HttpServletRequest requestion){
		//dispatcherLink(response,requestion,"fenxiao_order_list");
		dispatcherLink(response,requestion,"fenxiao_to_transfer_accounts_list");
    }
	/**
	 * 分销未入账订单列表
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/UnIncomeOrderList2")
	 public void UnIncomeOrderList2(HttpServletResponse response,HttpServletRequest requestion){
		//dispatcherLink(response,requestion,"fenxiao_order_list");
		dispatcherLink(response,requestion,"fenxiao_to_accounts_list");
    }
	/**
	 * 已销售台数（美容师）
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/salesNumbers")
	 public void salesNumbers(HttpServletResponse response,HttpServletRequest requestion){
		//dispatcherLink(response,requestion,"fenxiao_order_list");
		dispatcherLink(response,requestion,"fenxiao_to_accounts_list2");
    }
	
	/**
	 * 终端用户的页面
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("xialianUser")
	 public void drpterminalUser(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_next_user_list");
    }
	/**
	 * 终端用户的页面，分销商下线是会员或者微代理的
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("xialianUser2")
	 public void terminalUser(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_next_user_list2");
    }
	
	/**
	 * 门店终端用户的页面    需要带门店的openid
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("MendianTerminalUser")
	 public void terminalUser2(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_mendian_next_user_list");
    }

	/*合作商页面的*/
	@RequestMapping("cooperativeUser")
	 public void cooperativeUser(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_cooperative_business_list");
    }
	
	//门店统计页
	@RequestMapping("mendianUser")
	 public void mendianUser(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_store_list");
    }

	//分销的二维码
	@RequestMapping("/share2WM")
	 public void share2WM(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_2wm");
    }

	//历史提现记录
	@RequestMapping("/withdrawalsList")
	public void withdrawalsList(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_tixian_log");
	}
	
	//订单查询--分状态列表
	@RequestMapping("/ordersList")
	public void ordersList(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"fenxiao_fahuo_log");
	}
	
	/**
	 * 联系我们链接
	 * @param response
	 * @param requestion
	 */
	@RequestMapping("/contactUs")
	public void contactUs(HttpServletResponse response,HttpServletRequest requestion){
		dispatcherLink(response,requestion,"contact_us");
	}
	
	/**
	 * 判断处理当前代理商是否需要完善信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/handler_place", method = RequestMethod.POST)
	@ResponseBody
	public ResponseJson handlerPlace(HttpServletRequest request) {
		ResponseJson json = new ResponseJson();
		String openid = null;
		openid = WechatUtils.getUserBySession(request).getUserOpenid();
		json = placeInfoService.handlerPlaceInfo(openid);
		
		// 产生token
		if (json.getReturnCode() != 200) {
			json.addResponseKeyValue("addApplyToken", adminUtils.saveTokenToSession("addApplyToken", request.getSession()));
		}
		return json;
	}
	
	/**
	 * 添加申请完善的记录
	 * @param logs
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/add_apply/{token}", method = RequestMethod.POST)
	public ResponseJson addApplyLogs(ApplyPlaceLogs logs, @PathVariable("token")String token, HttpServletRequest request) {
		ResponseJson json = new ResponseJson();
		String openid = null;
		openid = WechatUtils.getUserBySession(request).getUserOpenid();
		
		// 校验token
		if (!adminUtils.checkToken(token, "addApplyToken", request.getSession())) {
			json.setReturnCode(401);
			json.addResponseKeyValue("token失效，请刷新重试!");
			return json;
		}
		
		// 校验数据
//		if (validatorUtil.validatorObject(logs)) {
//			json.setReturnCode(404);
//			json.addResponseKeyValue("数据填写不规范，请充填!");
//			return json;
//		}
		
		logs.setApplyOpenID(openid);	// 填写openID
		
		// 完成业务逻辑
		json = placeInfoService.addApplyPlaceLogs(logs);
		return json;
	}
	
	/**
	 * 跳转个人信息页面
	 * 2016年10月10日
	 * @param req
	 * @param res
	 */
	@RequestMapping("/placeInfo_detail")
	public void toPlaceInfoDetail(HttpServletRequest req,HttpServletResponse res){
		dispatcherLink(res, req, "personal_information");
	}
	
	/**
	 * 跳转个人信息修改页面
	 * 2016年10月10日
	 * @param req
	 * @param res
	 */
	@RequestMapping("/placeInfo_update")
	public void toUpdatePlaceInfo(HttpServletRequest req,HttpServletResponse res){
		dispatcherLink(res, req, "add_information");
	}
	
	/**
	 * 按角色查询各商户售出的商品台数
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectSalesSum")
	public ResultMsg selectSalesSum(HttpServletRequest request, 
			@RequestParam(value= "pageSize",defaultValue= "6" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO) {
		ResultMsg msg = new ResultMsg();
		Map<String,Object> map = new HashMap<String,Object>();
		MarketInfo marketInfo = new MarketInfo();
		marketInfo.getPage().setPageNumber(pageNO);
		marketInfo.getPage().setPageSize(pageSize);
		marketInfo.getPage().initRecordBegin();
		List<MarketInfo> marketList = adminStatisticsService.selectPlaceSalesSum(marketInfo);
		List<MarketInfo> placeList = adminStatisticsService.selectPlaceList();
		Integer salesSum = adminStatisticsService.selectSalesSum();
		if (null != marketList && marketList.size() > 0 && null != placeList && placeList.size() > 0) {
			for (MarketInfo moneyInfo : marketList) {
				for (MarketInfo placeInfo : placeList) {
					if (null != moneyInfo.getPlaceId() && !"".equals(moneyInfo.getPlaceId()) 
							&& null != placeInfo.getPlaceId() && !"".equals(placeInfo.getPlaceId()) 
							&& moneyInfo.getPlaceId().toString().equals(placeInfo.getPlaceId().toString())) {
						moneyInfo.setProvinceName(placeInfo.getProvinceName());
						moneyInfo.setCityName(placeInfo.getCityName());
						moneyInfo.setStoreName(placeInfo.getStoreName());
					}
				}
			}
		}
		map.put("marketList", marketList);
		map.put("marketCount", adminStatisticsService.selectPlaceSalesSumCount(marketInfo));
		map.put("salesSum", salesSum);
		msg.setData(map);
		msg.setStatus(true);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		return msg;
	}
	
	/**
	 * 业务员转发	若转发则返回true	否则返回false
	 * 2016年12月28日
	 * @param salesInfo
	 * @param request
	 * @param response
	 */
	private boolean forwardSalesStatistics(SalesmanInfo salesInfo,
			HttpServletRequest request,HttpServletResponse response){
		boolean flag = false;
		if(salesInfo == null || salesInfo.getsRoleId() == null ||
				salesInfo.getsStatus() == null || salesInfo.getsStatus().intValue() != 1){
			return flag;
		}
		try {
			if(salesInfo.getsRoleId().intValue() == 1){	//	普通业务员跳转页面
				request.getRequestDispatcher(NameUtils.getConfig("WECHAT_GO_SALES_MANAGER")).forward(request,response);
				flag = true;
			}else if(salesInfo.getsRoleId().intValue() == 2){	//管理员跳转页面
				request.getRequestDispatcher(NameUtils.getConfig("WECHAT_GO_TOTAL_MANAGER")).forward(request,response);
				flag = true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
		return flag;
	}
}
